2 * Copyright 2001-2007 Adrian Thurston <thurston@complang.org>
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>
43 #define S_IRUSR _S_IREAD
44 #define S_IWUSR _S_IWRITE
52 /* Parameters and output. */
58 #include "inputdata.h"
69 using std::streamsize;
71 /* Controls minimization. */
72 MinimizeLevel minimizeLevel = MinimizePartition2;
73 MinimizeOpt minimizeOpt = MinimizeMostOps;
75 /* Graphviz dot file generation. */
76 const 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 /* Target language and output style. */
85 CodeStyleEnum codeStyle = GenTables;
87 int numSplitPartitions = 0;
88 bool noLineDirectives = false;
90 bool displayPrintables = false;
91 bool graphvizDone = false;
93 /* Target ruby impl */
94 RubyImplEnum rubyImpl = MRI;
96 ArgsVector includePaths;
98 istream *inStream = 0;
99 ostream *outStream = 0;
100 output_filter *outFilter = 0;
101 const char *outputFileName = 0;
103 /* Print a summary of the options. */
107 "usage: ragel [options] file\n"
109 " -h, -H, -?, --help Print this usage and exit\n"
110 " -v, --version Print version information and exit\n"
111 " -o <file> Write output to <file>\n"
112 " -s Print some statistics on stderr\n"
113 " -d Do not remove duplicates from action lists\n"
114 " -I <dir> Add <dir> to the list of directories to search\n"
115 " for included an imported files\n"
116 "error reporting format:\n"
117 " --error-format=gnu file:line:column: message (default)\n"
118 " --error-format=msvc file(line,column): message\n"
119 "fsm minimization:\n"
120 " -n Do not perform minimization\n"
121 " -m Minimize at the end of the compilation\n"
122 " -l Minimize after most operations (default)\n"
123 " -e Minimize after every operation\n"
125 " -x Run the frontend only: emit XML intermediate format\n"
126 " -V Generate a dot file for Graphviz\n"
127 " -p Display printable characters on labels\n"
128 " -S <spec> FSM specification to output (for graphviz output)\n"
129 " -M <machine> Machine definition/instantiation to output (for graphviz output)\n"
131 " -C The host language is C, C++, Obj-C or Obj-C++ (default)\n"
132 " -D The host language is D\n"
133 " -J The host language is Java\n"
134 " -R The host language is Ruby\n"
135 " -A The host language is C#\n"
136 "line direcives: (C/D/C# only)\n"
137 " -L Inhibit writing of #line directives\n"
138 "code style: (C/Ruby/C# only)\n"
139 " -T0 Table driven FSM (default)\n"
140 " -T1 Faster table driven FSM\n"
141 " -F0 Flat table driven FSM\n"
142 " -F1 Faster flat table-driven FSM\n"
143 "code style: (C/C# only)\n"
144 " -G0 Goto-driven FSM\n"
145 " -G1 Faster goto-driven FSM\n"
146 "code style: (C only)\n"
147 " -G2 Really fast goto-driven FSM\n"
148 " -P<N> N-Way Split really fast goto-driven FSM\n"
154 /* Print version information and exit. */
157 cout << "Ragel State Machine Compiler version " VERSION << " " PUBDATE << endl <<
158 "Copyright (c) 2001-2008 by Adrian Thurston" << endl;
162 /* Error reporting format. */
163 ErrorFormat errorFormat = ErrorFormatGNU;
165 InputLoc makeInputLoc( const char *fileName, int line, int col)
167 InputLoc loc = { fileName, line, col };
171 ostream &operator<<( ostream &out, const InputLoc &loc )
173 assert( loc.fileName != 0 );
174 switch ( errorFormat ) {
175 case ErrorFormatMSVC:
176 out << loc.fileName << "(" << loc.line;
178 out << "," << loc.col;
183 out << loc.fileName << ":" << loc.line;
185 out << ":" << loc.col;
191 /* Total error count. */
192 int gblErrorCount = 0;
194 /* Print the opening to a warning in the input, then return the error ostream. */
195 ostream &warning( const InputLoc &loc )
197 cerr << loc << ": warning: ";
201 /* Print the opening to a program error, then return the error stream. */
205 cerr << PROGNAME ": ";
209 ostream &error( const InputLoc &loc )
216 void escapeLineDirectivePath( std::ostream &out, char *path )
218 for ( char *pc = path; *pc != 0; pc++ ) {
226 void processArgs( int argc, const char **argv, const char *&inputFileName )
228 ParamCheck pc("xo:dnmleabjkS:M:I:CDJRAvHh?-:sT:F:G:P:LpV", argc, argv);
230 /* FIXME: Need to check code styles VS langauge. */
232 while ( pc.check() ) {
233 switch ( pc.state ) {
234 case ParamCheck::match:
235 switch ( pc.parameter ) {
246 if ( *pc.paramArg == 0 )
247 error() << "a zero length output file name was given" << endl;
248 else if ( outputFileName != 0 )
249 error() << "more than one output file name was given" << endl;
251 /* Ok, remember the output file name. */
252 outputFileName = pc.paramArg;
256 /* Flag for turning off duplicate action removal. */
258 wantDupsRemoved = false;
261 /* Minimization, mostly hidden options. */
263 minimizeOpt = MinimizeNone;
266 minimizeOpt = MinimizeEnd;
269 minimizeOpt = MinimizeMostOps;
272 minimizeOpt = MinimizeEveryOp;
275 minimizeLevel = MinimizeApprox;
278 minimizeLevel = MinimizeStable;
281 minimizeLevel = MinimizePartition1;
284 minimizeLevel = MinimizePartition2;
289 if ( *pc.paramArg == 0 )
290 error() << "please specify an argument to -S" << endl;
291 else if ( machineSpec != 0 )
292 error() << "more than one -S argument was given" << endl;
294 /* Ok, remember the path to the machine to generate. */
295 machineSpec = pc.paramArg;
301 if ( *pc.paramArg == 0 )
302 error() << "please specify an argument to -M" << endl;
303 else if ( machineName != 0 )
304 error() << "more than one -M argument was given" << endl;
306 /* Ok, remember the machine name to generate. */
307 machineName = pc.paramArg;
312 if ( *pc.paramArg == 0 )
313 error() << "please specify an argument to -I" << endl;
315 includePaths.append( pc.paramArg );
319 /* Host language types. */
321 hostLang = &hostLangC;
324 hostLang = &hostLangD;
327 hostLang = &hostLangJava;
330 hostLang = &hostLangRuby;
333 hostLang = &hostLangCSharp;
336 /* Version and help. */
340 case 'H': case 'h': case '?':
344 printStatistics = true;
347 char *eq = strchr( pc.paramArg, '=' );
352 if ( strcmp( pc.paramArg, "help" ) == 0 )
354 else if ( strcmp( pc.paramArg, "version" ) == 0 )
356 else if ( strcmp( pc.paramArg, "error-format" ) == 0 ) {
358 error() << "expecting '=value' for error-format" << endl;
359 else if ( strcmp( eq, "gnu" ) == 0 )
360 errorFormat = ErrorFormatGNU;
361 else if ( strcmp( eq, "msvc" ) == 0 )
362 errorFormat = ErrorFormatMSVC;
364 error() << "invalid value for error-format" << endl;
366 else if ( strcmp( pc.paramArg, "rbx" ) == 0 )
369 error() << "--" << pc.paramArg <<
370 " is an invalid argument" << endl;
375 /* Passthrough args. */
377 if ( pc.paramArg[0] == '0' )
378 codeStyle = GenTables;
379 else if ( pc.paramArg[0] == '1' )
380 codeStyle = GenFTables;
382 error() << "-T" << pc.paramArg[0] <<
383 " is an invalid argument" << endl;
388 if ( pc.paramArg[0] == '0' )
390 else if ( pc.paramArg[0] == '1' )
391 codeStyle = GenFFlat;
393 error() << "-F" << pc.paramArg[0] <<
394 " is an invalid argument" << endl;
399 if ( pc.paramArg[0] == '0' )
401 else if ( pc.paramArg[0] == '1' )
402 codeStyle = GenFGoto;
403 else if ( pc.paramArg[0] == '2' )
404 codeStyle = GenIpGoto;
406 error() << "-G" << pc.paramArg[0] <<
407 " is an invalid argument" << endl;
412 codeStyle = GenSplit;
413 numSplitPartitions = atoi( pc.paramArg );
417 displayPrintables = true;
421 noLineDirectives = true;
426 case ParamCheck::invalid:
427 error() << "-" << pc.parameter << " is an invalid argument" << endl;
430 case ParamCheck::noparam:
431 /* It is interpreted as an input file. */
432 if ( *pc.curArg == 0 )
433 error() << "a zero length input file name was given" << endl;
434 else if ( inputFileName != 0 )
435 error() << "more than one input file name was given" << endl;
437 /* OK, Remember the filename. */
438 inputFileName = pc.curArg;
445 void process( const char *inputFileName )
447 bool wantComplete = true;
448 bool outputActive = true;
450 /* Open the input file for reading. */
451 assert( inputFileName != 0 );
452 ifstream *inFile = new ifstream( inputFileName );
453 if ( ! inFile->is_open() )
454 error() << "could not open " << inputFileName << " for reading" << endp;
456 /* Used for just a few things. */
457 std::ostringstream hostData;
459 /* Make the first input item. */
460 InputItem *firstInputItem = new InputItem;
461 firstInputItem->type = InputItem::HostData;
462 firstInputItem->loc.line = 1;
463 firstInputItem->loc.col = 1;
464 inputItems.append( firstInputItem );
466 Scanner scanner( inputFileName, *inFile, 0, 0, 0, false );
469 /* Finished, final check for errors.. */
470 if ( gblErrorCount > 0 )
473 /* Now send EOF to all parsers. */
474 terminateAllParsers();
476 /* Finished, final check for errors.. */
477 if ( gblErrorCount > 0 )
480 /* Bail on above error. */
481 if ( gblErrorCount > 0 )
484 /* Locate the backend program */
486 wantComplete = false;
487 outputActive = false;
490 InputData inputData( inputFileName, outputActive, wantComplete );
492 /* Compiles machines. */
493 inputData.prepareMachineGen();
495 if ( gblErrorCount > 0 )
498 inputData.openOutput();
500 /* Generates the reduced machine, which we use to write output. */
501 inputData.generateReduced();
503 if ( gblErrorCount > 0 )
506 inputData.writeOutput();
508 /* Close the input and the intermediate file. */
511 /* Bail on above error. */
512 if ( gblErrorCount > 0 )
515 /* If writing to a file, delete the ostream, causing it to flush.
516 * Standard out is flushed automatically. */
517 if ( outputFileName != 0 ) {
522 /* Finished, final check for errors.. */
523 if ( gblErrorCount > 0 ) {
524 /* If we opened an output file, remove it. */
525 if ( outputFileName != 0 )
526 unlink( outputFileName );
531 char *makeIntermedTemplate( const char *baseFileName )
534 const char *templ = "ragel-XXXXXX.xml";
535 char *lastSlash = strrchr( baseFileName, '/' );
536 if ( lastSlash == 0 ) {
537 result = new char[strlen(templ)+1];
538 strcpy( result, templ );
541 int baseLen = lastSlash - baseFileName + 1;
542 result = new char[baseLen + strlen(templ) + 1];
543 memcpy( result, baseFileName, baseLen );
544 strcpy( result+baseLen, templ );
549 const char *openIntermed( const char *inputFileName, const char *outputFileName )
552 const char *result = 0;
554 /* Which filename do we use as the base? */
555 const char *baseFileName = outputFileName != 0 ? outputFileName : inputFileName;
557 /* The template for the intermediate file name. */
558 const char *intermedFileName = makeIntermedTemplate( baseFileName );
560 /* Randomize the name and try to open. */
561 char fnChars[] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
562 char *firstX = strrchr( intermedFileName, 'X' ) - 5;
563 for ( int tries = 0; tries < 20; tries++ ) {
564 /* Choose a random name. */
565 for ( int x = 0; x < 6; x++ )
566 firstX[x] = fnChars[rand() % 52];
568 /* Try to open the file. */
569 int fd = ::open( intermedFileName, O_WRONLY|O_EXCL|O_CREAT, S_IRUSR|S_IWUSR );
572 /* Success. Close the file immediately and return the name for use
573 * by the child processes. */
575 result = intermedFileName;
579 if ( errno == EACCES ) {
580 error() << "failed to open temp file " << intermedFileName <<
581 ", access denied" << endp;
586 error() << "abnormal error: cannot find unique name for temp file" << endp;
593 /* Main, process args and call yyparse to start scanning input. */
594 int main( int argc, const char **argv )
596 const char *inputFileName = 0;
597 processArgs( argc, argv, inputFileName );
600 /* If -M or -S are given and we're not generating a dot file then invoke
601 * the frontend. These options are not useful with code generators. */
602 if ( machineName != 0 || machineSpec != 0 ) {
607 /* Require an input file. If we use standard in then we won't have a file
608 * name on which to base the output. */
609 if ( inputFileName == 0 )
610 error() << "no input file given" << endl;
612 /* Bail on argument processing errors. */
613 if ( gblErrorCount > 0 )
616 /* Make sure we are not writing to the same file as the input file. */
617 if ( inputFileName != 0 && outputFileName != 0 &&
618 strcmp( inputFileName, outputFileName ) == 0 )
620 error() << "output file \"" << outputFileName <<
621 "\" is the same as the input file" << endp;
624 process( inputFileName );
626 /* Clean up the intermediate. */