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