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