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), ignoreSection(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::active()
146 if ( parser == 0 && ! parserExistsError ) {
147 scan_error() << "there is no previous specification name" << endl;
148 parserExistsError = true;
157 ostream &Scanner::scan_error()
159 /* Maintain the error count. */
161 cerr << fileName << ":" << line << ":" << column << ": ";
165 bool Scanner::recursiveInclude( char *inclFileName, char *inclSectionName )
167 for ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {
168 if ( strcmp( si->fileName, inclFileName ) == 0 &&
169 strcmp( si->sectionName, inclSectionName ) == 0 )
177 void Scanner::updateCol()
182 //cerr << "adding " << tokend - from << " to column" << endl;
183 column += tokend - from;
187 void Scanner::token( int type, char c )
189 token( type, &c, &c + 1 );
192 void Scanner::token( int type )
198 machine section_parse;
200 # This relies on the the kelbt implementation and the order
201 # that tokens are declared.
208 action clear_words { word = lit = 0; word_len = lit_len = 0; }
209 action store_word { word = tokdata; word_len = toklen; }
210 action store_lit { lit = tokdata; lit_len = toklen; }
212 action mach_err { scan_error() << "bad machine statement" << endl; }
213 action incl_err { scan_error() << "bad include statement" << endl; }
214 action write_err { scan_error() << "bad write statement" << endl; }
216 action handle_machine
218 /* Assign a name to the machine. */
219 char *machine = word;
221 if ( inclSectionTarg == 0 ) {
222 ignoreSection = false;
224 ParserDictEl *pdEl = parserDict.find( machine );
226 pdEl = new ParserDictEl( machine );
227 pdEl->value = new Parser( fileName, machine, sectionLoc );
229 parserDict.insert( pdEl );
232 parser = pdEl->value;
234 else if ( strcmp( inclSectionTarg, machine ) == 0 ) {
235 /* found include target */
236 ignoreSection = false;
237 parser = inclToParser;
240 /* ignoring section */
241 ignoreSection = true;
247 ( KW_Machine TK_Word @store_word ';' ) @handle_machine
248 <>err mach_err <>eof mach_err;
250 action handle_include
253 char *inclSectionName = word;
254 char *inclFileName = 0;
256 /* Implement defaults for the input file and section name. */
257 if ( inclSectionName == 0 )
258 inclSectionName = parser->sectionName;
261 inclFileName = prepareFileName( lit, lit_len );
263 inclFileName = fileName;
265 /* Check for a recursive include structure. Add the current file/section
266 * name then check if what we are including is already in the stack. */
267 includeStack.append( IncludeStackItem( fileName, parser->sectionName ) );
269 if ( recursiveInclude( inclFileName, inclSectionName ) )
270 scan_error() << "include: this is a recursive include operation" << endl;
272 /* Open the input file for reading. */
273 ifstream *inFile = new ifstream( inclFileName );
274 if ( ! inFile->is_open() ) {
275 scan_error() << "include: could not open " <<
276 inclFileName << " for reading" << endl;
279 Scanner scanner( inclFileName, *inFile, output, parser,
280 inclSectionName, includeDepth+1 );
286 /* Remove the last element (len-1) */
287 includeStack.remove( -1 );
292 TK_Word @store_word ( TK_Literal @store_lit )? |
293 TK_Literal @store_lit
297 ( KW_Include include_names ';' ) @handle_include
298 <>err incl_err <>eof incl_err;
302 if ( active() && machineSpec == 0 && machineName == 0 ) {
304 " def_name=\"" << parser->sectionName << "\""
305 " line=\"" << line << "\""
306 " col=\"" << column << "\""
313 if ( active() && machineSpec == 0 && machineName == 0 )
314 output << "<arg>" << tokdata << "</arg>";
319 if ( active() && machineSpec == 0 && machineName == 0 )
320 output << "</write>\n";
324 ( KW_Write @write_command
325 ( TK_Word @write_arg )+ ';' @write_close )
326 <>err write_err <>eof write_err;
330 /* Send the token off to the parser. */
335 cerr << "scanner:" << line << ":" << column <<
336 ": sending token to the parser " << 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";
393 sectionLoc.fileName = fileName;
394 sectionLoc.line = line;
398 void Scanner::endSection( )
400 /* Execute the eof actions for the section parser. */
402 machine section_parse;
406 /* Close off the section with the parser. */
409 loc.fileName = fileName;
413 parser->token( loc, TK_EndSection, 0, 0 );
416 if ( includeDepth == 0 ) {
417 if ( machineSpec == 0 && machineName == 0 ) {
418 /* The end section may include a newline on the end, so
419 * we use the last line, which will count the newline. */
420 output << "<host line=\"" << line << "\">";
428 # This is sent by the driver code.
438 # Identifiers, numbers, commetns, and other common things.
439 ident = ( alpha | '_' ) ( alpha |digit |'_' )*;
441 hex_number = '0x' [0-9a-fA-F]+;
444 '/*' ( any | NL )* :>> '*/';
449 c_cpp_comment = c_comment | cpp_comment;
451 # These literal forms are common to C-like host code and ragel.
452 s_literal = "'" ([^'\\] | NL | '\\' (any | NL))* "'";
453 d_literal = '"' ([^"\\] | NL | '\\' (any | NL))* '"';
455 whitespace = [ \t] | NL;
456 pound_comment = '#' [^\n]* NL;
458 # An inline block of code. This is specified as a scanned, but is sent to
459 # the parser as one long block. The inline_block pointer is used to handle
460 # the preservation of the data.
462 # Inline expression keywords.
463 "fpc" => { token( KW_PChar ); };
464 "fc" => { token( KW_Char ); };
465 "fcurs" => { token( KW_CurState ); };
466 "ftargs" => { token( KW_TargState ); };
468 whitespaceOn = false;
472 # Inline statement keywords.
474 whitespaceOn = false;
477 "fexec" => { token( KW_Exec, 0, 0 ); };
479 whitespaceOn = false;
483 whitespaceOn = false;
487 whitespaceOn = false;
491 whitespaceOn = false;
495 whitespaceOn = false;
499 ident => { token( TK_Word, tokstart, tokend ); };
501 number => { token( TK_UInt, tokstart, tokend ); };
502 hex_number => { token( TK_Hex, tokstart, tokend ); };
504 ( s_literal | d_literal )
505 => { token( IL_Literal, tokstart, tokend ); };
509 token( IL_WhiteSpace, tokstart, tokend );
511 c_cpp_comment => { token( IL_Comment, tokstart, tokend ); };
513 "::" => { token( TK_NameSep, tokstart, tokend ); };
515 # Some symbols need to go to the parser as with their cardinal value as
516 # the token type (as opposed to being sent as anonymous symbols)
517 # because they are part of the sequences which we interpret. The * ) ;
518 # symbols cause whitespace parsing to come back on. This gets turned
519 # off by some keywords.
523 token( *tokstart, tokstart, tokend );
524 if ( inlineBlockType == SemiTerminated )
530 token( *tokstart, tokstart, tokend );
533 [,(] => { token( *tokstart, tokstart, tokend ); };
536 token( IL_Symbol, tokstart, tokend );
541 if ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {
542 /* Inline code block ends. */
547 /* Either a semi terminated inline block or only the closing
548 * brace of some inner scope, not the block's closing brace. */
549 token( IL_Symbol, tokstart, tokend );
554 scan_error() << "unterminated code block" << endl;
557 # Send every other character as a symbol.
558 any => { token( IL_Symbol, tokstart, tokend ); };
562 # Escape sequences in OR expressions.
563 '\\0' => { token( RE_Char, '\0' ); };
564 '\\a' => { token( RE_Char, '\a' ); };
565 '\\b' => { token( RE_Char, '\b' ); };
566 '\\t' => { token( RE_Char, '\t' ); };
567 '\\n' => { token( RE_Char, '\n' ); };
568 '\\v' => { token( RE_Char, '\v' ); };
569 '\\f' => { token( RE_Char, '\f' ); };
570 '\\r' => { token( RE_Char, '\r' ); };
571 '\\\n' => { updateCol(); };
572 '\\' any => { token( RE_Char, tokstart+1, tokend ); };
574 # Range dash in an OR expression.
575 '-' => { token( RE_Dash, 0, 0 ); };
577 # Terminate an OR expression.
578 ']' => { token( RE_SqClose ); fret; };
581 scan_error() << "unterminated OR literal" << endl;
584 # Characters in an OR expression.
585 [^\]] => { token( RE_Char, tokstart, tokend ); };
590 # Escape sequences in regular expressions.
591 '\\0' => { token( RE_Char, '\0' ); };
592 '\\a' => { token( RE_Char, '\a' ); };
593 '\\b' => { token( RE_Char, '\b' ); };
594 '\\t' => { token( RE_Char, '\t' ); };
595 '\\n' => { token( RE_Char, '\n' ); };
596 '\\v' => { token( RE_Char, '\v' ); };
597 '\\f' => { token( RE_Char, '\f' ); };
598 '\\r' => { token( RE_Char, '\r' ); };
599 '\\\n' => { updateCol(); };
600 '\\' any => { token( RE_Char, tokstart+1, tokend ); };
602 # Terminate an OR expression.
604 token( RE_Slash, tokstart, tokend );
608 # Special characters.
609 '.' => { token( RE_Dot ); };
610 '*' => { token( RE_Star ); };
612 '[' => { token( RE_SqOpen ); fcall or_literal; };
613 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
616 scan_error() << "unterminated regular expression" << endl;
619 # Characters in an OR expression.
620 [^\/] => { token( RE_Char, tokstart, tokend ); };
623 # We need a separate token space here to avoid the ragel keywords.
624 write_statement := |*
625 ident => { token( TK_Word, tokstart, tokend ); } ;
626 [ \t\n]+ => { updateCol(); };
627 ';' => { token( ';' ); fgoto parser_def; };
630 scan_error() << "unterminated write statement" << endl;
634 # Parser definitions.
636 'machine' => { token( KW_Machine ); };
637 'include' => { token( KW_Include ); };
640 fgoto write_statement;
642 'action' => { token( KW_Action ); };
643 'alphtype' => { token( KW_AlphType ); };
645 # FIXME: Enable this post 5.17.
646 # 'range' => { token( KW_Range ); };
650 inlineBlockType = SemiTerminated;
655 inlineBlockType = SemiTerminated;
659 token( KW_Variable );
660 inlineBlockType = SemiTerminated;
663 'when' => { token( KW_When ); };
664 'eof' => { token( KW_Eof ); };
665 'err' => { token( KW_Err ); };
666 'lerr' => { token( KW_Lerr ); };
667 'to' => { token( KW_To ); };
668 'from' => { token( KW_From ); };
671 ident => { token( TK_Word, tokstart, tokend ); } ;
674 number => { token( TK_UInt, tokstart, tokend ); };
675 hex_number => { token( TK_Hex, tokstart, tokend ); };
677 # Literals, with optionals.
678 ( s_literal | d_literal ) [i]?
679 => { token( TK_Literal, tokstart, tokend ); };
681 '[' => { token( RE_SqOpen ); fcall or_literal; };
682 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
684 '/' => { token( RE_Slash ); fgoto re_literal; };
687 pound_comment => { updateCol(); };
689 ':=' => { token( TK_ColonEquals ); };
692 ">~" => { token( TK_StartToState ); };
693 "$~" => { token( TK_AllToState ); };
694 "%~" => { token( TK_FinalToState ); };
695 "<~" => { token( TK_NotStartToState ); };
696 "@~" => { token( TK_NotFinalToState ); };
697 "<>~" => { token( TK_MiddleToState ); };
700 ">*" => { token( TK_StartFromState ); };
701 "$*" => { token( TK_AllFromState ); };
702 "%*" => { token( TK_FinalFromState ); };
703 "<*" => { token( TK_NotStartFromState ); };
704 "@*" => { token( TK_NotFinalFromState ); };
705 "<>*" => { token( TK_MiddleFromState ); };
708 ">/" => { token( TK_StartEOF ); };
709 "$/" => { token( TK_AllEOF ); };
710 "%/" => { token( TK_FinalEOF ); };
711 "</" => { token( TK_NotStartEOF ); };
712 "@/" => { token( TK_NotFinalEOF ); };
713 "<>/" => { token( TK_MiddleEOF ); };
715 # Global Error actions.
716 ">!" => { token( TK_StartGblError ); };
717 "$!" => { token( TK_AllGblError ); };
718 "%!" => { token( TK_FinalGblError ); };
719 "<!" => { token( TK_NotStartGblError ); };
720 "@!" => { token( TK_NotFinalGblError ); };
721 "<>!" => { token( TK_MiddleGblError ); };
723 # Local error actions.
724 ">^" => { token( TK_StartLocalError ); };
725 "$^" => { token( TK_AllLocalError ); };
726 "%^" => { token( TK_FinalLocalError ); };
727 "<^" => { token( TK_NotStartLocalError ); };
728 "@^" => { token( TK_NotFinalLocalError ); };
729 "<>^" => { token( TK_MiddleLocalError ); };
732 "<>" => { token( TK_Middle ); };
735 '>?' => { token( TK_StartCond ); };
736 '$?' => { token( TK_AllCond ); };
737 '%?' => { token( TK_LeavingCond ); };
739 '..' => { token( TK_DotDot ); };
740 '**' => { token( TK_StarStar ); };
741 '--' => { token( TK_DashDash ); };
742 '->' => { token( TK_Arrow ); };
743 '=>' => { token( TK_DoubleArrow ); };
745 ":>" => { token( TK_ColonGt ); };
746 ":>>" => { token( TK_ColonGtGt ); };
747 "<:" => { token( TK_LtColon ); };
749 # Opening of longest match.
750 "|*" => { token( TK_BarStar ); };
758 [ \t\r]+ => { updateCol(); };
760 # If we are in a single line machine then newline may end the spec.
763 if ( singleLineSpec ) {
772 inlineBlockType = CurlyDelimited;
777 scan_error() << "unterminated ragel section" << endl;
780 any => { token( *tokstart ); } ;
786 /* If no errors and we are at the bottom of the include stack (the
787 * source file listed on the command line) then write out the data. */
788 if ( includeDepth == 0 && machineSpec == 0 && machineName == 0 )
789 xmlEscapeHost( output, tokstart, tokend-tokstart );
792 # Outside code scanner. These tokens get passed through.
796 c_cpp_comment => pass;
797 s_literal | d_literal => pass;
800 singleLineSpec = false;
806 singleLineSpec = true;
819 void Scanner::do_scan()
822 char *buf = new char[bufsize];
823 const char last_char = 0;
824 int cs, act, have = 0;
828 bool singleLineSpec = false;
829 InlineBlockType inlineBlockType;
834 char *p = buf + have;
835 int space = bufsize - have;
838 /* We filled up the buffer trying to scan a token. Grow it. */
839 bufsize = bufsize * 2;
840 char *newbuf = new char[bufsize];
842 /* Recompute p and space. */
844 space = bufsize - have;
846 /* Patch up pointers possibly in use. */
848 tokstart = newbuf + ( tokstart - buf );
849 tokend = newbuf + ( tokend - buf );
851 /* Copy the new buffer in. */
852 memcpy( newbuf, buf, have );
857 input.read( p, space );
858 int len = input.gcount();
860 /* If we see eof then append the EOF char. */
862 p[0] = last_char, len = 1;
869 /* Check if we failed. */
870 if ( cs == rlscan_error ) {
871 /* Machine failed before finding a token. I'm not yet sure if this
873 scan_error() << "scanner error" << endl;
877 /* Decide if we need to preserve anything. */
878 char *preserve = tokstart;
880 /* Now set up the prefix. */
884 /* There is data that needs to be shifted over. */
885 have = pe - preserve;
886 memmove( buf, preserve, have );
887 unsigned int shiftback = preserve - buf;
889 tokstart -= shiftback;
899 void scan( char *fileName, istream &input, ostream &output )
901 Scanner scanner( fileName, input, output, 0, 0, 0 );
906 eofLoc.fileName = fileName;
908 eofLoc.line = scanner.line;