2 * Copyright 2006-2007 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"
39 extern char *Parser_lelNames[];
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
45 IncludeStackItem( char *fileName, char *sectionName )
46 : fileName(fileName), sectionName(sectionName) {}
52 typedef Vector<IncludeStackItem> IncludeStack;
62 Scanner( char *fileName, istream &input, ostream &output,
63 Parser *inclToParser, char *inclSectionTarg,
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),
76 bool recursiveInclude( char *inclFileName, char *inclSectionName );
78 char *prepareFileName( char *fileName, int len )
81 Token tokenFnStr, tokenRes;
82 tokenFnStr.data = fileName;
83 tokenFnStr.length = len;
84 tokenFnStr.prepareLitString( tokenRes, caseInsensitive );
89 void token( int type, char *start, char *end );
90 void token( int type, char c );
91 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;
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. */
131 machine section_parse;
136 void Scanner::init( )
141 bool Scanner::parserExists()
146 if ( ! parserExistsError ) {
147 scan_error() << "include: there is no previous specification name" << endl;
148 parserExistsError = true;
153 ostream &Scanner::scan_error()
155 /* Maintain the error count. */
157 cerr << fileName << ":" << line << ":" << column << ": ";
161 bool Scanner::recursiveInclude( char *inclFileName, char *inclSectionName )
163 for ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {
164 if ( strcmp( si->fileName, inclFileName ) == 0 &&
165 strcmp( si->sectionName, inclSectionName ) == 0 )
173 void Scanner::updateCol()
178 //cerr << "adding " << tokend - from << " to column" << endl;
179 column += tokend - from;
183 void Scanner::token( int type, char c )
185 token( type, &c, &c + 1 );
188 void Scanner::token( int type )
194 machine section_parse;
196 # This relies on the the kelbt implementation and the order
197 # that tokens are declared.
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; }
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; }
212 action handle_machine
214 /* Assign a name to the machine. */
215 char *machine = word;
217 if ( inclSectionTarg == 0 ) {
220 ParserDictEl *pdEl = parserDict.find( machine );
222 pdEl = new ParserDictEl( machine );
223 pdEl->value = new Parser( fileName, machine, sectionLoc );
225 parserDict.insert( pdEl );
228 parser = pdEl->value;
230 else if ( strcmp( inclSectionTarg, machine ) == 0 ) {
231 /* found include target */
233 parser = inclToParser;
236 /* ignoring section */
243 ( KW_Machine TK_Word @store_word ';' ) @handle_machine
244 <>err mach_err <>eof mach_err;
246 action handle_include
248 if ( active && parserExists() ) {
249 char *inclSectionName = word;
250 char *inclFileName = 0;
252 /* Implement defaults for the input file and section name. */
253 if ( inclSectionName == 0 )
254 inclSectionName = parser->sectionName;
257 inclFileName = prepareFileName( lit, lit_len );
259 inclFileName = fileName;
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 ) );
265 if ( recursiveInclude( inclFileName, inclSectionName ) )
266 scan_error() << "include: this is a recursive include operation" << endl;
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;
275 Scanner scanner( inclFileName, *inFile, output, parser,
276 inclSectionName, includeDepth+1 );
282 /* Remove the last element (len-1) */
283 includeStack.remove( -1 );
288 TK_Word @store_word ( TK_Literal @store_lit )? |
289 TK_Literal @store_lit
293 ( KW_Include include_names ';' ) @handle_include
294 <>err incl_err <>eof incl_err;
298 if ( active && machineSpec == 0 && machineName == 0 ) {
300 " def_name=\"" << parser->sectionName << "\""
301 " line=\"" << line << "\""
302 " col=\"" << column << "\""
309 if ( active && machineSpec == 0 && machineName == 0 )
310 output << "<arg>" << tokdata << "</arg>";
315 if ( active && machineSpec == 0 && machineName == 0 )
316 output << "</write>\n";
320 ( KW_Write @write_command
321 ( TK_Word @write_arg )+ ';' @write_close )
322 <>err write_err <>eof write_err;
326 /* Send the token off to the parser. */
327 if ( active && parserExists() ) {
331 cerr << "scanner:" << line << ":" << column <<
332 ": sending token to the parser " << Parser_lelNames[*p];
333 cerr << " " << toklen;
335 cerr << " " << tokdata;
339 loc.fileName = fileName;
343 parser->token( loc, type, tokdata, toklen );
347 # Catch everything else.
348 everything_else = ^( KW_Machine | KW_Include | KW_Write ) @handle_token;
358 void Scanner::token( int type, char *start, char *end )
367 tokdata = new char[toklen+1];
368 memcpy( tokdata, start, toklen );
373 machine section_parse;
380 void Scanner::startSection( )
382 parserExistsError = false;
384 if ( includeDepth == 0 ) {
385 if ( machineSpec == 0 && machineName == 0 )
386 output << "</host>\n";
389 sectionLoc.fileName = fileName;
390 sectionLoc.line = line;
394 void Scanner::endSection( )
396 /* Execute the eof actions for the section parser. */
398 machine section_parse;
402 /* Close off the section with the parser. */
403 if ( active && parserExists() ) {
405 loc.fileName = fileName;
409 parser->token( loc, TK_EndSection, 0, 0 );
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 << "\">";
424 # This is sent by the driver code.
434 # Identifiers, numbers, commetns, and other common things.
435 ident = ( alpha | '_' ) ( alpha |digit |'_' )*;
437 hex_number = '0x' [0-9a-fA-F]+;
440 '/*' ( any | NL )* :>> '*/';
445 c_cpp_comment = c_comment | cpp_comment;
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))* '"';
451 whitespace = [ \t] | NL;
452 pound_comment = '#' [^\n]* NL;
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.
458 # Inline expression keywords.
459 "fpc" => { token( KW_PChar ); };
460 "fc" => { token( KW_Char ); };
461 "fcurs" => { token( KW_CurState ); };
462 "ftargs" => { token( KW_TargState ); };
464 whitespaceOn = false;
468 # Inline statement keywords.
470 whitespaceOn = false;
473 "fexec" => { token( KW_Exec, 0, 0 ); };
475 whitespaceOn = false;
479 whitespaceOn = false;
483 whitespaceOn = false;
487 whitespaceOn = false;
491 whitespaceOn = false;
495 ident => { token( TK_Word, tokstart, tokend ); };
497 number => { token( TK_UInt, tokstart, tokend ); };
498 hex_number => { token( TK_Hex, tokstart, tokend ); };
500 ( s_literal | d_literal )
501 => { token( IL_Literal, tokstart, tokend ); };
505 token( IL_WhiteSpace, tokstart, tokend );
507 c_cpp_comment => { token( IL_Comment, tokstart, tokend ); };
509 "::" => { token( TK_NameSep, tokstart, tokend ); };
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.
519 token( *tokstart, tokstart, tokend );
520 if ( inlineBlockType == SemiTerminated )
526 token( *tokstart, tokstart, tokend );
529 [,(] => { token( *tokstart, tokstart, tokend ); };
532 token( IL_Symbol, tokstart, tokend );
537 if ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {
538 /* Inline code block ends. */
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 );
550 scan_error() << "unterminated code block" << endl;
553 # Send every other character as a symbol.
554 any => { token( IL_Symbol, tokstart, tokend ); };
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 ); };
570 # Range dash in an OR expression.
571 '-' => { token( RE_Dash, 0, 0 ); };
573 # Terminate an OR expression.
574 ']' => { token( RE_SqClose ); fret; };
577 scan_error() << "unterminated OR literal" << endl;
580 # Characters in an OR expression.
581 [^\]] => { token( RE_Char, tokstart, tokend ); };
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 ); };
598 # Terminate an OR expression.
600 token( RE_Slash, tokstart, tokend );
604 # Special characters.
605 '.' => { token( RE_Dot ); };
606 '*' => { token( RE_Star ); };
608 '[' => { token( RE_SqOpen ); fcall or_literal; };
609 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
612 scan_error() << "unterminated regular expression" << endl;
615 # Characters in an OR expression.
616 [^\/] => { token( RE_Char, tokstart, tokend ); };
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; };
626 scan_error() << "unterminated write statement" << endl;
630 # Parser definitions.
632 'machine' => { token( KW_Machine ); };
633 'include' => { token( KW_Include ); };
636 fgoto write_statement;
638 'action' => { token( KW_Action ); };
639 'alphtype' => { token( KW_AlphType ); };
641 # FIXME: Enable this post 5.17.
642 # 'range' => { token( KW_Range ); };
646 inlineBlockType = SemiTerminated;
651 inlineBlockType = SemiTerminated;
655 token( KW_Variable );
656 inlineBlockType = SemiTerminated;
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 ); };
667 ident => { token( TK_Word, tokstart, tokend ); } ;
670 number => { token( TK_UInt, tokstart, tokend ); };
671 hex_number => { token( TK_Hex, tokstart, tokend ); };
673 # Literals, with optionals.
674 ( s_literal | d_literal ) [i]?
675 => { token( TK_Literal, tokstart, tokend ); };
677 '[' => { token( RE_SqOpen ); fcall or_literal; };
678 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
680 '/' => { token( RE_Slash ); fgoto re_literal; };
683 pound_comment => { updateCol(); };
685 ':=' => { token( TK_ColonEquals ); };
688 ">~" => { token( TK_StartToState ); };
689 "$~" => { token( TK_AllToState ); };
690 "%~" => { token( TK_FinalToState ); };
691 "<~" => { token( TK_NotStartToState ); };
692 "@~" => { token( TK_NotFinalToState ); };
693 "<>~" => { token( TK_MiddleToState ); };
696 ">*" => { token( TK_StartFromState ); };
697 "$*" => { token( TK_AllFromState ); };
698 "%*" => { token( TK_FinalFromState ); };
699 "<*" => { token( TK_NotStartFromState ); };
700 "@*" => { token( TK_NotFinalFromState ); };
701 "<>*" => { token( TK_MiddleFromState ); };
704 ">/" => { token( TK_StartEOF ); };
705 "$/" => { token( TK_AllEOF ); };
706 "%/" => { token( TK_FinalEOF ); };
707 "</" => { token( TK_NotStartEOF ); };
708 "@/" => { token( TK_NotFinalEOF ); };
709 "<>/" => { token( TK_MiddleEOF ); };
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 ); };
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 ); };
728 "<>" => { token( TK_Middle ); };
731 '>?' => { token( TK_StartCond ); };
732 '$?' => { token( TK_AllCond ); };
733 '%?' => { token( TK_LeavingCond ); };
735 '..' => { token( TK_DotDot ); };
736 '**' => { token( TK_StarStar ); };
737 '--' => { token( TK_DashDash ); };
738 '->' => { token( TK_Arrow ); };
739 '=>' => { token( TK_DoubleArrow ); };
741 ":>" => { token( TK_ColonGt ); };
742 ":>>" => { token( TK_ColonGtGt ); };
743 "<:" => { token( TK_LtColon ); };
745 # Opening of longest match.
746 "|*" => { token( TK_BarStar ); };
754 [ \t\r]+ => { updateCol(); };
756 # If we are in a single line machine then newline may end the spec.
759 if ( singleLineSpec ) {
768 inlineBlockType = CurlyDelimited;
773 scan_error() << "unterminated ragel section" << endl;
776 any => { token( *tokstart ); } ;
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 );
788 # Outside code scanner. These tokens get passed through.
792 c_cpp_comment => pass;
793 s_literal | d_literal => pass;
796 singleLineSpec = false;
802 singleLineSpec = true;
815 void Scanner::do_scan()
818 char *buf = new char[bufsize];
819 const char last_char = 0;
820 int cs, act, have = 0;
824 bool singleLineSpec = false;
825 InlineBlockType inlineBlockType;
830 char *p = buf + have;
831 int space = bufsize - have;
834 /* We filled up the buffer trying to scan a token. Grow it. */
835 bufsize = bufsize * 2;
836 char *newbuf = new char[bufsize];
838 /* Recompute p and space. */
840 space = bufsize - have;
842 /* Patch up pointers possibly in use. */
844 tokstart = newbuf + ( tokstart - buf );
845 tokend = newbuf + ( tokend - buf );
847 /* Copy the new buffer in. */
848 memcpy( newbuf, buf, have );
853 input.read( p, space );
854 int len = input.gcount();
856 /* If we see eof then append the EOF char. */
858 p[0] = last_char, len = 1;
865 /* Check if we failed. */
866 if ( cs == rlscan_error ) {
867 /* Machine failed before finding a token. I'm not yet sure if this
869 scan_error() << "scanner error" << endl;
873 /* Decide if we need to preserve anything. */
874 char *preserve = tokstart;
876 /* Now set up the prefix. */
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;
885 tokstart -= shiftback;
895 void scan( char *fileName, istream &input, ostream &output )
897 Scanner scanner( fileName, input, output, 0, 0, 0 );
902 eofLoc.fileName = fileName;
904 eofLoc.line = scanner.line;