2 * Copyright 2006 Adrian Thurston <thurston@cs.queensu.ca>
5 /* This file is part of Ragel.
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.
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.
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
28 #include "parsedata.h"
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
44 IncludeStackItem( char *fileName, char *sectionName )
45 : fileName(fileName), sectionName(sectionName) {}
51 typedef Vector<IncludeStackItem> IncludeStack;
61 Scanner( char *fileName, istream &input, ostream &output,
62 Parser *inclToParser, char *inclSectionTarg,
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), ragelDefOpen(false),
75 bool recursiveInclude( char *inclFileName, char *inclSectionName );
77 char *prepareFileName( char *fileName, int len )
80 Token tokenFnStr, tokenRes;
81 tokenFnStr.data = fileName;
82 tokenFnStr.length = len;
83 tokenFnStr.prepareLitString( tokenRes, caseInsensitive );
88 void token( int type, char *start, char *end );
89 void token( int type, char c );
90 void token( int type );
97 ostream &scan_error();
102 Parser *inclToParser;
103 char *inclSectionTarg;
109 int word_len, lit_len;
111 char *tokstart, *tokend;
115 /* Set by machine statements, these persist from section to section
116 * allowing for unnamed sections. */
119 IncludeStack includeStack;
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;
126 /* This is for inline code. By default it is on. It goes off for
127 * statements and values in inline blocks which are parsed. */
132 machine section_parse;
137 void Scanner::init( )
142 bool Scanner::parserExists()
147 if ( ! parserExistsError ) {
148 scan_error() << "include: there is no previous specification name" << endl;
149 parserExistsError = true;
154 ostream &Scanner::scan_error()
156 /* Maintain the error count. */
158 cerr << fileName << ":" << line << ":" << column << ": ";
162 bool Scanner::recursiveInclude( char *inclFileName, char *inclSectionName )
164 for ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {
165 if ( strcmp( si->fileName, inclFileName ) == 0 &&
166 strcmp( si->sectionName, inclSectionName ) == 0 )
174 void Scanner::updateCol()
179 //cerr << "adding " << tokend - from << " to column" << endl;
180 column += tokend - from;
184 void Scanner::token( int type, char c )
186 token( type, &c, &c + 1 );
189 void Scanner::token( int type )
195 machine section_parse;
197 # This relies on the the kelbt implementation and the order
198 # that tokens are declared.
205 action clear_words { word = lit = 0; word_len = lit_len = 0; }
206 action store_word { word = tokdata; word_len = toklen; }
207 action store_lit { lit = tokdata; lit_len = toklen; }
209 action mach_err { scan_error() << "bad machine statement" << endl; }
210 action incl_err { scan_error() << "bad include statement" << endl; }
211 action write_err { scan_error() << "bad write statement" << endl; }
213 action handle_machine
215 /* Assign a name to the machine. */
216 char *machine = word;
218 if ( inclSectionTarg == 0 ) {
221 ParserDictEl *pdEl = parserDict.find( machine );
223 pdEl = new ParserDictEl( machine );
224 pdEl->value = new Parser( fileName, machine, sectionLoc );
226 parserDict.insert( pdEl );
229 parser = pdEl->value;
231 else if ( strcmp( inclSectionTarg, machine ) == 0 ) {
232 /* found include target */
234 parser = inclToParser;
237 /* ignoring section */
244 ( KW_Machine TK_Word @store_word ';' ) @handle_machine
245 <>err mach_err <>eof mach_err;
247 action handle_include
249 if ( active && parserExists() ) {
250 char *inclSectionName = word;
251 char *inclFileName = 0;
253 /* Implement defaults for the input file and section name. */
254 if ( inclSectionName == 0 )
255 inclSectionName = parser->sectionName;
258 inclFileName = prepareFileName( lit, lit_len );
260 inclFileName = fileName;
262 /* Check for a recursive include structure. Add the current file/section
263 * name then check if what we are including is already in the stack. */
264 includeStack.append( IncludeStackItem( fileName, parser->sectionName ) );
266 if ( recursiveInclude( inclFileName, inclSectionName ) )
267 scan_error() << "include: this is a recursive include operation" << endl;
269 /* Open the input file for reading. */
270 ifstream *inFile = new ifstream( inclFileName );
271 if ( ! inFile->is_open() ) {
272 scan_error() << "include: could not open " <<
273 inclFileName << " for reading" << endl;
276 Scanner scanner( inclFileName, *inFile, output, parser,
277 inclSectionName, includeDepth+1 );
283 /* Remove the last element (len-1) */
284 includeStack.remove( -1 );
289 TK_Word @store_word ( TK_Literal @store_lit )? |
290 TK_Literal @store_lit
294 ( KW_Include include_names ';' ) @handle_include
295 <>err incl_err <>eof incl_err;
301 if ( strcmp( tokdata, "data" ) != 0 &&
302 strcmp( tokdata, "init" ) != 0 &&
303 strcmp( tokdata, "exec" ) != 0 &&
304 strcmp( tokdata, "eof" ) != 0 )
306 scan_error() << "unknown write command" << endl;
308 output << " <write what=\"" << tokdata << "\">";
315 output << "<option>" << tokdata << "</option>";
320 output << "</write>\n";
324 ( KW_Write TK_Word @write_command
325 ( TK_Word @write_option )* ';' @write_close )
326 <>err write_err <>eof write_err;
330 /* Send the token off to the parser. */
331 if ( active && parserExists() ) {
335 cerr << "scanner:" << line << ":" << column <<
336 ": sending token to the parser " << lelNames[*p];
337 cerr << " " << toklen;
339 cerr << " " << tokdata;
343 loc.fileName = fileName;
347 parser->token( loc, type, tokdata, toklen );
351 # Catch everything else.
352 everything_else = ^( KW_Machine | KW_Include | KW_Write ) @handle_token;
362 void Scanner::token( int type, char *start, char *end )
371 tokdata = new char[toklen+1];
372 memcpy( tokdata, start, toklen );
377 machine section_parse;
384 void Scanner::startSection( )
386 parserExistsError = false;
388 if ( includeDepth == 0 ) {
389 if ( machineSpec == 0 && machineName == 0 )
390 output << "</host>\n";
391 ragelDefOpen = false;
394 sectionLoc.fileName = fileName;
395 sectionLoc.line = line;
399 void Scanner::openRagelDef()
401 if ( ! ragelDefOpen ) {
403 output << "<ragel_def name=\"" << parser->sectionName << "\">\n";
407 void Scanner::endSection( )
409 /* Execute the eof actions for the section parser. */
411 machine section_parse;
415 /* Close off the section with the parser. */
416 if ( active && parserExists() ) {
418 loc.fileName = fileName;
422 parser->token( loc, TK_EndSection, 0, 0 );
425 if ( includeDepth == 0 ) {
426 if ( ragelDefOpen ) {
427 output << "</ragel_def>\n";
428 ragelDefOpen = false;
431 if ( machineSpec == 0 && machineName == 0 ) {
432 /* The end section may include a newline on the end, so
433 * we use the last line, which will count the newline. */
434 output << "<host line=\"" << line << "\">";
442 # This is sent by the driver code.
452 # Identifiers, numbers, commetns, and other common things.
453 ident = ( alpha | '_' ) ( alpha |digit |'_' )*;
455 hex_number = '0x' [0-9a-fA-F]+;
458 '/*' ( any | NL )* :>> '*/';
463 c_cpp_comment = c_comment | cpp_comment;
465 # These literal forms are common to C-like host code and ragel.
466 s_literal = "'" ([^'\\] | NL | '\\' (any | NL))* "'";
467 d_literal = '"' ([^"\\] | NL | '\\' (any | NL))* '"';
469 whitespace = [ \t] | NL;
470 pound_comment = '#' [^\n]* NL;
472 # An inline block of code. This is specified as a scanned, but is sent to
473 # the parser as one long block. The inline_block pointer is used to handle
474 # the preservation of the data.
476 # Inline expression keywords.
477 "fpc" => { token( KW_PChar ); };
478 "fc" => { token( KW_Char ); };
479 "fcurs" => { token( KW_CurState ); };
480 "ftargs" => { token( KW_TargState ); };
482 whitespaceOn = false;
486 # Inline statement keywords.
488 whitespaceOn = false;
491 "fexec" => { token( KW_Exec, 0, 0 ); };
493 whitespaceOn = false;
497 whitespaceOn = false;
501 whitespaceOn = false;
505 whitespaceOn = false;
509 whitespaceOn = false;
513 ident => { token( TK_Word, tokstart, tokend ); };
515 number => { token( TK_UInt, tokstart, tokend ); };
516 hex_number => { token( TK_Hex, tokstart, tokend ); };
518 ( s_literal | d_literal )
519 => { token( IL_Literal, tokstart, tokend ); };
523 token( IL_WhiteSpace, tokstart, tokend );
525 c_cpp_comment => { token( IL_Comment, tokstart, tokend ); };
527 "::" => { token( TK_NameSep, tokstart, tokend ); };
529 # Some symbols need to go to the parser as with their cardinal value as
530 # the token type (as opposed to being sent as anonymous symbols)
531 # because they are part of the sequences which we interpret. The * ) ;
532 # symbols cause whitespace parsing to come back on. This gets turned
533 # off by some keywords.
537 token( *tokstart, tokstart, tokend );
538 if ( inlineBlockType == SemiTerminated )
544 token( *tokstart, tokstart, tokend );
547 [,(] => { token( *tokstart, tokstart, tokend ); };
550 token( IL_Symbol, tokstart, tokend );
555 if ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {
556 /* Inline code block ends. */
561 /* Either a semi terminated inline block or only the closing
562 * brace of some inner scope, not the block's closing brace. */
563 token( IL_Symbol, tokstart, tokend );
568 scan_error() << "unterminated code block" << endl;
571 # Send every other character as a symbol.
572 any => { token( IL_Symbol, tokstart, tokend ); };
576 # Escape sequences in OR expressions.
577 '\\0' => { token( RE_Char, '\0' ); };
578 '\\a' => { token( RE_Char, '\a' ); };
579 '\\b' => { token( RE_Char, '\b' ); };
580 '\\t' => { token( RE_Char, '\t' ); };
581 '\\n' => { token( RE_Char, '\n' ); };
582 '\\v' => { token( RE_Char, '\v' ); };
583 '\\f' => { token( RE_Char, '\f' ); };
584 '\\r' => { token( RE_Char, '\r' ); };
585 '\\\n' => { updateCol(); };
586 '\\' any => { token( RE_Char, tokstart+1, tokend ); };
588 # Range dash in an OR expression.
589 '-' => { token( RE_Dash, 0, 0 ); };
591 # Terminate an OR expression.
592 ']' => { token( RE_SqClose ); fret; };
595 scan_error() << "unterminated OR literal" << endl;
598 # Characters in an OR expression.
599 [^\]] => { token( RE_Char, tokstart, tokend ); };
604 # Escape sequences in regular expressions.
605 '\\0' => { token( RE_Char, '\0' ); };
606 '\\a' => { token( RE_Char, '\a' ); };
607 '\\b' => { token( RE_Char, '\b' ); };
608 '\\t' => { token( RE_Char, '\t' ); };
609 '\\n' => { token( RE_Char, '\n' ); };
610 '\\v' => { token( RE_Char, '\v' ); };
611 '\\f' => { token( RE_Char, '\f' ); };
612 '\\r' => { token( RE_Char, '\r' ); };
613 '\\\n' => { updateCol(); };
614 '\\' any => { token( RE_Char, tokstart+1, tokend ); };
616 # Terminate an OR expression.
618 token( RE_Slash, tokstart, tokend );
622 # Special characters.
623 '.' => { token( RE_Dot ); };
624 '*' => { token( RE_Star ); };
626 '[' => { token( RE_SqOpen ); fcall or_literal; };
627 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
630 scan_error() << "unterminated regular expression" << endl;
633 # Characters in an OR expression.
634 [^\/] => { token( RE_Char, tokstart, tokend ); };
637 # We need a separate token space here to avoid the ragel keywords.
638 write_statement := |*
639 ident => { token( TK_Word, tokstart, tokend ); } ;
640 [ \t\n]+ => { updateCol(); };
641 ';' => { token( ';' ); fgoto parser_def; };
644 scan_error() << "unterminated write statement" << endl;
648 # Parser definitions.
650 'machine' => { token( KW_Machine ); };
651 'include' => { token( KW_Include ); };
654 fgoto write_statement;
656 'action' => { token( KW_Action ); };
657 'alphtype' => { token( KW_AlphType ); };
659 # FIXME: Enable this post 5.17.
660 # 'range' => { token( KW_Range ); };
664 inlineBlockType = SemiTerminated;
669 inlineBlockType = SemiTerminated;
673 token( KW_Variable );
674 inlineBlockType = SemiTerminated;
677 'when' => { token( KW_When ); };
678 'eof' => { token( KW_Eof ); };
679 'err' => { token( KW_Err ); };
680 'lerr' => { token( KW_Lerr ); };
681 'to' => { token( KW_To ); };
682 'from' => { token( KW_From ); };
685 ident => { token( TK_Word, tokstart, tokend ); } ;
688 number => { token( TK_UInt, tokstart, tokend ); };
689 hex_number => { token( TK_Hex, tokstart, tokend ); };
691 # Literals, with optionals.
692 ( s_literal | d_literal ) [i]?
693 => { token( TK_Literal, tokstart, tokend ); };
695 '[' => { token( RE_SqOpen ); fcall or_literal; };
696 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
698 '/' => { token( RE_Slash ); fgoto re_literal; };
701 pound_comment => { updateCol(); };
703 ':=' => { token( TK_ColonEquals ); };
706 ">~" => { token( TK_StartToState ); };
707 "$~" => { token( TK_AllToState ); };
708 "%~" => { token( TK_FinalToState ); };
709 "<~" => { token( TK_NotStartToState ); };
710 "@~" => { token( TK_NotFinalToState ); };
711 "<>~" => { token( TK_MiddleToState ); };
714 ">*" => { token( TK_StartFromState ); };
715 "$*" => { token( TK_AllFromState ); };
716 "%*" => { token( TK_FinalFromState ); };
717 "<*" => { token( TK_NotStartFromState ); };
718 "@*" => { token( TK_NotFinalFromState ); };
719 "<>*" => { token( TK_MiddleFromState ); };
722 ">/" => { token( TK_StartEOF ); };
723 "$/" => { token( TK_AllEOF ); };
724 "%/" => { token( TK_FinalEOF ); };
725 "</" => { token( TK_NotStartEOF ); };
726 "@/" => { token( TK_NotFinalEOF ); };
727 "<>/" => { token( TK_MiddleEOF ); };
729 # Global Error actions.
730 ">!" => { token( TK_StartGblError ); };
731 "$!" => { token( TK_AllGblError ); };
732 "%!" => { token( TK_FinalGblError ); };
733 "<!" => { token( TK_NotStartGblError ); };
734 "@!" => { token( TK_NotFinalGblError ); };
735 "<>!" => { token( TK_MiddleGblError ); };
737 # Local error actions.
738 ">^" => { token( TK_StartLocalError ); };
739 "$^" => { token( TK_AllLocalError ); };
740 "%^" => { token( TK_FinalLocalError ); };
741 "<^" => { token( TK_NotStartLocalError ); };
742 "@^" => { token( TK_NotFinalLocalError ); };
743 "<>^" => { token( TK_MiddleLocalError ); };
746 "<>" => { token( TK_Middle ); };
749 '>?' => { token( TK_StartCond ); };
750 '$?' => { token( TK_AllCond ); };
751 '%?' => { token( TK_LeavingCond ); };
753 '..' => { token( TK_DotDot ); };
754 '**' => { token( TK_StarStar ); };
755 '--' => { token( TK_DashDash ); };
756 '->' => { token( TK_Arrow ); };
757 '=>' => { token( TK_DoubleArrow ); };
759 ":>" => { token( TK_ColonGt ); };
760 ":>>" => { token( TK_ColonGtGt ); };
761 "<:" => { token( TK_LtColon ); };
763 # Opening of longest match.
764 "|*" => { token( TK_BarStar ); };
772 [ \t]+ => { updateCol(); };
774 # If we are in a single line machine then newline may end the spec.
777 if ( singleLineSpec ) {
786 inlineBlockType = CurlyDelimited;
791 scan_error() << "unterminated ragel section" << endl;
794 any => { token( *tokstart ); } ;
800 /* If no errors and we are at the bottom of the include stack (the
801 * source file listed on the command line) then write out the data. */
802 if ( includeDepth == 0 && machineSpec == 0 && machineName == 0 )
803 xmlEscapeHost( output, tokstart, tokend-tokstart );
806 # Outside code scanner. These tokens get passed through.
810 c_cpp_comment => pass;
811 s_literal | d_literal => pass;
814 singleLineSpec = false;
820 singleLineSpec = true;
833 void Scanner::do_scan()
836 char *buf = new char[bufsize];
837 const char last_char = 0;
838 int cs, act, have = 0;
842 bool singleLineSpec = false;
843 InlineBlockType inlineBlockType;
848 char *p = buf + have;
849 int space = bufsize - have;
852 /* We filled up the buffer trying to scan a token. Grow it. */
853 bufsize = bufsize * 2;
854 char *newbuf = new char[bufsize];
856 /* Recompute p and space. */
858 space = bufsize - have;
860 /* Patch up pointers possibly in use. */
862 tokstart = newbuf + ( tokstart - buf );
863 tokend = newbuf + ( tokend - buf );
865 /* Copy the new buffer in. */
866 memcpy( newbuf, buf, have );
871 input.read( p, space );
872 int len = input.gcount();
874 /* If we see eof then append the EOF char. */
876 p[0] = last_char, len = 1;
883 /* Check if we failed. */
884 if ( cs == rlscan_error ) {
885 /* Machine failed before finding a token. I'm not yet sure if this
887 scan_error() << "scanner error" << endl;
891 /* Decide if we need to preserve anything. */
892 char *preserve = tokstart;
894 /* Now set up the prefix. */
898 /* There is data that needs to be shifted over. */
899 have = pe - preserve;
900 memmove( buf, preserve, have );
901 unsigned int shiftback = preserve - buf;
903 tokstart -= shiftback;
913 void scan( char *fileName, istream &input, ostream &output )
915 Scanner scanner( fileName, input, output, 0, 0, 0 );
920 eofLoc.fileName = fileName;
922 eofLoc.line = scanner.line;