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;
219 //cerr << "scanner: machine statement: " << machine << endl;
221 if ( inclSectionTarg == 0 ) {
224 ParserDictEl *pdEl = parserDict.find( machine );
226 //cerr << "scanner: using existing parser" << endl;
229 //cerr << "scanner: creating a new parser" << endl;
230 pdEl = new ParserDictEl( machine );
231 pdEl->value = new Parser( fileName, machine, sectionLoc );
233 parserDict.insert( pdEl );
236 parser = pdEl->value;
238 else if ( strcmp( inclSectionTarg, machine ) == 0 ) {
239 //cerr << "scanner: found include target" << endl;
241 parser = inclToParser;
244 //cerr << "scanner: ignoring section" << endl;
251 ( KW_Machine TK_Word @store_word ';' ) @handle_machine
252 <>err mach_err <>eof mach_err;
254 action handle_include
256 if ( active && parserExists() ) {
257 char *inclSectionName = word;
258 char *inclFileName = 0;
260 /* Implement defaults for the input file and section name. */
261 if ( inclSectionName == 0 )
262 inclSectionName = parser->sectionName;
265 inclFileName = prepareFileName( lit, lit_len );
267 inclFileName = fileName;
269 /* Open the file and process it. */
270 //cerr << "scanner: include: " << inclSectionName << " " << inclFileName << endl;
272 /* Check for a recursive include structure. Add the current file/section
273 * name then check if what we are including is already in the stack. */
274 includeStack.append( IncludeStackItem( fileName, parser->sectionName ) );
276 if ( recursiveInclude( includeStack, inclFileName, inclSectionName ) )
277 error() << "include: this is a recursive include operation" << endl;
279 /* Open the input file for reading. */
280 ifstream *inFile = new ifstream( inclFileName );
281 if ( ! inFile->is_open() ) {
282 error() << "include: could not open " <<
283 inclFileName << " for reading" << endl;
286 Scanner scanner( inclFileName, *inFile, parser,
287 inclSectionName, include_depth+1 );
293 /* Remove the last element (len-1) */
294 includeStack.remove( -1 );
299 TK_Word @store_word ( TK_Literal @store_lit )? |
300 TK_Literal @store_lit
304 ( KW_Include include_names ';' ) @handle_include
305 <>err incl_err <>eof incl_err;
311 if ( strcmp( tokdata, "data" ) != 0 &&
312 strcmp( tokdata, "init" ) != 0 &&
313 strcmp( tokdata, "exec" ) != 0 &&
314 strcmp( tokdata, "eof" ) != 0 )
316 error() << "unknown write command" << endl;
318 *outStream << " <write what=\"" << tokdata << "\">";
325 *outStream << "<option>" << tokdata << "</option>";
330 *outStream << "</write>\n";
334 ( KW_Write TK_Word @write_command
335 ( TK_Word @write_option )* ';' @write_close )
336 <>err write_err <>eof write_err;
340 /* Send the token off to the parser. */
341 if ( active && parserExists() ) {
345 cerr << "scanner:" << line << ":" << column <<
346 ": sending token to the parser " << lelNames[*p];
347 cerr << " " << toklen;
349 cerr << " " << tokdata;
353 loc.fileName = fileName;
357 parser->token( loc, type, tokdata, toklen );
361 # Catch everything else.
362 everything_else = ^( KW_Machine | KW_Include | KW_Write ) @handle_token;
372 void Scanner::token( int type, char *start, char *end )
381 tokdata = new char[toklen+1];
382 memcpy( tokdata, start, toklen );
387 machine section_parse;
394 void Scanner::startSection( )
396 parserExistsError = false;
398 if ( include_depth == 0 ) {
399 if ( machineSpec == 0 && machineName == 0 )
400 *outStream << "</host>\n";
401 ragelDefOpen = false;
404 sectionLoc.fileName = fileName;
405 sectionLoc.line = line;
409 void Scanner::openRagelDef()
411 if ( ! ragelDefOpen ) {
413 *outStream << "<ragel_def name=\"" << parser->sectionName << "\">\n";
417 void Scanner::endSection( )
419 /* Execute the eof actions for the section parser. */
421 machine section_parse;
425 /* Close off the section with the parser. */
426 if ( active && parserExists() ) {
428 loc.fileName = fileName;
432 parser->token( loc, TK_EndSection, 0, 0 );
435 if ( include_depth == 0 ) {
436 if ( ragelDefOpen ) {
437 *outStream << "</ragel_def>\n";
438 ragelDefOpen = false;
441 if ( machineSpec == 0 && machineName == 0 ) {
442 /* The end section may include a newline on the end, so
443 * we use the last line, which will count the newline. */
444 *outStream << "<host line=\"" << line << "\">";
452 # This is sent by the driver code.
462 # Identifiers, numbers, commetns, and other common things.
463 ident = ( alpha | '_' ) ( alpha |digit |'_' )*;
465 hex_number = '0x' [0-9a-fA-F]+;
468 '/*' ( any | NL )* :>> '*/';
473 c_cpp_comment = c_comment | cpp_comment;
475 # These literal forms are common to C-like host code and ragel.
476 s_literal = "'" ([^'\\] | NL | '\\' (any | NL))* "'";
477 d_literal = '"' ([^"\\] | NL | '\\' (any | NL))* '"';
479 whitespace = [ \t] | NL;
480 pound_comment = '#' [^\n]* NL;
482 # An inline block of code. This is specified as a scanned, but is sent to
483 # the parser as one long block. The inline_block pointer is used to handle
484 # the preservation of the data.
486 # Inline expression keywords.
487 "fpc" => { token( KW_PChar ); };
488 "fc" => { token( KW_Char ); };
489 "fcurs" => { token( KW_CurState ); };
490 "ftargs" => { token( KW_TargState ); };
492 whitespaceOn = false;
496 # Inline statement keywords.
498 whitespaceOn = false;
501 "fexec" => { token( KW_Exec, 0, 0 ); };
503 whitespaceOn = false;
507 whitespaceOn = false;
511 whitespaceOn = false;
515 whitespaceOn = false;
519 whitespaceOn = false;
523 ident => { token( TK_Word, tokstart, tokend ); };
525 number => { token( TK_UInt, tokstart, tokend ); };
526 hex_number => { token( TK_Hex, tokstart, tokend ); };
528 ( s_literal | d_literal )
529 => { token( IL_Literal, tokstart, tokend ); };
533 token( IL_WhiteSpace, tokstart, tokend );
535 c_cpp_comment => { token( IL_Comment, tokstart, tokend ); };
537 "::" => { token( TK_NameSep, tokstart, tokend ); };
539 # Some symbols need to go to the parser as with their cardinal value as
540 # the token type (as opposed to being sent as anonymous symbols)
541 # because they are part of the sequences which we interpret. The * ) ;
542 # symbols cause whitespace parsing to come back on. This gets turned
543 # off by some keywords.
547 token( *tokstart, tokstart, tokend );
548 if ( inlineBlockType == SemiTerminated )
554 token( *tokstart, tokstart, tokend );
557 [,(] => { token( *tokstart, tokstart, tokend ); };
560 token( IL_Symbol, tokstart, tokend );
565 if ( --curly_count == 0 && inlineBlockType == CurlyDelimited ) {
566 /* Inline code block ends. */
571 /* Either a semi terminated inline block or only the closing
572 * brace of some inner scope, not the block's closing brace. */
573 token( IL_Symbol, tokstart, tokend );
578 error() << "unterminated code block" << endl;
581 # Send every other character as a symbol.
582 any => { token( IL_Symbol, tokstart, tokend ); };
586 # Escape sequences in OR 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 # Range dash in an OR expression.
599 '-' => { token( RE_Dash, 0, 0 ); };
601 # Terminate an OR expression.
602 ']' => { token( RE_SqClose ); fret; };
605 error() << "unterminated OR literal" << endl;
608 # Characters in an OR expression.
609 [^\]] => { token( RE_Char, tokstart, tokend ); };
614 # Escape sequences in regular expressions.
615 '\\0' => { token( RE_Char, '\0' ); };
616 '\\a' => { token( RE_Char, '\a' ); };
617 '\\b' => { token( RE_Char, '\b' ); };
618 '\\t' => { token( RE_Char, '\t' ); };
619 '\\n' => { token( RE_Char, '\n' ); };
620 '\\v' => { token( RE_Char, '\v' ); };
621 '\\f' => { token( RE_Char, '\f' ); };
622 '\\r' => { token( RE_Char, '\r' ); };
623 '\\\n' => { updateCol(); };
624 '\\' any => { token( RE_Char, tokstart+1, tokend ); };
626 # Terminate an OR expression.
628 token( RE_Slash, tokstart, tokend );
632 # Special characters.
633 '.' => { token( RE_Dot ); };
634 '*' => { token( RE_Star ); };
636 '[' => { token( RE_SqOpen ); fcall or_literal; };
637 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
640 error() << "unterminated regular expression" << endl;
643 # Characters in an OR expression.
644 [^\/] => { token( RE_Char, tokstart, tokend ); };
647 write_statement := |*
648 ident => { token( TK_Word, tokstart, tokend ); } ;
649 [ \t\n]+ => { updateCol(); };
650 ';' => { token( ';' ); fgoto parser_def; };
653 error() << "unterminated write statement" << endl;
657 # Parser definitions.
659 'machine' => { token( KW_Machine ); };
660 'include' => { token( KW_Include ); };
663 fgoto write_statement;
665 'action' => { token( KW_Action ); };
666 'alphtype' => { token( KW_AlphType ); };
668 # FIXME: Enable this post 5.17.
669 # 'range' => { token( KW_Range ); };
673 inlineBlockType = SemiTerminated;
678 inlineBlockType = SemiTerminated;
682 token( KW_Variable );
683 inlineBlockType = SemiTerminated;
686 'when' => { token( KW_When ); };
687 'eof' => { token( KW_Eof ); };
688 'err' => { token( KW_Err ); };
689 'lerr' => { token( KW_Lerr ); };
690 'to' => { token( KW_To ); };
691 'from' => { token( KW_From ); };
694 ident => { token( TK_Word, tokstart, tokend ); } ;
697 number => { token( TK_UInt, tokstart, tokend ); };
698 hex_number => { token( TK_Hex, tokstart, tokend ); };
700 # Literals, with optionals.
701 ( s_literal | d_literal ) [i]?
702 => { token( TK_Literal, tokstart, tokend ); };
704 '[' => { token( RE_SqOpen ); fcall or_literal; };
705 '[^' => { token( RE_SqOpenNeg ); fcall or_literal; };
707 '/' => { token( RE_Slash ); fgoto re_literal; };
710 pound_comment => { updateCol(); };
712 ':=' => { token( TK_ColonEquals ); };
715 ">~" => { token( TK_StartToState ); };
716 "$~" => { token( TK_AllToState ); };
717 "%~" => { token( TK_FinalToState ); };
718 "<~" => { token( TK_NotStartToState ); };
719 "@~" => { token( TK_NotFinalToState ); };
720 "<>~" => { token( TK_MiddleToState ); };
723 ">*" => { token( TK_StartFromState ); };
724 "$*" => { token( TK_AllFromState ); };
725 "%*" => { token( TK_FinalFromState ); };
726 "<*" => { token( TK_NotStartFromState ); };
727 "@*" => { token( TK_NotFinalFromState ); };
728 "<>*" => { token( TK_MiddleFromState ); };
731 ">/" => { token( TK_StartEOF ); };
732 "$/" => { token( TK_AllEOF ); };
733 "%/" => { token( TK_FinalEOF ); };
734 "</" => { token( TK_NotStartEOF ); };
735 "@/" => { token( TK_NotFinalEOF ); };
736 "<>/" => { token( TK_MiddleEOF ); };
738 # Global Error actions.
739 ">!" => { token( TK_StartGblError ); };
740 "$!" => { token( TK_AllGblError ); };
741 "%!" => { token( TK_FinalGblError ); };
742 "<!" => { token( TK_NotStartGblError ); };
743 "@!" => { token( TK_NotFinalGblError ); };
744 "<>!" => { token( TK_MiddleGblError ); };
746 # Local error actions.
747 ">^" => { token( TK_StartLocalError ); };
748 "$^" => { token( TK_AllLocalError ); };
749 "%^" => { token( TK_FinalLocalError ); };
750 "<^" => { token( TK_NotStartLocalError ); };
751 "@^" => { token( TK_NotFinalLocalError ); };
752 "<>^" => { token( TK_MiddleLocalError ); };
755 "<>" => { token( TK_Middle ); };
758 '>?' => { token( TK_StartCond ); };
759 '$?' => { token( TK_AllCond ); };
760 '%?' => { token( TK_LeavingCond ); };
762 '..' => { token( TK_DotDot ); };
763 '**' => { token( TK_StarStar ); };
764 '--' => { token( TK_DashDash ); };
765 '->' => { token( TK_Arrow ); };
766 '=>' => { token( TK_DoubleArrow ); };
768 ":>" => { token( TK_ColonGt ); };
769 ":>>" => { token( TK_ColonGtGt ); };
770 "<:" => { token( TK_LtColon ); };
772 # Opening of longest match.
773 "|*" => { token( TK_BarStar ); };
776 /* In order to generate anything we must be in the top level file
777 * and the current spec must be active and there must not have been
778 * any parse errors. */
784 [ \t]+ => { updateCol(); };
786 # If we are in a single line machine then newline may end the spec.
789 if ( singleLineSpec ) {
790 /* In order to generate anything we must be in the top level file
791 * and the current spec must be active and there must not have been
792 * any parse errors. */
801 inlineBlockType = CurlyDelimited;
806 error() << "unterminated ragel section" << endl;
809 any => { token( *tokstart ); } ;
815 /* If no errors and we are at the bottom of the include stack (the
816 * source file listed on the command line) then write out the data. */
817 if ( include_depth == 0 && machineSpec == 0 && machineName == 0 )
818 xmlEscapeHost( *outStream, tokstart, tokend-tokstart );
821 # Outside code scanner. These tokens get passed through.
825 c_cpp_comment => pass;
826 s_literal | d_literal => pass;
829 singleLineSpec = false;
835 singleLineSpec = true;
848 void Scanner::do_scan()
851 char *buf = new char[bufsize];
852 const char last_char = 0;
853 int cs, act, have = 0;
857 bool singleLineSpec = false;
858 InlineBlockType inlineBlockType;
863 char *p = buf + have;
864 int space = bufsize - have;
867 /* We filled up the buffer trying to scan a token. Grow it. */
868 bufsize = bufsize * 2;
869 char *newbuf = new char[bufsize];
870 //cerr << "FULL BUFFER, NEW SIZE: " << bufsize << endl;
872 /* Recompute p and space. */
874 space = bufsize - have;
876 /* Patch up pointers possibly in use. */
878 tokstart = newbuf + ( tokstart - buf );
879 tokend = newbuf + ( tokend - buf );
881 /* Copy the new buffer in. */
882 memcpy( newbuf, buf, have );
887 input.read( p, space );
888 int len = input.gcount();
890 /* If we see eof then append the EOF char. */
892 p[0] = last_char, len = 1;
899 /* Check if we failed. */
900 if ( cs == rlscan_error ) {
901 /* Machine failed before finding a token. */
902 //cerr << "PARSE ERROR" << endl;
906 /* Decide if we need to preserve anything. */
907 char *preserve = tokstart;
909 /* Now set up the prefix. */
913 /* There is data that needs to be shifted over. */
914 have = pe - preserve;
915 memmove( buf, preserve, have );
916 unsigned int shiftback = preserve - buf;
918 tokstart -= shiftback;
928 void scan( char *fileName, istream &input )
930 Scanner scanner( fileName, input, 0, 0, 0 );
935 eofLoc.fileName = fileName;
937 eofLoc.line = scanner.line;