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