CR characters need to be treated as whitespace.
[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 "rlparse.h"
28 #include "parsedata.h"
29 #include "avltree.h"
30 #include "vector.h"
31
32 using std::ifstream;
33 using std::istream;
34 using std::ostream;
35 using std::cout;
36 using std::cerr;
37 using std::endl;
38
39 extern char *Parser_lelNames[];
40
41 /* This is used for tracking the current stack of include file/machine pairs. It is
42  * is used to detect and recursive include structure. */
43 struct IncludeStackItem
44 {
45         IncludeStackItem( char *fileName, char *sectionName )
46                 : fileName(fileName), sectionName(sectionName) {}
47
48         char *fileName;
49         char *sectionName;
50 };
51
52 typedef Vector<IncludeStackItem> IncludeStack;
53
54 enum InlineBlockType
55 {
56         CurlyDelimited,
57         SemiTerminated
58 };
59
60 struct Scanner
61 {
62         Scanner( char *fileName, istream &input, ostream &output,
63                         Parser *inclToParser, char *inclSectionTarg,
64                         int includeDepth )
65         : 
66                 fileName(fileName), input(input), output(output),
67                 inclToParser(inclToParser),
68                 inclSectionTarg(inclSectionTarg),
69                 includeDepth(includeDepth),
70                 line(1), column(1), lastnl(0), 
71                 parser(0), active(false), 
72                 parserExistsError(false),
73                 whitespaceOn(true)
74                 {}
75
76         bool recursiveInclude( char *inclFileName, char *inclSectionName );
77
78         char *prepareFileName( char *fileName, int len )
79         {
80                 bool caseInsensitive;
81                 Token tokenFnStr, tokenRes;
82                 tokenFnStr.data = fileName;
83                 tokenFnStr.length = len;
84                 tokenFnStr.prepareLitString( tokenRes, caseInsensitive );
85                 return tokenRes.data;
86         }
87
88         void init();
89         void token( int type, char *start, char *end );
90         void token( int type, char c );
91         void token( int type );
92         void updateCol();
93         void startSection();
94         void endSection();
95         void do_scan();
96         bool parserExists();
97         ostream &scan_error();
98
99         char *fileName;
100         istream &input;
101         ostream &output;
102         Parser *inclToParser;
103         char *inclSectionTarg;
104         int includeDepth;
105
106         int cs;
107         int line;
108         char *word, *lit;
109         int word_len, lit_len;
110         InputLoc sectionLoc;
111         char *tokstart, *tokend;
112         int column;
113         char *lastnl;
114
115         /* Set by machine statements, these persist from section to section
116          * allowing for unnamed sections. */
117         Parser *parser;
118         bool active;
119         IncludeStack includeStack;
120
121         /* This is set if ragel has already emitted an error stating that
122          * no section name has been seen and thus no parser exists. */
123         bool parserExistsError;
124
125         /* This is for inline code. By default it is on. It goes off for
126          * statements and values in inline blocks which are parsed. */
127         bool whitespaceOn;
128 };
129
130 %%{
131         machine section_parse;
132         alphtype int;
133         write data;
134 }%%
135
136 void Scanner::init( )
137 {
138         %% write init;
139 }
140
141 bool Scanner::parserExists()
142 {
143         if ( parser != 0 )
144                 return true;
145
146         if ( ! parserExistsError ) {
147                 scan_error() << "include: there is no previous specification name" << endl;
148                 parserExistsError = true;
149         }
150         return false;
151 }
152
153 ostream &Scanner::scan_error()
154 {
155         /* Maintain the error count. */
156         gblErrorCount += 1;
157         cerr << fileName << ":" << line << ":" << column << ": ";
158         return cerr;
159 }
160
161 bool Scanner::recursiveInclude( char *inclFileName, char *inclSectionName )
162 {
163         for ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {
164                 if ( strcmp( si->fileName, inclFileName ) == 0 &&
165                                 strcmp( si->sectionName, inclSectionName ) == 0 )
166                 {
167                         return true;
168                 }
169         }
170         return false;   
171 }
172
173 void Scanner::updateCol()
174 {
175         char *from = lastnl;
176         if ( from == 0 )
177                 from = tokstart;
178         //cerr << "adding " << tokend - from << " to column" << endl;
179         column += tokend - from;
180         lastnl = 0;
181 }
182
183 void Scanner::token( int type, char c )
184 {
185         token( type, &c, &c + 1 );
186 }
187
188 void Scanner::token( int type )
189 {
190         token( type, 0, 0 );
191 }
192
193 %%{
194         machine section_parse;
195
196         # This relies on the the kelbt implementation and the order
197         # that tokens are declared.
198         KW_Machine = 128;
199         KW_Include = 129;
200         KW_Write = 130;
201         TK_Word = 131;
202         TK_Literal = 132;
203
204         action clear_words { word = lit = 0; word_len = lit_len = 0; }
205         action store_word { word = tokdata; word_len = toklen; }
206         action store_lit { lit = tokdata; lit_len = toklen; }
207
208         action mach_err { scan_error() << "bad machine statement" << endl; }
209         action incl_err { scan_error() << "bad include statement" << endl; }
210         action write_err { scan_error() << "bad write statement" << endl; }
211
212         action handle_machine
213         {
214                 /* Assign a name to the machine. */
215                 char *machine = word;
216
217                 if ( inclSectionTarg == 0 ) {
218                         active = true;
219
220                         ParserDictEl *pdEl = parserDict.find( machine );
221                         if ( pdEl == 0 ) {
222                                 pdEl = new ParserDictEl( machine );
223                                 pdEl->value = new Parser( fileName, machine, sectionLoc );
224                                 pdEl->value->init();
225                                 parserDict.insert( pdEl );
226                         }
227
228                         parser = pdEl->value;
229                 }
230                 else if ( strcmp( inclSectionTarg, machine ) == 0 ) {
231                         /* found include target */
232                         active = true;
233                         parser = inclToParser;
234                 }
235                 else {
236                         /* ignoring section */
237                         active = false;
238                         parser = 0;
239                 }
240         }
241
242         machine_stmt =
243                 ( KW_Machine TK_Word @store_word ';' ) @handle_machine
244                 <>err mach_err <>eof mach_err;
245
246         action handle_include
247         {
248                 if ( active && parserExists() ) {
249                         char *inclSectionName = word;
250                         char *inclFileName = 0;
251
252                         /* Implement defaults for the input file and section name. */
253                         if ( inclSectionName == 0 )
254                                 inclSectionName = parser->sectionName;
255
256                         if ( lit != 0 ) 
257                                 inclFileName = prepareFileName( lit, lit_len );
258                         else
259                                 inclFileName = fileName;
260
261                         /* Check for a recursive include structure. Add the current file/section
262                          * name then check if what we are including is already in the stack. */
263                         includeStack.append( IncludeStackItem( fileName, parser->sectionName ) );
264
265                         if ( recursiveInclude( inclFileName, inclSectionName ) )
266                                 scan_error() << "include: this is a recursive include operation" << endl;
267                         else {
268                                 /* Open the input file for reading. */
269                                 ifstream *inFile = new ifstream( inclFileName );
270                                 if ( ! inFile->is_open() ) {
271                                         scan_error() << "include: could not open " << 
272                                                         inclFileName << " for reading" << endl;
273                                 }
274
275                                 Scanner scanner( inclFileName, *inFile, output, parser,
276                                                 inclSectionName, includeDepth+1 );
277                                 scanner.init();
278                                 scanner.do_scan( );
279                                 delete inFile;
280                         }
281
282                         /* Remove the last element (len-1) */
283                         includeStack.remove( -1 );
284                 }
285         }
286
287         include_names = (
288                 TK_Word @store_word ( TK_Literal @store_lit )? |
289                 TK_Literal @store_lit
290         ) >clear_words;
291
292         include_stmt =
293                 ( KW_Include include_names ';' ) @handle_include
294                 <>err incl_err <>eof incl_err;
295
296         action write_command
297         {
298                 if ( active && machineSpec == 0 && machineName == 0 ) {
299                         output << "<write"
300                                         " def_name=\"" << parser->sectionName << "\""
301                                         " line=\"" << line << "\""
302                                         " col=\"" << column << "\""
303                                         ">";
304                 }
305         }
306
307         action write_arg
308         {
309                 if ( active && machineSpec == 0 && machineName == 0 )
310                         output << "<arg>" << tokdata << "</arg>";
311         }
312
313         action write_close
314         {
315                 if ( active && machineSpec == 0 && machineName == 0 )
316                         output << "</write>\n";
317         }
318
319         write_stmt =
320                 ( KW_Write @write_command 
321                 ( TK_Word @write_arg )+ ';' @write_close )
322                 <>err write_err <>eof write_err;
323
324         action handle_token
325         {
326                 /* Send the token off to the parser. */
327                 if ( active && parserExists() ) {
328                         InputLoc loc;
329
330                         #if 0
331                         cerr << "scanner:" << line << ":" << column << 
332                                         ": sending token to the parser " << Parser_lelNames[*p];
333                         cerr << " " << toklen;
334                         if ( tokdata != 0 )
335                                 cerr << " " << tokdata;
336                         cerr << endl;
337                         #endif
338
339                         loc.fileName = fileName;
340                         loc.line = line;
341                         loc.col = column;
342
343                         parser->token( loc, type, tokdata, toklen );
344                 }
345         }
346
347         # Catch everything else.
348         everything_else = ^( KW_Machine | KW_Include | KW_Write ) @handle_token;
349
350         main := ( 
351                 machine_stmt |
352                 include_stmt |
353                 write_stmt |
354                 everything_else
355         )*;
356 }%%
357
358 void Scanner::token( int type, char *start, char *end )
359 {
360         char *tokdata = 0;
361         int toklen = 0;
362         int *p = &type;
363         int *pe = &type + 1;
364
365         if ( start != 0 ) {
366                 toklen = end-start;
367                 tokdata = new char[toklen+1];
368                 memcpy( tokdata, start, toklen );
369                 tokdata[toklen] = 0;
370         }
371
372         %%{
373                 machine section_parse;
374                 write exec;
375         }%%
376
377         updateCol();
378 }
379
380 void Scanner::startSection( )
381 {
382         parserExistsError = false;
383
384         if ( includeDepth == 0 ) {
385                 if ( machineSpec == 0 && machineName == 0 )
386                         output << "</host>\n";
387         }
388
389         sectionLoc.fileName = fileName;
390         sectionLoc.line = line;
391         sectionLoc.col = 0;
392 }
393
394 void Scanner::endSection( )
395 {
396         /* Execute the eof actions for the section parser. */
397         %%{
398                 machine section_parse;
399                 write eof;
400         }%%
401
402         /* Close off the section with the parser. */
403         if ( active && parserExists() ) {
404                 InputLoc loc;
405                 loc.fileName = fileName;
406                 loc.line = line;
407                 loc.col = 0;
408
409                 parser->token( loc, TK_EndSection, 0, 0 );
410         }
411
412         if ( includeDepth == 0 ) {
413                 if ( machineSpec == 0 && machineName == 0 ) {
414                         /* The end section may include a newline on the end, so
415                          * we use the last line, which will count the newline. */
416                         output << "<host line=\"" << line << "\">";
417                 }
418         }
419 }
420
421 %%{
422         machine rlscan;
423
424         # This is sent by the driver code.
425         EOF = 0;
426         
427         action inc_nl { 
428                 lastnl = p; 
429                 column = 0;
430                 line++;
431         }
432         NL = '\n' @inc_nl;
433
434         # Identifiers, numbers, commetns, and other common things.
435         ident = ( alpha | '_' ) ( alpha |digit |'_' )*;
436         number = digit+;
437         hex_number = '0x' [0-9a-fA-F]+;
438
439         c_comment = 
440                 '/*' ( any | NL )* :>> '*/';
441
442         cpp_comment =
443                 '//' [^\n]* NL;
444
445         c_cpp_comment = c_comment | cpp_comment;
446
447         # These literal forms are common to C-like host code and ragel.
448         s_literal = "'" ([^'\\] | NL | '\\' (any | NL))* "'";
449         d_literal = '"' ([^"\\] | NL | '\\' (any | NL))* '"';
450
451         whitespace = [ \t] | NL;
452         pound_comment = '#' [^\n]* NL;
453
454         # An inline block of code. This is specified as a scanned, but is sent to
455         # the parser as one long block. The inline_block pointer is used to handle
456         # the preservation of the data.
457         inline_code := |*
458                 # Inline expression keywords.
459                 "fpc" => { token( KW_PChar ); };
460                 "fc" => { token( KW_Char ); };
461                 "fcurs" => { token( KW_CurState ); };
462                 "ftargs" => { token( KW_TargState ); };
463                 "fentry" => { 
464                         whitespaceOn = false; 
465                         token( KW_Entry );
466                 };
467
468                 # Inline statement keywords.
469                 "fhold" => { 
470                         whitespaceOn = false; 
471                         token( KW_Hold );
472                 };
473                 "fexec" => { token( KW_Exec, 0, 0 ); };
474                 "fgoto" => { 
475                         whitespaceOn = false; 
476                         token( KW_Goto );
477                 };
478                 "fnext" => { 
479                         whitespaceOn = false; 
480                         token( KW_Next );
481                 };
482                 "fcall" => { 
483                         whitespaceOn = false; 
484                         token( KW_Call );
485                 };
486                 "fret" => { 
487                         whitespaceOn = false; 
488                         token( KW_Ret );
489                 };
490                 "fbreak" => { 
491                         whitespaceOn = false; 
492                         token( KW_Break );
493                 };
494
495                 ident => { token( TK_Word, tokstart, tokend ); };
496
497                 number => { token( TK_UInt, tokstart, tokend ); };
498                 hex_number => { token( TK_Hex, tokstart, tokend ); };
499
500                 ( s_literal | d_literal ) 
501                         => { token( IL_Literal, tokstart, tokend ); };
502
503                 whitespace+ => { 
504                         if ( whitespaceOn ) 
505                                 token( IL_WhiteSpace, tokstart, tokend );
506                 };
507                 c_cpp_comment => { token( IL_Comment, tokstart, tokend ); };
508
509                 "::" => { token( TK_NameSep, tokstart, tokend ); };
510
511                 # Some symbols need to go to the parser as with their cardinal value as
512                 # the token type (as opposed to being sent as anonymous symbols)
513                 # because they are part of the sequences which we interpret. The * ) ;
514                 # symbols cause whitespace parsing to come back on. This gets turned
515                 # off by some keywords.
516
517                 ";" => {
518                         whitespaceOn = true;
519                         token( *tokstart, tokstart, tokend );
520                         if ( inlineBlockType == SemiTerminated )
521                                 fgoto parser_def;
522                 };
523
524                 [*)] => { 
525                         whitespaceOn = true;
526                         token( *tokstart, tokstart, tokend );
527                 };
528
529                 [,(] => { token( *tokstart, tokstart, tokend ); };
530
531                 '{' => { 
532                         token( IL_Symbol, tokstart, tokend );
533                         curly_count += 1; 
534                 };
535
536                 '}' => { 
537                         if ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {
538                                 /* Inline code block ends. */
539                                 token( '}' );
540                                 fgoto parser_def;
541                         }
542                         else {
543                                 /* Either a semi terminated inline block or only the closing
544                                  * brace of some inner scope, not the block's closing brace. */
545                                 token( IL_Symbol, tokstart, tokend );
546                         }
547                 };
548
549                 EOF => {
550                         scan_error() << "unterminated code block" << endl;
551                 };
552
553                 # Send every other character as a symbol.
554                 any => { token( IL_Symbol, tokstart, tokend ); };
555         *|;
556
557         or_literal := |*
558                 # Escape sequences in OR expressions.
559                 '\\0' => { token( RE_Char, '\0' ); };
560                 '\\a' => { token( RE_Char, '\a' ); };
561                 '\\b' => { token( RE_Char, '\b' ); };
562                 '\\t' => { token( RE_Char, '\t' ); };
563                 '\\n' => { token( RE_Char, '\n' ); };
564                 '\\v' => { token( RE_Char, '\v' ); };
565                 '\\f' => { token( RE_Char, '\f' ); };
566                 '\\r' => { token( RE_Char, '\r' ); };
567                 '\\\n' => { updateCol(); };
568                 '\\' any => { token( RE_Char, tokstart+1, tokend ); };
569
570                 # Range dash in an OR expression.
571                 '-' => { token( RE_Dash, 0, 0 ); };
572
573                 # Terminate an OR expression.
574                 ']'     => { token( RE_SqClose ); fret; };
575
576                 EOF => {
577                         scan_error() << "unterminated OR literal" << endl;
578                 };
579
580                 # Characters in an OR expression.
581                 [^\]] => { token( RE_Char, tokstart, tokend ); };
582
583         *|;
584
585         re_literal := |*
586                 # Escape sequences in regular expressions.
587                 '\\0' => { token( RE_Char, '\0' ); };
588                 '\\a' => { token( RE_Char, '\a' ); };
589                 '\\b' => { token( RE_Char, '\b' ); };
590                 '\\t' => { token( RE_Char, '\t' ); };
591                 '\\n' => { token( RE_Char, '\n' ); };
592                 '\\v' => { token( RE_Char, '\v' ); };
593                 '\\f' => { token( RE_Char, '\f' ); };
594                 '\\r' => { token( RE_Char, '\r' ); };
595                 '\\\n' => { updateCol(); };
596                 '\\' any => { token( RE_Char, tokstart+1, tokend ); };
597
598                 # Terminate an OR expression.
599                 '/' [i]? => { 
600                         token( RE_Slash, tokstart, tokend ); 
601                         fgoto parser_def;
602                 };
603
604                 # Special characters.
605                 '.' => { token( RE_Dot ); };
606                 '*' => { token( RE_Star ); };
607
608                 '[' => { token( RE_SqOpen ); fcall or_literal; };
609                 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
610
611                 EOF => {
612                         scan_error() << "unterminated regular expression" << endl;
613                 };
614
615                 # Characters in an OR expression.
616                 [^\/] => { token( RE_Char, tokstart, tokend ); };
617         *|;
618
619         # We need a separate token space here to avoid the ragel keywords.
620         write_statement := |*
621                 ident => { token( TK_Word, tokstart, tokend ); } ;
622                 [ \t\n]+ => { updateCol(); };
623                 ';' => { token( ';' ); fgoto parser_def; };
624
625                 EOF => {
626                         scan_error() << "unterminated write statement" << endl;
627                 };
628         *|;
629
630         # Parser definitions. 
631         parser_def := |*
632                 'machine' => { token( KW_Machine ); };
633                 'include' => { token( KW_Include ); };
634                 'write' => { 
635                         token( KW_Write );
636                         fgoto write_statement;
637                 };
638                 'action' => { token( KW_Action ); };
639                 'alphtype' => { token( KW_AlphType ); };
640
641                 # FIXME: Enable this post 5.17.
642                 # 'range' => { token( KW_Range ); };
643
644                 'getkey' => { 
645                         token( KW_GetKey );
646                         inlineBlockType = SemiTerminated;
647                         fgoto inline_code;
648                 };
649                 'access' => { 
650                         token( KW_Access );
651                         inlineBlockType = SemiTerminated;
652                         fgoto inline_code;
653                 };
654                 'variable' => { 
655                         token( KW_Variable );
656                         inlineBlockType = SemiTerminated;
657                         fgoto inline_code;
658                 };
659                 'when' => { token( KW_When ); };
660                 'eof' => { token( KW_Eof ); };
661                 'err' => { token( KW_Err ); };
662                 'lerr' => { token( KW_Lerr ); };
663                 'to' => { token( KW_To ); };
664                 'from' => { token( KW_From ); };
665
666                 # Identifiers.
667                 ident => { token( TK_Word, tokstart, tokend ); } ;
668
669                 # Numbers
670                 number => { token( TK_UInt, tokstart, tokend ); };
671                 hex_number => { token( TK_Hex, tokstart, tokend ); };
672
673                 # Literals, with optionals.
674                 ( s_literal | d_literal ) [i]? 
675                         => { token( TK_Literal, tokstart, tokend ); };
676
677                 '[' => { token( RE_SqOpen ); fcall or_literal; };
678                 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
679
680                 '/' => { token( RE_Slash ); fgoto re_literal; };
681
682                 # Ignore.
683                 pound_comment => { updateCol(); };
684
685                 ':=' => { token( TK_ColonEquals ); };
686
687                 # To State Actions.
688                 ">~" => { token( TK_StartToState ); };
689                 "$~" => { token( TK_AllToState ); };
690                 "%~" => { token( TK_FinalToState ); };
691                 "<~" => { token( TK_NotStartToState ); };
692                 "@~" => { token( TK_NotFinalToState ); };
693                 "<>~" => { token( TK_MiddleToState ); };
694
695                 # From State actions
696                 ">*" => { token( TK_StartFromState ); };
697                 "$*" => { token( TK_AllFromState ); };
698                 "%*" => { token( TK_FinalFromState ); };
699                 "<*" => { token( TK_NotStartFromState ); };
700                 "@*" => { token( TK_NotFinalFromState ); };
701                 "<>*" => { token( TK_MiddleFromState ); };
702
703                 # EOF Actions.
704                 ">/" => { token( TK_StartEOF ); };
705                 "$/" => { token( TK_AllEOF ); };
706                 "%/" => { token( TK_FinalEOF ); };
707                 "</" => { token( TK_NotStartEOF ); };
708                 "@/" => { token( TK_NotFinalEOF ); };
709                 "<>/" => { token( TK_MiddleEOF ); };
710
711                 # Global Error actions.
712                 ">!" => { token( TK_StartGblError ); };
713                 "$!" => { token( TK_AllGblError ); };
714                 "%!" => { token( TK_FinalGblError ); };
715                 "<!" => { token( TK_NotStartGblError ); };
716                 "@!" => { token( TK_NotFinalGblError ); };
717                 "<>!" => { token( TK_MiddleGblError ); };
718
719                 # Local error actions.
720                 ">^" => { token( TK_StartLocalError ); };
721                 "$^" => { token( TK_AllLocalError ); };
722                 "%^" => { token( TK_FinalLocalError ); };
723                 "<^" => { token( TK_NotStartLocalError ); };
724                 "@^" => { token( TK_NotFinalLocalError ); };
725                 "<>^" => { token( TK_MiddleLocalError ); };
726
727                 # Middle.
728                 "<>" => { token( TK_Middle ); };
729
730                 # Conditions. 
731                 '>?' => { token( TK_StartCond ); };
732                 '$?' => { token( TK_AllCond ); };
733                 '%?' => { token( TK_LeavingCond ); };
734
735                 '..' => { token( TK_DotDot ); };
736                 '**' => { token( TK_StarStar ); };
737                 '--' => { token( TK_DashDash ); };
738                 '->' => { token( TK_Arrow ); };
739                 '=>' => { token( TK_DoubleArrow ); };
740
741                 ":>"  => { token( TK_ColonGt ); };
742                 ":>>" => { token( TK_ColonGtGt ); };
743                 "<:"  => { token( TK_LtColon ); };
744
745                 # Opening of longest match.
746                 "|*" => { token( TK_BarStar ); };
747
748                 '}%%' => { 
749                         updateCol();
750                         endSection();
751                         fgoto main;
752                 };
753
754                 [ \t\r]+ => { updateCol(); };
755
756                 # If we are in a single line machine then newline may end the spec.
757                 NL => {
758                         updateCol();
759                         if ( singleLineSpec ) {
760                                 endSection();
761                                 fgoto main;
762                         }
763                 };
764
765                 '{' => { 
766                         token( '{' );
767                         curly_count = 1; 
768                         inlineBlockType = CurlyDelimited;
769                         fgoto inline_code;
770                 };
771
772                 EOF => {
773                         scan_error() << "unterminated ragel section" << endl;
774                 };
775
776                 any => { token( *tokstart ); } ;
777         *|;
778
779         action pass {
780                 updateCol();
781
782                 /* If no errors and we are at the bottom of the include stack (the
783                  * source file listed on the command line) then write out the data. */
784                 if ( includeDepth == 0 && machineSpec == 0 && machineName == 0 )
785                         xmlEscapeHost( output, tokstart, tokend-tokstart );
786         }
787
788         # Outside code scanner. These tokens get passed through.
789         main := |*
790                 ident => pass;
791                 number => pass;
792                 c_cpp_comment => pass;
793                 s_literal | d_literal => pass;
794                 '%%{' => { 
795                         updateCol();
796                         singleLineSpec = false;
797                         startSection();
798                         fgoto parser_def;
799                 };
800                 '%%' => { 
801                         updateCol();
802                         singleLineSpec = true;
803                         startSection();
804                         fgoto parser_def;
805                 };
806                 whitespace+ => pass;
807                 EOF;
808                 any => pass;
809         *|;
810
811 }%%
812
813 %% write data;
814
815 void Scanner::do_scan()
816 {
817         int bufsize = 8;
818         char *buf = new char[bufsize];
819         const char last_char = 0;
820         int cs, act, have = 0;
821         int top, stack[1];
822         int curly_count = 0;
823         bool execute = true;
824         bool singleLineSpec = false;
825         InlineBlockType inlineBlockType;
826
827         %% write init;
828
829         while ( execute ) {
830                 char *p = buf + have;
831                 int space = bufsize - have;
832
833                 if ( space == 0 ) {
834                         /* We filled up the buffer trying to scan a token. Grow it. */
835                         bufsize = bufsize * 2;
836                         char *newbuf = new char[bufsize];
837
838                         /* Recompute p and space. */
839                         p = newbuf + have;
840                         space = bufsize - have;
841
842                         /* Patch up pointers possibly in use. */
843                         if ( tokstart != 0 )
844                                 tokstart = newbuf + ( tokstart - buf );
845                         tokend = newbuf + ( tokend - buf );
846
847                         /* Copy the new buffer in. */
848                         memcpy( newbuf, buf, have );
849                         delete[] buf;
850                         buf = newbuf;
851                 }
852
853                 input.read( p, space );
854                 int len = input.gcount();
855
856                 /* If we see eof then append the EOF char. */
857                 if ( len == 0 ) {
858                         p[0] = last_char, len = 1;
859                         execute = false;
860                 }
861
862                 char *pe = p + len;
863                 %% write exec;
864
865                 /* Check if we failed. */
866                 if ( cs == rlscan_error ) {
867                         /* Machine failed before finding a token. I'm not yet sure if this
868                          * is reachable. */
869                         scan_error() << "scanner error" << endl;
870                         exit(1);
871                 }
872
873                 /* Decide if we need to preserve anything. */
874                 char *preserve = tokstart;
875
876                 /* Now set up the prefix. */
877                 if ( preserve == 0 )
878                         have = 0;
879                 else {
880                         /* There is data that needs to be shifted over. */
881                         have = pe - preserve;
882                         memmove( buf, preserve, have );
883                         unsigned int shiftback = preserve - buf;
884                         if ( tokstart != 0 )
885                                 tokstart -= shiftback;
886                         tokend -= shiftback;
887
888                         preserve = buf;
889                 }
890         }
891
892         delete[] buf;
893 }
894
895 void scan( char *fileName, istream &input, ostream &output )
896 {
897         Scanner scanner( fileName, input, output, 0, 0, 0 );
898         scanner.init();
899         scanner.do_scan();
900
901         InputLoc eofLoc;
902         eofLoc.fileName = fileName;
903         eofLoc.col = 1;
904         eofLoc.line = scanner.line;
905 }