Track the entire include history of a parser state to prevent duplicates.
[external/ragel.git] / ragel / rlscan.rl
1 /*
2  *  Copyright 2006-2007 Adrian Thurston <thurston@cs.queensu.ca>
3  */
4
5 /*  This file is part of Ragel.
6  *
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.
11  * 
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.
16  * 
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 
20  */
21
22 #include <iostream>
23 #include <fstream>
24 #include <string.h>
25
26 #include "ragel.h"
27 #include "rlscan.h"
28
29 //#define LOG_TOKENS
30
31 using std::ifstream;
32 using std::istream;
33 using std::ostream;
34 using std::cout;
35 using std::cerr;
36 using std::endl;
37
38 enum InlineBlockType
39 {
40         CurlyDelimited,
41         SemiTerminated
42 };
43
44 #ifdef _WIN32
45 #define PATH_SEP '\\'
46 #else
47 #define PATH_SEP '/'
48 #endif
49
50
51 /*
52  * The Scanner for Importing
53  */
54
55 %%{
56         machine inline_token_scan;
57         alphtype int;
58         access tok_;
59
60         # Import scanner tokens.
61         import "rlparse.h"; 
62
63         main := |*
64                 # Define of number.
65                 IMP_Define IMP_Word IMP_UInt => { 
66                         int base = tok_ts - token_data;
67                         int nameOff = 1;
68                         int numOff = 2;
69
70                         directToParser( inclToParser, fileName, line, column, TK_Word, 
71                                         token_strings[base+nameOff], token_lens[base+nameOff] );
72                         directToParser( inclToParser, fileName, line, column, '=', 0, 0 );
73                         directToParser( inclToParser, fileName, line, column, TK_UInt,
74                                         token_strings[base+numOff], token_lens[base+numOff] );
75                         directToParser( inclToParser, fileName, line, column, ';', 0, 0 );
76                 };
77
78                 # Assignment of number.
79                 IMP_Word '=' IMP_UInt => { 
80                         int base = tok_ts - token_data;
81                         int nameOff = 0;
82                         int numOff = 2;
83
84                         directToParser( inclToParser, fileName, line, column, TK_Word, 
85                                         token_strings[base+nameOff], token_lens[base+nameOff] );
86                         directToParser( inclToParser, fileName, line, column, '=', 0, 0 );
87                         directToParser( inclToParser, fileName, line, column, TK_UInt,
88                                         token_strings[base+numOff], token_lens[base+numOff] );
89                         directToParser( inclToParser, fileName, line, column, ';', 0, 0 );
90                 };
91
92                 # Define of literal.
93                 IMP_Define IMP_Word IMP_Literal => { 
94                         int base = tok_ts - token_data;
95                         int nameOff = 1;
96                         int litOff = 2;
97
98                         directToParser( inclToParser, fileName, line, column, TK_Word, 
99                                         token_strings[base+nameOff], token_lens[base+nameOff] );
100                         directToParser( inclToParser, fileName, line, column, '=', 0, 0 );
101                         directToParser( inclToParser, fileName, line, column, TK_Literal,
102                                         token_strings[base+litOff], token_lens[base+litOff] );
103                         directToParser( inclToParser, fileName, line, column, ';', 0, 0 );
104                 };
105
106                 # Assignment of literal.
107                 IMP_Word '=' IMP_Literal => { 
108                         int base = tok_ts - token_data;
109                         int nameOff = 0;
110                         int litOff = 2;
111
112                         directToParser( inclToParser, fileName, line, column, TK_Word, 
113                                         token_strings[base+nameOff], token_lens[base+nameOff] );
114                         directToParser( inclToParser, fileName, line, column, '=', 0, 0 );
115                         directToParser( inclToParser, fileName, line, column, TK_Literal,
116                                         token_strings[base+litOff], token_lens[base+litOff] );
117                         directToParser( inclToParser, fileName, line, column, ';', 0, 0 );
118                 };
119
120                 # Catch everything else.
121                 any;
122         *|;
123 }%%
124
125 %% write data;
126
127 void Scanner::flushImport()
128 {
129         int *p = token_data;
130         int *pe = token_data + cur_token;
131         int *eof = 0;
132
133         %%{
134                 machine inline_token_scan;
135                 write init;
136                 write exec;
137         }%%
138
139         if ( tok_ts == 0 )
140                 cur_token = 0;
141         else {
142                 cur_token = pe - tok_ts;
143                 int ts_offset = tok_ts - token_data;
144                 memmove( token_data, token_data+ts_offset, cur_token*sizeof(token_data[0]) );
145                 memmove( token_strings, token_strings+ts_offset, cur_token*sizeof(token_strings[0]) );
146                 memmove( token_lens, token_lens+ts_offset, cur_token*sizeof(token_lens[0]) );
147         }
148 }
149
150 void Scanner::directToParser( Parser *toParser, char *tokFileName, int tokLine, 
151                 int tokColumn, int type, char *tokdata, int toklen )
152 {
153         InputLoc loc;
154
155         #ifdef LOG_TOKENS
156         cerr << "scanner:" << tokLine << ":" << tokColumn << 
157                         ": sending token to the parser " << Parser_lelNames[type];
158         cerr << " " << toklen;
159         if ( tokdata != 0 )
160                 cerr << " " << tokdata;
161         cerr << endl;
162         #endif
163
164         loc.fileName = tokFileName;
165         loc.line = tokLine;
166         loc.col = tokColumn;
167
168         toParser->token( loc, type, tokdata, toklen );
169 }
170
171 void Scanner::importToken( int token, char *start, char *end )
172 {
173         if ( cur_token == max_tokens )
174                 flushImport();
175
176         token_data[cur_token] = token;
177         if ( start == 0 ) {
178                 token_strings[cur_token] = 0;
179                 token_lens[cur_token] = 0;
180         }
181         else {
182                 int toklen = end-start;
183                 token_lens[cur_token] = toklen;
184                 token_strings[cur_token] = new char[toklen+1];
185                 memcpy( token_strings[cur_token], start, toklen );
186                 token_strings[cur_token][toklen] = 0;
187         }
188         cur_token++;
189 }
190
191 void Scanner::pass( int token, char *start, char *end )
192 {
193         if ( importMachines )
194                 importToken( token, start, end );
195         pass();
196 }
197
198 void Scanner::pass()
199 {
200         updateCol();
201
202         /* If no errors and we are at the bottom of the include stack (the
203          * source file listed on the command line) then write out the data. */
204         if ( includeDepth == 0 && machineSpec == 0 && machineName == 0 )
205                 xmlEscapeHost( output, ts, te-ts );
206 }
207
208 /*
209  * The scanner for processing sections, includes, imports, etc.
210  */
211
212 %%{
213         machine section_parse;
214         alphtype int;
215         write data;
216 }%%
217
218
219 void Scanner::init( )
220 {
221         %% write init;
222 }
223
224 bool Scanner::active()
225 {
226         if ( ignoreSection )
227                 return false;
228
229         if ( parser == 0 && ! parserExistsError ) {
230                 scan_error() << "this specification has no name, nor does any previous"
231                         " specification" << endl;
232                 parserExistsError = true;
233         }
234
235         if ( parser == 0 )
236                 return false;
237
238         return true;
239 }
240
241 ostream &Scanner::scan_error()
242 {
243         /* Maintain the error count. */
244         gblErrorCount += 1;
245         cerr << makeInputLoc( fileName, line, column ) << ": ";
246         return cerr;
247 }
248
249 bool Scanner::duplicateInclude( char *inclFileName, char *inclSectionName )
250 {
251         for ( IncludeHistory::Iter hi = parser->includeHistory; hi.lte(); hi++ ) {
252                 if ( strcmp( hi->fileName, inclFileName ) == 0 &&
253                                 strcmp( hi->sectionName, inclSectionName ) == 0 )
254                 {
255                         return true;
256                 }
257         }
258         return false;   
259 }
260
261 void Scanner::updateCol()
262 {
263         char *from = lastnl;
264         if ( from == 0 )
265                 from = ts;
266         //cerr << "adding " << te - from << " to column" << endl;
267         column += te - from;
268         lastnl = 0;
269 }
270
271 void Scanner::handleMachine()
272 {
273         /* Assign a name to the machine. */
274         char *machine = word;
275
276         if ( !importMachines && inclSectionTarg == 0 ) {
277                 ignoreSection = false;
278
279                 ParserDictEl *pdEl = parserDict.find( machine );
280                 if ( pdEl == 0 ) {
281                         pdEl = new ParserDictEl( machine );
282                         pdEl->value = new Parser( fileName, machine, sectionLoc );
283                         pdEl->value->init();
284                         parserDict.insert( pdEl );
285                 }
286
287                 parser = pdEl->value;
288         }
289         else if ( !importMachines && strcmp( inclSectionTarg, machine ) == 0 ) {
290                 /* found include target */
291                 ignoreSection = false;
292                 parser = inclToParser;
293         }
294         else {
295                 /* ignoring section */
296                 ignoreSection = true;
297                 parser = 0;
298         }
299 }
300
301 void Scanner::handleInclude()
302 {
303         if ( active() ) {
304                 char *inclSectionName = word;
305                 char **includeChecks = 0;
306
307                 /* Implement defaults for the input file and section name. */
308                 if ( inclSectionName == 0 )
309                         inclSectionName = parser->sectionName;
310
311                 if ( lit != 0 )
312                         includeChecks = makeIncludePathChecks( fileName, lit, lit_len );
313                 else {
314                         char *test = new char[strlen(fileName)+1];
315                         strcpy( test, fileName );
316
317                         includeChecks = new char*[2];
318
319                         includeChecks[0] = test;
320                         includeChecks[1] = 0;
321                 }
322
323                 long found = 0;
324                 ifstream *inFile = tryOpenInclude( includeChecks, found );
325                 if ( inFile == 0 ) {
326                         scan_error() << "include: failed to locate file" << endl;
327                         char **tried = includeChecks;
328                         while ( *tried != 0 )
329                                 scan_error() << "include: attempted: \"" << *tried++ << '\"' << endl;
330                 }
331                 else {
332                         /* Don't include anything that's already been included. */
333                         if ( !duplicateInclude( includeChecks[found], inclSectionName ) ) {
334                                 parser->includeHistory.append( IncludeHistoryItem( 
335                                                 includeChecks[found], inclSectionName ) );
336
337                                 Scanner scanner( includeChecks[found], *inFile, output, parser,
338                                                 inclSectionName, includeDepth+1, false );
339                                 scanner.do_scan( );
340                                 delete inFile;
341                         }
342                 }
343         }
344 }
345
346 void Scanner::handleImport()
347 {
348         if ( active() ) {
349                 char **importChecks = makeIncludePathChecks( fileName, lit, lit_len );
350
351                 /* Open the input file for reading. */
352                 long found = 0;
353                 ifstream *inFile = tryOpenInclude( importChecks, found );
354                 if ( inFile == 0 ) {
355                         scan_error() << "import: could not open import file " <<
356                                         "for reading" << endl;
357                         char **tried = importChecks;
358                         while ( *tried != 0 )
359                                 scan_error() << "import: attempted: \"" << *tried++ << '\"' << endl;
360                 }
361
362                 Scanner scanner( importChecks[found], *inFile, output, parser,
363                                 0, includeDepth+1, true );
364                 scanner.do_scan( );
365                 scanner.importToken( 0, 0, 0 );
366                 scanner.flushImport();
367                 delete inFile;
368         }
369 }
370
371 %%{
372         machine section_parse;
373
374         # Need the defines representing tokens.
375         import "rlparse.h"; 
376
377         action clear_words { word = lit = 0; word_len = lit_len = 0; }
378         action store_word { word = tokdata; word_len = toklen; }
379         action store_lit { lit = tokdata; lit_len = toklen; }
380
381         action mach_err { scan_error() << "bad machine statement" << endl; }
382         action incl_err { scan_error() << "bad include statement" << endl; }
383         action import_err { scan_error() << "bad import statement" << endl; }
384         action write_err { scan_error() << "bad write statement" << endl; }
385
386         action handle_machine { handleMachine(); }
387         action handle_include { handleInclude(); }
388         action handle_import { handleImport(); }
389
390         machine_stmt =
391                 ( KW_Machine TK_Word @store_word ';' ) @handle_machine
392                 <>err mach_err <>eof mach_err;
393
394         include_names = (
395                 TK_Word @store_word ( TK_Literal @store_lit )? |
396                 TK_Literal @store_lit
397         ) >clear_words;
398
399         include_stmt =
400                 ( KW_Include include_names ';' ) @handle_include
401                 <>err incl_err <>eof incl_err;
402
403         import_stmt =
404                 ( KW_Import TK_Literal @store_lit ';' ) @handle_import
405                 <>err import_err <>eof import_err;
406
407         action write_command
408         {
409                 if ( active() && machineSpec == 0 && machineName == 0 ) {
410                         output << "<write"
411                                         " def_name=\"" << parser->sectionName << "\""
412                                         " line=\"" << line << "\""
413                                         " col=\"" << column << "\""
414                                         ">";
415                 }
416         }
417
418         action write_arg
419         {
420                 if ( active() && machineSpec == 0 && machineName == 0 )
421                         output << "<arg>" << tokdata << "</arg>";
422         }
423
424         action write_close
425         {
426                 if ( active() && machineSpec == 0 && machineName == 0 )
427                         output << "</write>\n";
428         }
429
430         write_stmt =
431                 ( KW_Write @write_command 
432                 ( TK_Word @write_arg )+ ';' @write_close )
433                 <>err write_err <>eof write_err;
434
435         action handle_token
436         {
437                 /* Send the token off to the parser. */
438                 if ( active() )
439                         directToParser( parser, fileName, line, column, type, tokdata, toklen );
440         }
441
442         # Catch everything else.
443         everything_else = 
444                 ^( KW_Machine | KW_Include | KW_Import | KW_Write ) @handle_token;
445
446         main := ( 
447                 machine_stmt |
448                 include_stmt |
449                 import_stmt |
450                 write_stmt |
451                 everything_else
452         )*;
453 }%%
454
455 void Scanner::token( int type, char c )
456 {
457         token( type, &c, &c + 1 );
458 }
459
460 void Scanner::token( int type )
461 {
462         token( type, 0, 0 );
463 }
464
465 void Scanner::token( int type, char *start, char *end )
466 {
467         char *tokdata = 0;
468         int toklen = 0;
469         if ( start != 0 ) {
470                 toklen = end-start;
471                 tokdata = new char[toklen+1];
472                 memcpy( tokdata, start, toklen );
473                 tokdata[toklen] = 0;
474         }
475
476         processToken( type, tokdata, toklen );
477 }
478
479 void Scanner::processToken( int type, char *tokdata, int toklen )
480 {
481         int *p, *pe, *eof;
482         
483
484         if ( type < 0 )
485                 p = pe = eof = 0;
486         else {
487                 p = &type;
488                 pe = &type + 1;
489                 eof = 0;
490         }
491
492         %%{
493                 machine section_parse;
494                 write exec;
495         }%%
496
497         updateCol();
498
499         /* Record the last token for use in controlling the scan of subsequent
500          * tokens. */
501         lastToken = type;
502 }
503
504 void Scanner::startSection( )
505 {
506         parserExistsError = false;
507
508         if ( includeDepth == 0 ) {
509                 if ( machineSpec == 0 && machineName == 0 )
510                         output << "</host>\n";
511         }
512
513         sectionLoc.fileName = fileName;
514         sectionLoc.line = line;
515         sectionLoc.col = 0;
516 }
517
518 void Scanner::endSection( )
519 {
520         /* Execute the eof actions for the section parser. */
521         processToken( -1, 0, 0 );
522
523         /* Close off the section with the parser. */
524         if ( active() ) {
525                 InputLoc loc;
526                 loc.fileName = fileName;
527                 loc.line = line;
528                 loc.col = 0;
529
530                 parser->token( loc, TK_EndSection, 0, 0 );
531         }
532
533         if ( includeDepth == 0 ) {
534                 if ( machineSpec == 0 && machineName == 0 ) {
535                         /* The end section may include a newline on the end, so
536                          * we use the last line, which will count the newline. */
537                         output << "<host line=\"" << line << "\">";
538                 }
539         }
540 }
541
542 bool isAbsolutePath( const char *path )
543 {
544 #ifdef _WIN32
545         return isalpha( path[0] ) && path[1] == ':' && path[2] == '\\';
546 #else
547         return path[0] == '/';
548 #endif
549 }
550
551 char **Scanner::makeIncludePathChecks( char *thisFileName, char *fileName, int fnlen )
552 {
553         char **checks = new char*[2];
554         long nextCheck = 0;
555
556         bool caseInsensitive = false;
557         long length = 0;
558         char *data = prepareLitString( InputLoc(), fileName, fnlen, 
559                         length, caseInsensitive );
560
561         /* Absolute path? */
562         if ( isAbsolutePath( data ) )
563                 checks[nextCheck++] = data;
564         else {
565                 /* Search from the the location of the current file. */
566                 const char *lastSlash = strrchr( thisFileName, PATH_SEP );
567                 if ( lastSlash == 0 )
568                         checks[nextCheck++] = data;
569                 else {
570                         long givenPathLen = (lastSlash - thisFileName) + 1;
571                         long checklen = givenPathLen + length;
572                         char *check = new char[checklen+1];
573                         memcpy( check, thisFileName, givenPathLen );
574                         memcpy( check+givenPathLen, data, length );
575                         check[checklen] = 0;
576                         checks[nextCheck++] = check;
577                 }
578
579                 /* Search from the include paths given on the command line. */
580                 for ( ArgsVector::Iter incp = includePaths; incp.lte(); incp++ ) {
581                         long pathLen = strlen( *incp );
582                         long checkLen = pathLen + 1 + length;
583                         char *check = new char[checkLen+1];
584                         memcpy( check, *incp, pathLen );
585                         check[pathLen] = PATH_SEP;
586                         memcpy( check+pathLen+1, data, length );
587                         check[checkLen] = 0;
588                         checks[nextCheck++] = check;
589                 }
590         }
591
592         checks[nextCheck] = 0;
593         return checks;
594 }
595
596 ifstream *Scanner::tryOpenInclude( char **pathChecks, long &found )
597 {
598         char **check = pathChecks;
599         ifstream *inFile = new ifstream;
600         
601         while ( *check != 0 ) {
602                 inFile->open( *check );
603                 if ( inFile->is_open() ) {
604                         found = check - pathChecks;
605                         return inFile;
606                 }
607                 check += 1;
608         }
609
610         found = -1;
611         delete inFile;
612         return 0;
613 }
614
615 %%{
616         machine rlscan;
617
618         # This is sent by the driver code.
619         EOF = 0;
620         
621         action inc_nl { 
622                 lastnl = p; 
623                 column = 0;
624                 line++;
625         }
626         NL = '\n' @inc_nl;
627
628         # Identifiers, numbers, commetns, and other common things.
629         ident = ( alpha | '_' ) ( alpha |digit |'_' )*;
630         number = digit+;
631         hex_number = '0x' [0-9a-fA-F]+;
632
633         c_comment = 
634                 '/*' ( any | NL )* :>> '*/';
635
636         cpp_comment =
637                 '//' [^\n]* NL;
638
639         c_cpp_comment = c_comment | cpp_comment;
640
641         ruby_comment = '#' [^\n]* NL;
642
643         # These literal forms are common to host code and ragel.
644         s_literal = "'" ([^'\\] | NL | '\\' (any | NL))* "'";
645         d_literal = '"' ([^"\\] | NL | '\\' (any | NL))* '"';
646         host_re_literal = '/' ([^/\\] | NL | '\\' (any | NL))* '/';
647
648         whitespace = [ \t] | NL;
649         pound_comment = '#' [^\n]* NL;
650
651         # An inline block of code for Ruby.
652         inline_code_ruby := |*
653                 # Inline expression keywords.
654                 "fpc" => { token( KW_PChar ); };
655                 "fc" => { token( KW_Char ); };
656                 "fcurs" => { token( KW_CurState ); };
657                 "ftargs" => { token( KW_TargState ); };
658                 "fentry" => { 
659                         whitespaceOn = false; 
660                         token( KW_Entry );
661                 };
662
663                 # Inline statement keywords.
664                 "fhold" => { 
665                         whitespaceOn = false; 
666                         token( KW_Hold );
667                 };
668                 "fexec" => { token( KW_Exec, 0, 0 ); };
669                 "fgoto" => { 
670                         whitespaceOn = false; 
671                         token( KW_Goto );
672                 };
673                 "fnext" => { 
674                         whitespaceOn = false; 
675                         token( KW_Next );
676                 };
677                 "fcall" => { 
678                         whitespaceOn = false; 
679                         token( KW_Call );
680                 };
681                 "fret" => { 
682                         whitespaceOn = false; 
683                         token( KW_Ret );
684                 };
685                 "fbreak" => { 
686                         whitespaceOn = false; 
687                         token( KW_Break );
688                 };
689
690                 ident => { token( TK_Word, ts, te ); };
691
692                 number => { token( TK_UInt, ts, te ); };
693                 hex_number => { token( TK_Hex, ts, te ); };
694
695                 ( s_literal | d_literal | host_re_literal ) 
696                         => { token( IL_Literal, ts, te ); };
697
698                 whitespace+ => { 
699                         if ( whitespaceOn ) 
700                                 token( IL_WhiteSpace, ts, te );
701                 };
702
703                 ruby_comment => { token( IL_Comment, ts, te ); };
704
705                 "::" => { token( TK_NameSep, ts, te ); };
706
707                 # Some symbols need to go to the parser as with their cardinal value as
708                 # the token type (as opposed to being sent as anonymous symbols)
709                 # because they are part of the sequences which we interpret. The * ) ;
710                 # symbols cause whitespace parsing to come back on. This gets turned
711                 # off by some keywords.
712
713                 ";" => {
714                         whitespaceOn = true;
715                         token( *ts, ts, te );
716                         if ( inlineBlockType == SemiTerminated )
717                                 fret;
718                 };
719
720                 [*)] => { 
721                         whitespaceOn = true;
722                         token( *ts, ts, te );
723                 };
724
725                 [,(] => { token( *ts, ts, te ); };
726
727                 '{' => { 
728                         token( IL_Symbol, ts, te );
729                         curly_count += 1; 
730                 };
731
732                 '}' => { 
733                         if ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {
734                                 /* Inline code block ends. */
735                                 token( '}' );
736                                 fret;
737                         }
738                         else {
739                                 /* Either a semi terminated inline block or only the closing
740                                  * brace of some inner scope, not the block's closing brace. */
741                                 token( IL_Symbol, ts, te );
742                         }
743                 };
744
745                 EOF => {
746                         scan_error() << "unterminated code block" << endl;
747                 };
748
749                 # Send every other character as a symbol.
750                 any => { token( IL_Symbol, ts, te ); };
751         *|;
752
753
754         # An inline block of code for languages other than Ruby.
755         inline_code := |*
756                 # Inline expression keywords.
757                 "fpc" => { token( KW_PChar ); };
758                 "fc" => { token( KW_Char ); };
759                 "fcurs" => { token( KW_CurState ); };
760                 "ftargs" => { token( KW_TargState ); };
761                 "fentry" => { 
762                         whitespaceOn = false; 
763                         token( KW_Entry );
764                 };
765
766                 # Inline statement keywords.
767                 "fhold" => { 
768                         whitespaceOn = false; 
769                         token( KW_Hold );
770                 };
771                 "fexec" => { token( KW_Exec, 0, 0 ); };
772                 "fgoto" => { 
773                         whitespaceOn = false; 
774                         token( KW_Goto );
775                 };
776                 "fnext" => { 
777                         whitespaceOn = false; 
778                         token( KW_Next );
779                 };
780                 "fcall" => { 
781                         whitespaceOn = false; 
782                         token( KW_Call );
783                 };
784                 "fret" => { 
785                         whitespaceOn = false; 
786                         token( KW_Ret );
787                 };
788                 "fbreak" => { 
789                         whitespaceOn = false; 
790                         token( KW_Break );
791                 };
792
793                 ident => { token( TK_Word, ts, te ); };
794
795                 number => { token( TK_UInt, ts, te ); };
796                 hex_number => { token( TK_Hex, ts, te ); };
797
798                 ( s_literal | d_literal ) 
799                         => { token( IL_Literal, ts, te ); };
800
801                 whitespace+ => { 
802                         if ( whitespaceOn ) 
803                                 token( IL_WhiteSpace, ts, te );
804                 };
805
806                 c_cpp_comment => { token( IL_Comment, ts, te ); };
807
808                 "::" => { token( TK_NameSep, ts, te ); };
809
810                 # Some symbols need to go to the parser as with their cardinal value as
811                 # the token type (as opposed to being sent as anonymous symbols)
812                 # because they are part of the sequences which we interpret. The * ) ;
813                 # symbols cause whitespace parsing to come back on. This gets turned
814                 # off by some keywords.
815
816                 ";" => {
817                         whitespaceOn = true;
818                         token( *ts, ts, te );
819                         if ( inlineBlockType == SemiTerminated )
820                                 fret;
821                 };
822
823                 [*)] => { 
824                         whitespaceOn = true;
825                         token( *ts, ts, te );
826                 };
827
828                 [,(] => { token( *ts, ts, te ); };
829
830                 '{' => { 
831                         token( IL_Symbol, ts, te );
832                         curly_count += 1; 
833                 };
834
835                 '}' => { 
836                         if ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {
837                                 /* Inline code block ends. */
838                                 token( '}' );
839                                 fret;
840                         }
841                         else {
842                                 /* Either a semi terminated inline block or only the closing
843                                  * brace of some inner scope, not the block's closing brace. */
844                                 token( IL_Symbol, ts, te );
845                         }
846                 };
847
848                 EOF => {
849                         scan_error() << "unterminated code block" << endl;
850                 };
851
852                 # Send every other character as a symbol.
853                 any => { token( IL_Symbol, ts, te ); };
854         *|;
855
856         or_literal := |*
857                 # Escape sequences in OR expressions.
858                 '\\0' => { token( RE_Char, '\0' ); };
859                 '\\a' => { token( RE_Char, '\a' ); };
860                 '\\b' => { token( RE_Char, '\b' ); };
861                 '\\t' => { token( RE_Char, '\t' ); };
862                 '\\n' => { token( RE_Char, '\n' ); };
863                 '\\v' => { token( RE_Char, '\v' ); };
864                 '\\f' => { token( RE_Char, '\f' ); };
865                 '\\r' => { token( RE_Char, '\r' ); };
866                 '\\\n' => { updateCol(); };
867                 '\\' any => { token( RE_Char, ts+1, te ); };
868
869                 # Range dash in an OR expression.
870                 '-' => { token( RE_Dash, 0, 0 ); };
871
872                 # Terminate an OR expression.
873                 ']'     => { token( RE_SqClose ); fret; };
874
875                 EOF => {
876                         scan_error() << "unterminated OR literal" << endl;
877                 };
878
879                 # Characters in an OR expression.
880                 [^\]] => { token( RE_Char, ts, te ); };
881
882         *|;
883
884         ragel_re_literal := |*
885                 # Escape sequences in regular expressions.
886                 '\\0' => { token( RE_Char, '\0' ); };
887                 '\\a' => { token( RE_Char, '\a' ); };
888                 '\\b' => { token( RE_Char, '\b' ); };
889                 '\\t' => { token( RE_Char, '\t' ); };
890                 '\\n' => { token( RE_Char, '\n' ); };
891                 '\\v' => { token( RE_Char, '\v' ); };
892                 '\\f' => { token( RE_Char, '\f' ); };
893                 '\\r' => { token( RE_Char, '\r' ); };
894                 '\\\n' => { updateCol(); };
895                 '\\' any => { token( RE_Char, ts+1, te ); };
896
897                 # Terminate an OR expression.
898                 '/' [i]? => { 
899                         token( RE_Slash, ts, te ); 
900                         fgoto parser_def;
901                 };
902
903                 # Special characters.
904                 '.' => { token( RE_Dot ); };
905                 '*' => { token( RE_Star ); };
906
907                 '[' => { token( RE_SqOpen ); fcall or_literal; };
908                 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
909
910                 EOF => {
911                         scan_error() << "unterminated regular expression" << endl;
912                 };
913
914                 # Characters in an OR expression.
915                 [^\/] => { token( RE_Char, ts, te ); };
916         *|;
917
918         # We need a separate token space here to avoid the ragel keywords.
919         write_statement := |*
920                 ident => { token( TK_Word, ts, te ); } ;
921                 [ \t\n]+ => { updateCol(); };
922                 ';' => { token( ';' ); fgoto parser_def; };
923
924                 EOF => {
925                         scan_error() << "unterminated write statement" << endl;
926                 };
927         *|;
928
929         # Parser definitions. 
930         parser_def := |*
931                 'machine' => { token( KW_Machine ); };
932                 'include' => { token( KW_Include ); };
933                 'import' => { token( KW_Import ); };
934                 'write' => { 
935                         token( KW_Write );
936                         fgoto write_statement;
937                 };
938                 'action' => { token( KW_Action ); };
939                 'alphtype' => { token( KW_AlphType ); };
940                 'prepush' => { token( KW_PrePush ); };
941                 'postpop' => { token( KW_PostPop ); };
942
943                 # FIXME: Enable this post 5.17.
944                 # 'range' => { token( KW_Range ); };
945
946                 'getkey' => { 
947                         token( KW_GetKey );
948                         inlineBlockType = SemiTerminated;
949                         if ( hostLang->lang == HostLang::Ruby )
950                                 fcall inline_code_ruby;
951                         else
952                                 fcall inline_code;
953                 };
954                 'access' => { 
955                         token( KW_Access );
956                         inlineBlockType = SemiTerminated;
957                         if ( hostLang->lang == HostLang::Ruby )
958                                 fcall inline_code_ruby;
959                         else
960                                 fcall inline_code;
961                 };
962                 'variable' => { 
963                         token( KW_Variable );
964                         inlineBlockType = SemiTerminated;
965                         if ( hostLang->lang == HostLang::Ruby )
966                                 fcall inline_code_ruby;
967                         else
968                                 fcall inline_code;
969                 };
970                 'when' => { token( KW_When ); };
971                 'inwhen' => { token( KW_InWhen ); };
972                 'outwhen' => { token( KW_OutWhen ); };
973                 'eof' => { token( KW_Eof ); };
974                 'err' => { token( KW_Err ); };
975                 'lerr' => { token( KW_Lerr ); };
976                 'to' => { token( KW_To ); };
977                 'from' => { token( KW_From ); };
978                 'export' => { token( KW_Export ); };
979
980                 # Identifiers.
981                 ident => { token( TK_Word, ts, te ); } ;
982
983                 # Numbers
984                 number => { token( TK_UInt, ts, te ); };
985                 hex_number => { token( TK_Hex, ts, te ); };
986
987                 # Literals, with optionals.
988                 ( s_literal | d_literal ) [i]? 
989                         => { token( TK_Literal, ts, te ); };
990
991                 '[' => { token( RE_SqOpen ); fcall or_literal; };
992                 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
993
994                 '/' => { token( RE_Slash ); fgoto ragel_re_literal; };
995
996                 # Ignore.
997                 pound_comment => { updateCol(); };
998
999                 ':=' => { token( TK_ColonEquals ); };
1000
1001                 # To State Actions.
1002                 ">~" => { token( TK_StartToState ); };
1003                 "$~" => { token( TK_AllToState ); };
1004                 "%~" => { token( TK_FinalToState ); };
1005                 "<~" => { token( TK_NotStartToState ); };
1006                 "@~" => { token( TK_NotFinalToState ); };
1007                 "<>~" => { token( TK_MiddleToState ); };
1008
1009                 # From State actions
1010                 ">*" => { token( TK_StartFromState ); };
1011                 "$*" => { token( TK_AllFromState ); };
1012                 "%*" => { token( TK_FinalFromState ); };
1013                 "<*" => { token( TK_NotStartFromState ); };
1014                 "@*" => { token( TK_NotFinalFromState ); };
1015                 "<>*" => { token( TK_MiddleFromState ); };
1016
1017                 # EOF Actions.
1018                 ">/" => { token( TK_StartEOF ); };
1019                 "$/" => { token( TK_AllEOF ); };
1020                 "%/" => { token( TK_FinalEOF ); };
1021                 "</" => { token( TK_NotStartEOF ); };
1022                 "@/" => { token( TK_NotFinalEOF ); };
1023                 "<>/" => { token( TK_MiddleEOF ); };
1024
1025                 # Global Error actions.
1026                 ">!" => { token( TK_StartGblError ); };
1027                 "$!" => { token( TK_AllGblError ); };
1028                 "%!" => { token( TK_FinalGblError ); };
1029                 "<!" => { token( TK_NotStartGblError ); };
1030                 "@!" => { token( TK_NotFinalGblError ); };
1031                 "<>!" => { token( TK_MiddleGblError ); };
1032
1033                 # Local error actions.
1034                 ">^" => { token( TK_StartLocalError ); };
1035                 "$^" => { token( TK_AllLocalError ); };
1036                 "%^" => { token( TK_FinalLocalError ); };
1037                 "<^" => { token( TK_NotStartLocalError ); };
1038                 "@^" => { token( TK_NotFinalLocalError ); };
1039                 "<>^" => { token( TK_MiddleLocalError ); };
1040
1041                 # Middle.
1042                 "<>" => { token( TK_Middle ); };
1043
1044                 # Conditions. 
1045                 '>?' => { token( TK_StartCond ); };
1046                 '$?' => { token( TK_AllCond ); };
1047                 '%?' => { token( TK_LeavingCond ); };
1048
1049                 '..' => { token( TK_DotDot ); };
1050                 '**' => { token( TK_StarStar ); };
1051                 '--' => { token( TK_DashDash ); };
1052                 '->' => { token( TK_Arrow ); };
1053                 '=>' => { token( TK_DoubleArrow ); };
1054
1055                 ":>"  => { token( TK_ColonGt ); };
1056                 ":>>" => { token( TK_ColonGtGt ); };
1057                 "<:"  => { token( TK_LtColon ); };
1058
1059                 # Opening of longest match.
1060                 "|*" => { token( TK_BarStar ); };
1061
1062                 # Separater for name references.
1063                 "::" => { token( TK_NameSep, ts, te ); };
1064
1065                 '}%%' => { 
1066                         updateCol();
1067                         endSection();
1068                         fret;
1069                 };
1070
1071                 [ \t\r]+ => { updateCol(); };
1072
1073                 # If we are in a single line machine then newline may end the spec.
1074                 NL => {
1075                         updateCol();
1076                         if ( singleLineSpec ) {
1077                                 endSection();
1078                                 fret;
1079                         }
1080                 };
1081
1082                 '{' => { 
1083                         if ( lastToken == KW_Export || lastToken == KW_Entry )
1084                                 token( '{' );
1085                         else {
1086                                 token( '{' );
1087                                 curly_count = 1; 
1088                                 inlineBlockType = CurlyDelimited;
1089                                 if ( hostLang->lang == HostLang::Ruby )
1090                                         fcall inline_code_ruby;
1091                                 else
1092                                         fcall inline_code;
1093                         }
1094                 };
1095
1096                 EOF => {
1097                         scan_error() << "unterminated ragel section" << endl;
1098                 };
1099
1100                 any => { token( *ts ); } ;
1101         *|;
1102
1103         # Outside code scanner. These tokens get passed through.
1104         main_ruby := |*
1105                 ident => { pass( IMP_Word, ts, te ); };
1106                 number => { pass( IMP_UInt, ts, te ); };
1107                 ruby_comment => { pass(); };
1108                 ( s_literal | d_literal | host_re_literal ) 
1109                         => { pass( IMP_Literal, ts, te ); };
1110
1111                 '%%{' => { 
1112                         updateCol();
1113                         singleLineSpec = false;
1114                         startSection();
1115                         fcall parser_def;
1116                 };
1117                 '%%' => { 
1118                         updateCol();
1119                         singleLineSpec = true;
1120                         startSection();
1121                         fcall parser_def;
1122                 };
1123                 whitespace+ => { pass(); };
1124                 EOF;
1125                 any => { pass( *ts, 0, 0 ); };
1126         *|;
1127
1128         # Outside code scanner. These tokens get passed through.
1129         main := |*
1130                 'define' => { pass( IMP_Define, 0, 0 ); };
1131                 ident => { pass( IMP_Word, ts, te ); };
1132                 number => { pass( IMP_UInt, ts, te ); };
1133                 c_cpp_comment => { pass(); };
1134                 ( s_literal | d_literal ) => { pass( IMP_Literal, ts, te ); };
1135
1136                 '%%{' => { 
1137                         updateCol();
1138                         singleLineSpec = false;
1139                         startSection();
1140                         fcall parser_def;
1141                 };
1142                 '%%' => { 
1143                         updateCol();
1144                         singleLineSpec = true;
1145                         startSection();
1146                         fcall parser_def;
1147                 };
1148                 whitespace+ => { pass(); };
1149                 EOF;
1150                 any => { pass( *ts, 0, 0 ); };
1151         *|;
1152 }%%
1153
1154 %% write data;
1155
1156 void Scanner::do_scan()
1157 {
1158         int bufsize = 8;
1159         char *buf = new char[bufsize];
1160         int cs, act, have = 0;
1161         int top;
1162
1163         /* The stack is two deep, one level for going into ragel defs from the main
1164          * machines which process outside code, and another for going into or literals
1165          * from either a ragel spec, or a regular expression. */
1166         int stack[2];
1167         int curly_count = 0;
1168         bool execute = true;
1169         bool singleLineSpec = false;
1170         InlineBlockType inlineBlockType = CurlyDelimited;
1171
1172         /* Init the section parser and the character scanner. */
1173         init();
1174         %% write init;
1175
1176         /* Set up the start state. FIXME: After 5.20 is released the nocs write
1177          * init option should be used, the main machine eliminated and this statement moved
1178          * above the write init. */
1179         if ( hostLang->lang == HostLang::Ruby )
1180                 cs = rlscan_en_main_ruby;
1181         else
1182                 cs = rlscan_en_main;
1183         
1184         while ( execute ) {
1185                 char *p = buf + have;
1186                 int space = bufsize - have;
1187
1188                 if ( space == 0 ) {
1189                         /* We filled up the buffer trying to scan a token. Grow it. */
1190                         bufsize = bufsize * 2;
1191                         char *newbuf = new char[bufsize];
1192
1193                         /* Recompute p and space. */
1194                         p = newbuf + have;
1195                         space = bufsize - have;
1196
1197                         /* Patch up pointers possibly in use. */
1198                         if ( ts != 0 )
1199                                 ts = newbuf + ( ts - buf );
1200                         te = newbuf + ( te - buf );
1201
1202                         /* Copy the new buffer in. */
1203                         memcpy( newbuf, buf, have );
1204                         delete[] buf;
1205                         buf = newbuf;
1206                 }
1207
1208                 input.read( p, space );
1209                 int len = input.gcount();
1210                 char *pe = p + len;
1211
1212                 /* If we see eof then append the eof var. */
1213                 char *eof = 0;
1214                 if ( len == 0 ) {
1215                         eof = pe;
1216                         execute = false;
1217                 }
1218
1219                 %% write exec;
1220
1221                 /* Check if we failed. */
1222                 if ( cs == rlscan_error ) {
1223                         /* Machine failed before finding a token. I'm not yet sure if this
1224                          * is reachable. */
1225                         scan_error() << "scanner error" << endl;
1226                         exit(1);
1227                 }
1228
1229                 /* Decide if we need to preserve anything. */
1230                 char *preserve = ts;
1231
1232                 /* Now set up the prefix. */
1233                 if ( preserve == 0 )
1234                         have = 0;
1235                 else {
1236                         /* There is data that needs to be shifted over. */
1237                         have = pe - preserve;
1238                         memmove( buf, preserve, have );
1239                         unsigned int shiftback = preserve - buf;
1240                         if ( ts != 0 )
1241                                 ts -= shiftback;
1242                         te -= shiftback;
1243
1244                         preserve = buf;
1245                 }
1246         }
1247
1248         delete[] buf;
1249 }