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