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;
52 IncludeStack includeStack;
62 Scanner( char *fileName, istream &input,
63 Parser *inclToParser, char *inclSectionTarg,
66 fileName(fileName), input(input),
67 inclToParser(inclToParser),
68 inclSectionTarg(inclSectionTarg),
69 include_depth(include_depth),
70 line(1), column(1), lastnl(0),
71 parser(0), active(false),
72 parserExistsError(false), ragelDefOpen(false),
76 bool recursiveInclude( IncludeStack &includeStack,
77 char *inclFileName, char *inclSectionName );
79 char *prepareFileName( char *fileName, int len )
82 Token tokenFnStr, tokenRes;
83 tokenFnStr.data = fileName;
84 tokenFnStr.length = len;
85 tokenFnStr.prepareLitString( tokenRes, caseInsensitive );
90 void token( int type, char *start, char *end );
91 void token( int type, char c );
92 void token( int type );
103 Parser *inclToParser;
104 char *inclSectionTarg;
110 int word_len, lit_len;
112 char *tokstart, *tokend;
116 /* Set by machine statements, these persist from section to section
117 * allowing for unnamed sections. */
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 error() << "include: there is no previous specification name" << endl;
149 parserExistsError = true;
154 ostream &Scanner::error()
156 /* Maintain the error count. */
159 cerr << fileName << ":" << line << ":" << column << ": ";
163 bool Scanner::recursiveInclude( IncludeStack &includeStack,
164 char *inclFileName, char *inclSectionName )
166 for ( IncludeStack::Iter si = includeStack; si.lte(); si++ ) {
167 if ( strcmp( si->fileName, inclFileName ) == 0 &&
168 strcmp( si->sectionName, inclSectionName ) == 0 )
176 void Scanner::updateCol()
181 //cerr << "adding " << tokend - from << " to column" << endl;
182 column += tokend - from;
186 void Scanner::token( int type, char c )
188 token( type, &c, &c + 1 );
191 void Scanner::token( int type )
197 machine section_parse;
199 # This relies on the the kelbt implementation and the order
200 # that tokens are declared.
207 action clear_words { word = lit = 0; word_len = lit_len = 0; }
208 action store_word { word = tokdata; word_len = toklen; }
209 action store_lit { lit = tokdata; lit_len = toklen; }
211 action mach_err { error() << "bad machine statement" << endl; }
212 action incl_err { error() << "bad include statement" << endl; }
213 action write_err { error() << "bad write statement" << endl; }
215 action handle_machine
217 /* Assign a name to the machine. */
218 char *machine = word;
220 if ( inclSectionTarg == 0 ) {
223 ParserDictEl *pdEl = parserDict.find( machine );
225 pdEl = new ParserDictEl( machine );
226 pdEl->value = new Parser( fileName, machine, sectionLoc );
228 parserDict.insert( pdEl );
231 parser = pdEl->value;
233 else if ( strcmp( inclSectionTarg, machine ) == 0 ) {
234 /* found include target */
236 parser = inclToParser;
239 /* ignoring section */
246 ( KW_Machine TK_Word @store_word ';' ) @handle_machine
247 <>err mach_err <>eof mach_err;
249 action handle_include
251 if ( active && parserExists() ) {
252 char *inclSectionName = word;
253 char *inclFileName = 0;
255 /* Implement defaults for the input file and section name. */
256 if ( inclSectionName == 0 )
257 inclSectionName = parser->sectionName;
260 inclFileName = prepareFileName( lit, lit_len );
262 inclFileName = fileName;
264 /* Check for a recursive include structure. Add the current file/section
265 * name then check if what we are including is already in the stack. */
266 includeStack.append( IncludeStackItem( fileName, parser->sectionName ) );
268 if ( recursiveInclude( includeStack, inclFileName, inclSectionName ) )
269 error() << "include: this is a recursive include operation" << endl;
271 /* Open the input file for reading. */
272 ifstream *inFile = new ifstream( inclFileName );
273 if ( ! inFile->is_open() ) {
274 error() << "include: could not open " <<
275 inclFileName << " for reading" << endl;
278 Scanner scanner( inclFileName, *inFile, parser,
279 inclSectionName, include_depth+1 );
285 /* Remove the last element (len-1) */
286 includeStack.remove( -1 );
291 TK_Word @store_word ( TK_Literal @store_lit )? |
292 TK_Literal @store_lit
296 ( KW_Include include_names ';' ) @handle_include
297 <>err incl_err <>eof incl_err;
303 if ( strcmp( tokdata, "data" ) != 0 &&
304 strcmp( tokdata, "init" ) != 0 &&
305 strcmp( tokdata, "exec" ) != 0 &&
306 strcmp( tokdata, "eof" ) != 0 )
308 error() << "unknown write command" << endl;
310 *outStream << " <write what=\"" << tokdata << "\">";
317 *outStream << "<option>" << tokdata << "</option>";
322 *outStream << "</write>\n";
326 ( KW_Write TK_Word @write_command
327 ( TK_Word @write_option )* ';' @write_close )
328 <>err write_err <>eof write_err;
332 /* Send the token off to the parser. */
333 if ( active && parserExists() ) {
337 cerr << "scanner:" << line << ":" << column <<
338 ": sending token to the parser " << lelNames[*p];
339 cerr << " " << toklen;
341 cerr << " " << tokdata;
345 loc.fileName = fileName;
349 parser->token( loc, type, tokdata, toklen );
353 # Catch everything else.
354 everything_else = ^( KW_Machine | KW_Include | KW_Write ) @handle_token;
364 void Scanner::token( int type, char *start, char *end )
373 tokdata = new char[toklen+1];
374 memcpy( tokdata, start, toklen );
379 machine section_parse;
386 void Scanner::startSection( )
388 parserExistsError = false;
390 if ( include_depth == 0 ) {
391 if ( machineSpec == 0 && machineName == 0 )
392 *outStream << "</host>\n";
393 ragelDefOpen = false;
396 sectionLoc.fileName = fileName;
397 sectionLoc.line = line;
401 void Scanner::openRagelDef()
403 if ( ! ragelDefOpen ) {
405 *outStream << "<ragel_def name=\"" << parser->sectionName << "\">\n";
409 void Scanner::endSection( )
411 /* Execute the eof actions for the section parser. */
413 machine section_parse;
417 /* Close off the section with the parser. */
418 if ( active && parserExists() ) {
420 loc.fileName = fileName;
424 parser->token( loc, TK_EndSection, 0, 0 );
427 if ( include_depth == 0 ) {
428 if ( ragelDefOpen ) {
429 *outStream << "</ragel_def>\n";
430 ragelDefOpen = false;
433 if ( machineSpec == 0 && machineName == 0 ) {
434 /* The end section may include a newline on the end, so
435 * we use the last line, which will count the newline. */
436 *outStream << "<host line=\"" << line << "\">";
444 # This is sent by the driver code.
454 # Identifiers, numbers, commetns, and other common things.
455 ident = ( alpha | '_' ) ( alpha |digit |'_' )*;
457 hex_number = '0x' [0-9a-fA-F]+;
460 '/*' ( any | NL )* :>> '*/';
465 c_cpp_comment = c_comment | cpp_comment;
467 # These literal forms are common to C-like host code and ragel.
468 s_literal = "'" ([^'\\] | NL | '\\' (any | NL))* "'";
469 d_literal = '"' ([^"\\] | NL | '\\' (any | NL))* '"';
471 whitespace = [ \t] | NL;
472 pound_comment = '#' [^\n]* NL;
474 # An inline block of code. This is specified as a scanned, but is sent to
475 # the parser as one long block. The inline_block pointer is used to handle
476 # the preservation of the data.
478 # Inline expression keywords.
479 "fpc" => { token( KW_PChar ); };
480 "fc" => { token( KW_Char ); };
481 "fcurs" => { token( KW_CurState ); };
482 "ftargs" => { token( KW_TargState ); };
484 whitespaceOn = false;
488 # Inline statement keywords.
490 whitespaceOn = false;
493 "fexec" => { token( KW_Exec, 0, 0 ); };
495 whitespaceOn = false;
499 whitespaceOn = false;
503 whitespaceOn = false;
507 whitespaceOn = false;
511 whitespaceOn = false;
515 ident => { token( TK_Word, tokstart, tokend ); };
517 number => { token( TK_UInt, tokstart, tokend ); };
518 hex_number => { token( TK_Hex, tokstart, tokend ); };
520 ( s_literal | d_literal )
521 => { token( IL_Literal, tokstart, tokend ); };
525 token( IL_WhiteSpace, tokstart, tokend );
527 c_cpp_comment => { token( IL_Comment, tokstart, tokend ); };
529 "::" => { token( TK_NameSep, tokstart, tokend ); };
531 # Some symbols need to go to the parser as with their cardinal value as
532 # the token type (as opposed to being sent as anonymous symbols)
533 # because they are part of the sequences which we interpret. The * ) ;
534 # symbols cause whitespace parsing to come back on. This gets turned
535 # off by some keywords.
539 token( *tokstart, tokstart, tokend );
540 if ( inlineBlockType == SemiTerminated )
546 token( *tokstart, tokstart, tokend );
549 [,(] => { token( *tokstart, tokstart, tokend ); };
552 token( IL_Symbol, tokstart, tokend );
557 if ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {
558 /* Inline code block ends. */
563 /* Either a semi terminated inline block or only the closing
564 * brace of some inner scope, not the block's closing brace. */
565 token( IL_Symbol, tokstart, tokend );
570 error() << "unterminated code block" << endl;
573 # Send every other character as a symbol.
574 any => { token( IL_Symbol, tokstart, tokend ); };
578 # Escape sequences in OR expressions.
579 '\\0' => { token( RE_Char, '\0' ); };
580 '\\a' => { token( RE_Char, '\a' ); };
581 '\\b' => { token( RE_Char, '\b' ); };
582 '\\t' => { token( RE_Char, '\t' ); };
583 '\\n' => { token( RE_Char, '\n' ); };
584 '\\v' => { token( RE_Char, '\v' ); };
585 '\\f' => { token( RE_Char, '\f' ); };
586 '\\r' => { token( RE_Char, '\r' ); };
587 '\\\n' => { updateCol(); };
588 '\\' any => { token( RE_Char, tokstart+1, tokend ); };
590 # Range dash in an OR expression.
591 '-' => { token( RE_Dash, 0, 0 ); };
593 # Terminate an OR expression.
594 ']' => { token( RE_SqClose ); fret; };
597 error() << "unterminated OR literal" << endl;
600 # Characters in an OR expression.
601 [^\]] => { token( RE_Char, tokstart, tokend ); };
606 # Escape sequences in regular expressions.
607 '\\0' => { token( RE_Char, '\0' ); };
608 '\\a' => { token( RE_Char, '\a' ); };
609 '\\b' => { token( RE_Char, '\b' ); };
610 '\\t' => { token( RE_Char, '\t' ); };
611 '\\n' => { token( RE_Char, '\n' ); };
612 '\\v' => { token( RE_Char, '\v' ); };
613 '\\f' => { token( RE_Char, '\f' ); };
614 '\\r' => { token( RE_Char, '\r' ); };
615 '\\\n' => { updateCol(); };
616 '\\' any => { token( RE_Char, tokstart+1, tokend ); };
618 # Terminate an OR expression.
620 token( RE_Slash, tokstart, tokend );
624 # Special characters.
625 '.' => { token( RE_Dot ); };
626 '*' => { token( RE_Star ); };
628 '[' => { token( RE_SqOpen ); fcall or_literal; };
629 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
632 error() << "unterminated regular expression" << endl;
635 # Characters in an OR expression.
636 [^\/] => { token( RE_Char, tokstart, tokend ); };
639 write_statement := |*
640 ident => { token( TK_Word, tokstart, tokend ); } ;
641 [ \t\n]+ => { updateCol(); };
642 ';' => { token( ';' ); fgoto parser_def; };
645 error() << "unterminated write statement" << endl;
649 # Parser definitions.
651 'machine' => { token( KW_Machine ); };
652 'include' => { token( KW_Include ); };
655 fgoto write_statement;
657 'action' => { token( KW_Action ); };
658 'alphtype' => { token( KW_AlphType ); };
660 # FIXME: Enable this post 5.17.
661 # 'range' => { token( KW_Range ); };
665 inlineBlockType = SemiTerminated;
670 inlineBlockType = SemiTerminated;
674 token( KW_Variable );
675 inlineBlockType = SemiTerminated;
678 'when' => { token( KW_When ); };
679 'eof' => { token( KW_Eof ); };
680 'err' => { token( KW_Err ); };
681 'lerr' => { token( KW_Lerr ); };
682 'to' => { token( KW_To ); };
683 'from' => { token( KW_From ); };
686 ident => { token( TK_Word, tokstart, tokend ); } ;
689 number => { token( TK_UInt, tokstart, tokend ); };
690 hex_number => { token( TK_Hex, tokstart, tokend ); };
692 # Literals, with optionals.
693 ( s_literal | d_literal ) [i]?
694 => { token( TK_Literal, tokstart, tokend ); };
696 '[' => { token( RE_SqOpen ); fcall or_literal; };
697 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
699 '/' => { token( RE_Slash ); fgoto re_literal; };
702 pound_comment => { updateCol(); };
704 ':=' => { token( TK_ColonEquals ); };
707 ">~" => { token( TK_StartToState ); };
708 "$~" => { token( TK_AllToState ); };
709 "%~" => { token( TK_FinalToState ); };
710 "<~" => { token( TK_NotStartToState ); };
711 "@~" => { token( TK_NotFinalToState ); };
712 "<>~" => { token( TK_MiddleToState ); };
715 ">*" => { token( TK_StartFromState ); };
716 "$*" => { token( TK_AllFromState ); };
717 "%*" => { token( TK_FinalFromState ); };
718 "<*" => { token( TK_NotStartFromState ); };
719 "@*" => { token( TK_NotFinalFromState ); };
720 "<>*" => { token( TK_MiddleFromState ); };
723 ">/" => { token( TK_StartEOF ); };
724 "$/" => { token( TK_AllEOF ); };
725 "%/" => { token( TK_FinalEOF ); };
726 "</" => { token( TK_NotStartEOF ); };
727 "@/" => { token( TK_NotFinalEOF ); };
728 "<>/" => { token( TK_MiddleEOF ); };
730 # Global Error actions.
731 ">!" => { token( TK_StartGblError ); };
732 "$!" => { token( TK_AllGblError ); };
733 "%!" => { token( TK_FinalGblError ); };
734 "<!" => { token( TK_NotStartGblError ); };
735 "@!" => { token( TK_NotFinalGblError ); };
736 "<>!" => { token( TK_MiddleGblError ); };
738 # Local error actions.
739 ">^" => { token( TK_StartLocalError ); };
740 "$^" => { token( TK_AllLocalError ); };
741 "%^" => { token( TK_FinalLocalError ); };
742 "<^" => { token( TK_NotStartLocalError ); };
743 "@^" => { token( TK_NotFinalLocalError ); };
744 "<>^" => { token( TK_MiddleLocalError ); };
747 "<>" => { token( TK_Middle ); };
750 '>?' => { token( TK_StartCond ); };
751 '$?' => { token( TK_AllCond ); };
752 '%?' => { token( TK_LeavingCond ); };
754 '..' => { token( TK_DotDot ); };
755 '**' => { token( TK_StarStar ); };
756 '--' => { token( TK_DashDash ); };
757 '->' => { token( TK_Arrow ); };
758 '=>' => { token( TK_DoubleArrow ); };
760 ":>" => { token( TK_ColonGt ); };
761 ":>>" => { token( TK_ColonGtGt ); };
762 "<:" => { token( TK_LtColon ); };
764 # Opening of longest match.
765 "|*" => { token( TK_BarStar ); };
768 /* In order to generate anything we must be in the top level file
769 * and the current spec must be active and there must not have been
770 * any parse errors. */
776 [ \t]+ => { updateCol(); };
778 # If we are in a single line machine then newline may end the spec.
781 if ( singleLineSpec ) {
782 /* In order to generate anything we must be in the top level file
783 * and the current spec must be active and there must not have been
784 * any parse errors. */
793 inlineBlockType = CurlyDelimited;
798 error() << "unterminated ragel section" << endl;
801 any => { token( *tokstart ); } ;
807 /* If no errors and we are at the bottom of the include stack (the
808 * source file listed on the command line) then write out the data. */
809 if ( include_depth == 0 && machineSpec == 0 && machineName == 0 )
810 xmlEscapeHost( *outStream, tokstart, tokend-tokstart );
813 # Outside code scanner. These tokens get passed through.
817 c_cpp_comment => pass;
818 s_literal | d_literal => pass;
821 singleLineSpec = false;
827 singleLineSpec = true;
840 void Scanner::do_scan()
843 char *buf = new char[bufsize];
844 const char last_char = 0;
845 int cs, act, have = 0;
849 bool singleLineSpec = false;
850 InlineBlockType inlineBlockType;
855 char *p = buf + have;
856 int space = bufsize - have;
859 /* We filled up the buffer trying to scan a token. Grow it. */
860 bufsize = bufsize * 2;
861 char *newbuf = new char[bufsize];
863 /* Recompute p and space. */
865 space = bufsize - have;
867 /* Patch up pointers possibly in use. */
869 tokstart = newbuf + ( tokstart - buf );
870 tokend = newbuf + ( tokend - buf );
872 /* Copy the new buffer in. */
873 memcpy( newbuf, buf, have );
878 input.read( p, space );
879 int len = input.gcount();
881 /* If we see eof then append the EOF char. */
883 p[0] = last_char, len = 1;
890 /* Check if we failed. */
891 if ( cs == rlscan_error ) {
892 /* Machine failed before finding a token. I'm not yet sure if this
894 error() << "scanner error" << endl;
898 /* Decide if we need to preserve anything. */
899 char *preserve = tokstart;
901 /* Now set up the prefix. */
905 /* There is data that needs to be shifted over. */
906 have = pe - preserve;
907 memmove( buf, preserve, have );
908 unsigned int shiftback = preserve - buf;
910 tokstart -= shiftback;
920 void scan( char *fileName, istream &input )
922 Scanner scanner( fileName, input, 0, 0, 0 );
927 eofLoc.fileName = fileName;
929 eofLoc.line = scanner.line;