2 % Copyright 2001-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
21 % TODO: Need a section on the different strategies for handline recursion.
23 \documentclass[letterpaper,11pt,oneside]{book}
33 \setlength{\parskip}{0pt}
34 \setlength{\topsep}{0pt}
35 \setlength{\partopsep}{0pt}
36 \setlength{\itemsep}{0pt}
40 \newcommand{\verbspace}{\vspace{10pt}}
41 \newcommand{\graphspace}{\vspace{10pt}}
43 \renewcommand\floatpagefraction{.99}
44 \renewcommand\topfraction{.99}
45 \renewcommand\bottomfraction{.99}
46 \renewcommand\textfraction{.01}
47 \setcounter{totalnumber}{50}
48 \setcounter{topnumber}{50}
49 \setcounter{bottomnumber}{50}
51 \newenvironment{inline_code}{\def\baselinestretch{1}\vspace{12pt}\small}{}
61 {\huge Ragel State Machine Compiler}\\
67 {\large Adrian Thurston}\\
77 Ragel version \version, \pubdate\\
78 Copyright \copyright\ 2003, 2004, 2005, 2006 Adrian Thurston
81 {\bf\it\noindent This document is part of Ragel, and as such, this document is
82 released under the terms of the GNU General Public License as published by the
83 Free Software Foundation; either version 2 of the License, or (at your option)
88 {\bf\it\noindent Ragel is distributed in the hope that it will be useful, but
89 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
90 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
95 {\bf\it\noindent You should have received a copy of the GNU General Public
96 License along with Ragel; if not, write to the Free Software Foundation, Inc.,
97 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA}
110 \pagenumbering{arabic}
112 \chapter{Introduction}
116 Regular expressions are used heavily in practice for the purpose of specifying
117 parsers. However, they are normally used as black boxes linked together with
118 program logic. User actions are executed in between invocations of the regular
119 expression engine. Adding actions before a pattern terminates requires patterns
120 to be broken and pasted back together with program logic. The more user actions
121 are needed, the less the advantages of regular expressions are seen.
123 Ragel is a software development tool which allows user actions to be
124 embedded into the transitions of a regular expression's corresponding state
125 machine, eliminating the need to switch from the regular expression engine and
126 user code execution environment and back again. As a result, expressions can be
127 maximally continuous. One is free to specify an entire parser using a single
128 regular experssion. The single-expression model affords concise and elegant
129 descriptions of languages and the generation of very simple, fast and robust
130 code. Ragel compiles finite state machines from a high level regular language
131 notation to executable C, C++, Objective-C or D.
133 In addition to building state machines from regular expressions, Ragel allows
134 the programmer to directly specify state machines with state charts. These two
135 notations may be freely combined. There are also facilities for controlling
136 nondeterminism in the resulting machines and building scanners using patterns
137 that themselves have embedded actions. Ragel can produce code that runs
138 nearly as fast as manually constructed machines. Ragel can handle
139 integer-sized alphabets and can compile very large state machines.
143 When a programmer is faced with the task of producing a parser for a
144 context-free language there are many tools to choose from. It is quite common
145 to generate useful and efficient parsers for programming languages from a
146 formal grammar. It is also quite common for programmers to avoid such tools
147 when making parsers for simple computer languages, such as file formats and
148 communication protocols. Such languages often meet the criteria for the
149 regular languages. Tools for processing the context-free languages are viewed
150 as too heavyweight for the purpose of parsing regular languages because the extra
151 run-time effort required for supporting the recursive nature of context-free
154 When we turn to the regular expression-based parsing tools, such as Lex, Re2C,
155 and scripting languages such as Sed, Awk and Perl we find that they are split
156 into two levels: a regular expression matching engine and some kind of program
157 logic for linking patterns together. For example, a Lex program is composed of
158 sets of regular expressions. The implied program logic repeatedly attempts to
159 match a pattern in the current set, then executes the associated user code. It requires the
160 user to consider a language as a sequence of independent tokens. Scripting
161 languages and regular expression libraries allow one to link patterns together
162 using arbitrary program code. This is very flexible and powerful, however we
163 can be more concise and clear if we avoid gluing together regular expressions
164 with if statements and while loops.
166 This model of execution, where the runtime alternates between regular
167 expression matching and user code exectution places severe restrictions on when
168 action code may be executed. Since action code can only be associated with
169 complete patterns, any action code which must be executed before an entire
170 pattern is matched requires that the pattern be broken into smaller units.
171 Instead of being forced to disrupt the regular expression syntax and write
172 smaller expressions, it is desirable to retain a single expression and embed
173 code for performing actions directly into the transitions which move over the
174 characters. After all, capable programmers are astutely aware of the machinery
175 underlying their programs, so why not provide them with access to that
176 machinery? To achieve this we require an action execution model for associating
177 code with the sub-expressions of a regular expression in a way that does not
180 The primary goal of Ragel is to provide developers with an ability to embed
181 actions into the transitions and states of a regular expression in support of the
182 definition of entire parsers or large sections of parsers using a single
183 regular expression that is compiled to a finite state machine. From the
184 regular expression we gain a clear and concise statement of our language. From
185 the state machine we obtain a very fast and robust executable that lends itself
186 to many kinds of analysis and visualization.
190 Ragel is a language for specifying state machines. The Ragel program is a
191 compiler that assembles a state machine definition to executable code. Ragel
192 is based on the principle that any regular language can be converted to a
193 deterministic finite state automaton. Since every regular language has a state
194 machine representation and vice versa, the terms regular language and state
195 machine (or just machine) will be used interchangeably in this document.
197 Ragel outputs machines to C, C++, Objective-C, or D code. The output is
198 designed to be generic and is not bound to any particular input or processing
199 method. A Ragel machine expects to have data passed to it in buffer blocks.
200 When there is no more input, the machine can be queried for acceptance. In
201 this way, a Ragel machine can be used to simply recognize a regular language
202 like a regular expression library. By embedding code into the regular language,
203 a Ragel machine can also be used to parse input.
205 The Ragel input language has many operators for constructing and manipulating
206 machines. Machines are built up from smaller machines, to bigger ones, to the
207 final machine representing the language that needs to be recognized or parsed.
209 The core state machine construction operators are those found in most ``Theory
210 of Computation'' textbooks. They date back to the 1950s and are widely studied.
211 They are based on set operations and permit one to think of languages as a set
212 of strings. They are Union, Intersection, Subtraction, Concatenation and Kleene
213 Star. Put together, these operators make up what most people know as regular
214 expressions. Ragel also provides a scanner construction construction operator
215 and provides operators for explicitly constructing machines
216 using a state chart method. In the state chart method, one joins machines
217 together without any implied transitions and then explicitly specifies where
218 epsilon transitions should be drawn.
220 The state machine manipulation operators are specific to Ragel. They allow the
221 programmer to access the states and transitions of regular language's
222 corresponding machine. There are two uses of the manipulation operators. The
223 first and primary use is to embed code into transitions and states, allowing
224 the programmer to specify the actions of the state machine.
226 Ragel attempts to make the action embedding facility as intuitive as possible.
227 To do that, a number issues need to be addresses. For example, when making a
228 nondeterministic specification into a DFA using machines that have embedded
229 actions, new transitions are often made that have the combined actions of
230 several source transitions. Ragel ensures that multiple actions associated with
231 a single transition are ordered consistently with respect to the order of
232 reference and the natural ordering implied by the construction operators.
234 The second use of the manipulation operators is to assign priorities in
235 transitions. Priorities provide a convenient way of controlling any
236 nondeterminism introduced by the construction operators. Suppose two
237 transitions leave from the same state and go to distinct target states on the
238 same character. If these transitions are assigned conflicting priorities, then
239 during the determinization process the transition with the higher priority will
240 take precedence over the transition with the lower priority. The lower priority
241 transition gets abandoned. The transitions would otherwise be combined to a new
242 transition that goes to a new state which is a combination of the original
243 target states. Priorities are often required for segmenting machines. The most
244 common uses of priorities have been encoded into a set of simple operators
245 which should be used instead of priority embeddings whenever possible.
247 For the purposes of embedding, Ragel divides transitions and states into
248 different classes. There are four operators for embedding actions and
249 priorities into the transitions of a state machine. It is possible to embed
250 into start transitions, finishing transitions, all transitions and pending out
251 transitions. The embedding of pending out transitions is a special case.
252 These transition embeddings get stored in the final states of a machine. They
253 are transferred to any transitions that may be made going out of the machine by
254 a concatenation or kleene star operator.
256 There are several more operators for embedding actions into states. Like the
257 transition embeddings, there are various different classes of states that the
258 embedding operators access. For example, one can access start states, final
259 states or all states, among others. Unlike the transition embeddings, there are
260 several different types of state action embeddings. These are executed at
261 various different times during the processing of input. It is possible to embed
262 actions which are exectued on all transitions which enter into a state, all
263 transitions out of a state, transitions taken on the error event, or
264 transitions taken on the EOF event.
266 Within actions, it is possible to influence the behaviour of the state machine.
267 The user can write action code that jumps or calls to another portion of the
268 machine, changes the current character being processed, or breaks out of the
269 processing loop. With the state machine calling feature Ragel can be used to
270 parse languages which are not regular. For example, one can parse balanced
271 parentheses by calling into a parser when an open bracket character is seen and
272 returning to the state on the top of the stack when the corresponding closing
273 bracket character is seen. More complicated context-free languages such as
274 expressions in C, are out of the scope of Ragel.
276 Ragel also provides a scanner construction operator which can be used to build scanners
277 much the same way that Lex is used. The Ragel generated code, which relies on
278 user-defined variables for
279 backtracking, repeatedly tries to match patterns to the input, favouring longer
280 patterns over shorter ones and patterns that appear ahead of others when the
281 lengths of the possible matches are identical. When a pattern is matched the
282 associated action is executed.
284 The key distinguishing feature between scanners in Ragel and scanners in Lex is
285 that Ragel patterns may be arbitrary Ragel expressions and can therefore
286 contain embedded code. With a Ragel-based scanner the user need not wait until
287 the end of a pattern before user code can be executed.
289 Scanners do take Ragel out of the domain of pure state machines and require the
290 user to maintain the backtracking related variables. However, scanners
291 integrate well with regular state machine instantiations. They can be called to
292 or jumped to only when needed, or they can be called out of or jumped out of
293 when a simpler, pure state machine model is appropriate.
295 Two types of output code style are available. Ragel can produce a table-driven
296 machine or a directly executable machine. The directly executable machine is
297 much faster than the table-driven. On the other hand, the table-driven machine
298 is more compact and less demanding on the host language compiler. It is better
299 suited to compiling large state machines.
301 \section{Related Work}
303 Lex is perhaps the best-known tool for constructing parsers from regular
304 expressions. In the Lex processing model, generated code attempts to match one
305 of the user's regular expression patterns, favouring longer matches over
306 shorter ones. Once a match is made it then executes the code associated with
307 the pattern and consumes the matching string. This process is repeated until
308 the input is fully consumed.
310 Through the use of start conditions, related sets of patterns may be defined.
311 The active set may be changed at any time. This allows the user to define
312 different lexical regions. It also allows the user to link patterns together by
313 requiring that some patterns come before others. This is quite like a
314 concatenation operation. However, use of Lex for languages that require a
315 considerable amount of pattern concatenation is inappropriate. In such cases a
316 Lex program deteriorates into a manually specified state machine, where start
317 conditions define the states and pattern actions define the transitions. Lex
318 is therefore best suited to parsing tasks where the language to be parsed can
319 be described in terms of regions of tokens.
321 Lex is useful in many scenarios and has undoubtedly stood the test of time.
322 There are, however, several drawbacks to using Lex. Lex can impose too much
323 overhead for parsing applications where buffering is not required because all
324 the characters are available in a single string. In these cases there is
325 structure to the language to be parsed and a parser specification tool can
326 help, but employing a heavyweight processing loop that imposes a stream
327 ``pull'' model and dynamic input buffer allocation is inappropriate. An
328 example of this kind of scenario is the conversion of floating point numbers
329 contained in a string to their corresponding numerical values.
331 Another drawback is the very issue that Ragel attempts to solve.
332 It is not possbile to execute a user action while
333 matching a character contained inside a pattern. For example, if scanning a
334 programming language and string literals can contain newlines which must be
335 counted, a Lex user must break up a string literal pattern so as to associate
336 an action with newlines. This forces the definition of a new start condition.
337 Alternatively the user can reprocess the text of the matched string literal to
341 How ragel is different from Lex.
343 %Like Re2c, Ragel provides a simple execution model that does not make any
344 %assumptions as to how the input is collected. Also, Ragel does not do any
345 %buffering in the generated code. Consequently there are no dependencies on
346 %external functions such as \verb|malloc|.
348 %If buffering is required it can be manually implemented by embedding actions
349 %that copy the current character to a buffer, or data can be passed to the
350 %parser using known block boundaries. If the longest-match operator is used,
351 %Ragel requires the user to ensure that the ending portion of the input buffer
352 %is preserved when the buffer is exhaused before a token is fully matched. The
353 %user should move the token prefix to a new memory location, such as back to the
354 %beginning of the input buffer, then place the subsequently read input
355 %immediately after the prefix.
357 %These properties of Ragel make it more work to write a program that requires
358 %the longest-match operator or buffering of input, however they make Ragel a
359 %more flexible tool that can produce very simple and fast-running programs under
360 %a variety of input acquisition arrangements.
362 %In Ragel, it is not necessary
363 %to introduce start conditions to concatenate tokens and retain action
364 %execution. Ragel allows one to structure a parser as a series of tokens, but
365 %does not require it.
367 %Like Lex and Re2C, Ragel is able to process input using a longest-match
368 %execution model, however the core of the Ragel language specifies parsers at a
369 %much lower level. This core is built around a pure state machine model. When
370 %building basic machines there is no implied algorithm for processing input
371 %other than to move from state to state on the transitions of the machine. This
372 %core of pure state machine operations makes Ragel well suited to handling
373 %parsing problems not based on token scanning. Should one need to use a
374 %longest-match model, the functionality is available and the lower level state
375 %machine construction facilities can be used to specify the patterns of a
376 %longest-match machine.
378 %This is not possible in Ragel. One can only program
379 %a longest-match instantiation with a fixed set of rules. One can jump to
380 %another longest-match machine that employs the same machine definitions in the
381 %construction of its rules, however no states will be shared.
383 %In Ragel, input may be re-parsed using a
384 %different machine, but since the action to be executed is associated with
385 %transitions of the compiled state machine, the longest-match construction does
386 %not permit a single rule to be excluded from the active set. It cannot be done
387 %ahead of time nor in the excluded rule's action.
390 The Re2C program defines an input processing model similar to that of Lex.
391 Re2C focuses on making generated state machines run very fast and
392 integrate easily into any program, free of dependencies. Re2C generates
393 directly executable code and is able to claim that generated parsers run nearly
394 as fast as their hand-coded equivalents. This is very important for user
395 adoption, as programmers are reluctant to use a tool when a faster alternative
396 exists. A consideration to ease of use is also important because developers
397 need the freedom to integrate the generated code as they see fit.
399 Many scripting languages provide ways of composing parsers by linking regular
400 expressions using program logic. For example, Sed and Awk are two established
401 Unix scripting tools that allow the programmer to exploit regular expressions
402 for the purpose of locating and extracting text of interest. High-level
403 programming languages such as Perl, Python, PHP and Ruby all provide regular
404 expression libraries that allow the user to combine regular expressions with
407 In addition to supporting the linking of regular expressions with arbitrary
408 program logic, the Perl programming language permits the embedding of code into
409 regular expressions. Perl embeddings do not translate into the embedding of
410 code into deterministic state machines. Perl regular expressions are in fact
411 not fully compiled to deterministic machines when embedded code is involved.
412 They are instead interpreted and involve backtracking. This is shown by the
413 following Perl program. When it is fed the input \verb|abcd| the interpretor
414 attempts to match the first alternative, printing \verb|a1 b1|. When this
415 possibility fails it backtracks and tries the second possibility, printing
416 \verb|a2 b2|, at which point it succeeds.
420 print "YES\n" if ( <STDIN> =~
421 /( a (?{ print "a1 "; }) b (?{ print "b1 "; }) cX ) |
422 ( a (?{ print "a2 "; }) b (?{ print "b2 "; }) cd )/x )
427 In Ragel there is no regular expression interpretor. Aside from the scanner
428 operator, all Ragel expressions are made into deterministic machines and the
429 run time simply moves from state to state as it consumes input. An equivalent
430 parser expressed in Ragel would attempt both of the alternatives concurrently,
431 printing \verb|a1 a2 b1 b2|.
433 \section{Development Status}
435 Ragel is a relatively new tool and is under continuous development. As a rough
436 release guide, minor revision number changes are for implementation
437 improvements and feature additions. Major revision number changes are for
438 implementation and language changes that do not preserve backwards
439 compatibility. Though in the past this has not always held true: changes that
440 break code have crept into minor version number changes. Typically, the
441 documentation lags behind the development in the interest of documenting only
442 the lasting features. The latest changes are always documented in the ChangeLog
443 file. As Ragel stabilizes, which is expected in the 5.x line, the version
444 numbering rules will become more strict and the documentation will become more
448 \chapter{Constructing State Machines}
450 \section{Ragel State Machine Specifications}
452 A Ragel input file consists of a host language code file with embedded machine
453 specifications. Ragel normally passes input straight to output. When it sees
454 a machine specification it stops to read the Ragel statements and possibly generate
455 code in place of the specification.
456 Afterwards it continues to pass input through. There
457 can be any number of FSM specifications in an input file. A multi-line FSM spec
458 starts with \verb|%%{| and ends with \verb|}%%|. A single-line FSM spec starts
459 with \verb|%%| and ends at the first newline.
461 While Ragel is looking for FSM specifications it does basic lexical analysis on
462 the surrounding input. It interprets literal strings and comments so a
463 \verb|%%| sequence in either of those will not trigger the parsing of an FSM
464 specification. Ragel does not pass the input through any preprocessor nor does it
465 interpret preprocessor directives itself so includes, defines and ifdef logic
466 cannot be used to alter the parse of a Ragel input file. It is therefore not
467 possible to use an \verb|#if 0| directive to comment out a machine as is
468 commonly done in C code. As an alternative, a machine can be prevented from
469 causing any generated output by commenting out the write statements.
471 In Figure \ref{cmd-line-parsing}, a multi-line machine is used to define the
472 machine and single line machines are used to trigger the writing of the machine
473 data and execution code.
493 int main( int argc, char **argv )
498 char *pe = p + strlen(p) + 1;
502 printf("result = %i\n", res );
507 \caption{Parsing a command line argument.}
508 \label{cmd-line-parsing}
512 \subsection{Naming Ragel Blocks}
519 The \verb|machine| statement gives the name of the FSM. If present in a
520 specification, this statement must appear first. If a machine specification
521 does not have a name then Ragel uses the previous specification name. If no
522 previous specification name exists then this is an error. Because FSM
523 specifications persist in memory, a machine's statements can be spread across
524 multiple machine specifications. This allows one to break up a machine across
525 several files or draw in statements that are common to multiple machines using
526 the include statement.
528 \subsection{Including Ragel Code}
531 include FsmName "inputfile.rl";
535 The \verb|include| statement can be used to draw in the statements of another FSM
536 specification. Both the name and input file are optional, however at least one
537 must be given. Without an FSM name, the given input file is searched for an FSM
538 of the same name as the current specification. Without an input file the
539 current file is searched for a machine of the given name. If both are present,
540 the given input file is searched for a machine of the given name.
542 \subsection{Machine Definition}
546 <name> = <expression>;
550 The machine definition statement associates an FSM expression with a name. Machine
551 expressions assigned to names can later be referenced by other expressions. A
552 definition statement on its own does not cause any states to be generated. It is simply a
553 description of a machine to be used later. States are generated only when a definition is
554 instantiated, which happens when a definition is referenced in an instantiated
557 \subsection{Machine Instantiation}
558 \label{instantiation}
561 <name> := <expression>;
565 The machine instantiation statement generates a set of states representing an expression and
566 associates a name with the entry point. Each instantiation generates a distinct
567 set of states. At a very minimum the \verb|main| machine must be instantiated.
568 Other machines may be instantiated and control passed to them by use of
569 \verb|fcall|, \verb|fgoto| or \verb|fnext| statements.
571 \section{Lexical Analysis of an FSM Specification}
574 Within a machine specification the following lexical rules apply to the parse
579 \item The \verb|#| symbol begins a comment that terminates at the next newline.
581 \item The symbols \verb|""|, \verb|''|, \verb|//|, \verb|[]| behave as the
582 delimiters of literal strings. With them, the following escape sequences are interpreted:
584 \verb| \0 \a \b \t \n \v \f \r|
586 A backslash at the end of a line joins the following line onto the current. A
587 backslash preceding any other character removes special meaning. This applies
588 to terminating characters and to special characters in regular expression
589 literals. As an exception, regular expression literals do not support escape
590 sequences as the operands of a range within a list. See the bullet on regular
591 expressions in Section \ref{basic}.
593 \item The symbols \verb|{}| delimit a block of host language code that will be
594 embedded into the machine as an action. Within the block of host language
595 code, basic lexical analysis of C/C++ comments and strings is done in order to
596 correctly find the closing brace of the block. With the exception of FSM
597 commands embedded in code blocks, the entire block is preserved as is for
598 identical reproduction in the output code.
600 \item The pattern \verb|[+-]?[0-9]+| denotes an integer in decimal format.
601 Integers used for specifying machines may be negative only if the alphabet type
602 is signed. Integers used for specifying priorities may be positive or negative.
604 \item The pattern \verb|0x[0-9a-fA-f]+| denotes an integer in hexadecimal
607 \item The keywords are \verb|access|, \verb|action|, \verb|alphtype|,
608 \verb|getkey|, \verb|write|, \verb|machine| and \verb|include|.
610 \item The pattern \verb|[a-zA-Z_][a-zA-Z_0-9]*| denotes an identifier.
612 %\item The allowable symbols are:
614 %\verb/ ( ) ! ^ * ? + : -> - | & . , := = ; > @ $ % /\\
615 %\verb| >/ $/ %/ </ @/ <>/ >! $! %! <! @! <>!|\\
616 %\verb| >^ $^ %^ <^ @^ <>^ >~ $~ %~ <~ @~ <>~|\\
617 %\verb| >* $* %* <* @* <>*|
619 \item Any amount of whitespace may separate tokens.
623 %\section{Parse of an FSM Specification}
625 %The following statements are possible within an FSM specification. The
626 %requirements for trailing semicolons loosely follow that of C.
628 %specifying code does not require a trailing semicolon. An expression
629 %statement does require a trailing semicolon.
632 \section{Basic Machines}
635 The basic machines are the base operands of regular language expressions. They
636 are the smallest unit to which machine construction and manipulation operators
639 In the diagrams that follow the symbol \verb|df| represents
640 the default transition, which is taken if no other transition can be taken. The
641 symbol \verb|cr| represents the carriage return character, \verb|nl| represents the newline character (aka line feed) and the symbol
642 \verb|sp| represents the space character.
646 \item \verb|'hello'| -- Concatenation Literal. Produces a machine that matches
647 the sequence of characters in the quoted string. If there are 5 characters
648 there will be 6 states chained together with the characters in the string. See
649 Section \ref{lexing} for information on valid escape sequences.
664 \includegraphics[scale=0.45]{bmconcat}
668 to make a concatenation literal case-insensitive by appending an \verb|i| to
669 the string, for example \verb|'cmd'i|.
671 \item \verb|"hello"| -- Identical to the single quoted version.
673 \item \verb|[hello]| -- Or Expression. Produces a union of characters. There
674 will be two states with a transition for each unique character between the two states.
675 The \verb|[]| delimiters behave like the quotes of a literal string. For example,
676 \verb|[ \t]| means tab or space. The or expression supports character ranges
677 with the \verb|-| symbol as a separator. The meaning of the union can be negated
678 using an initial \verb|^| character as in standard regular expressions.
679 See Section \ref{lexing} for information on valid escape sequences
695 \includegraphics[scale=0.45]{bmor}
698 \item \verb|''|, \verb|""|, and \verb|[]| -- Zero Length Machine. Produces a machine
699 that matches the zero length string. Zero length machines have one state that is both
700 a start state and a final state.
715 \includegraphics[scale=0.45]{bmnull}
718 % FIXME: More on the range of values here.
719 \item \verb|42| -- Numerical Literal. Produces a two state machine with one
720 transition on the given number. The number may be in decimal or hexadecimal
721 format and should be in the range allowed by the alphabet type. The minimum and
722 maximum values permitted are defined by the host machine that Ragel is compiled
723 on. For example, numbers in a \verb|short| alphabet on an i386 machine should
724 be in the range \verb|-32768| to \verb|32767|.
738 \includegraphics[scale=0.45]{bmnum}
741 \item \verb|/simple_regex/| -- Regular Expression. Regular expressions are
742 parsed as a series of expressions that will be concatenated together. Each
743 concatenated expression
744 may be a literal character, the any character specified by the \verb|.|
745 symbol, or a union of characters specified by the \verb|[]| delimiters. If the
746 first character of a union is \verb|^| then it matches any character not in the
747 list. Within a union, a range of characters can be given by separating the first
748 and last characters of the range with the \verb|-| symbol. Each
749 concatenated machine may have repetition specified by following it with the
750 \verb|*| symbol. The standard escape sequences described in Section
751 \ref{lexing} are supported everywhere in regular expressions except as the
752 operands of a range within in a list. This notation also supports the \verb|i|
753 trailing option. Use it to produce case-insensitive machines, as in \verb|/GET/i|.
755 Ragel does not support very complex regular expressions because the desired
756 results can always be achieved using the more general machine construction
757 operators listed in Section \ref{machconst}. The following diagram shows the
758 result of compiling \verb|/ab*[c-z].*[123]/|.
766 main := /ab*[c-z].*[123]/;
773 \includegraphics[scale=0.45]{bmregex}
776 \item \verb|'a' .. 'z'| -- Range. Produces a machine that matches any
777 characters in the specified range. Allowable upper and lower bounds of the
778 range are concatenation literals of length one and numerical literals. For
779 example, \verb|0x10..0x20|, \verb|0..63|, and \verb|'a'..'z'| are valid ranges.
780 The bounds should be in the range allowed by the alphabet type.
795 \includegraphics[scale=0.45]{bmrange}
799 \item \verb|variable_name| -- Lookup the machine definition assigned to the
800 variable name given and use an instance of it. See Section \ref{definition} for
801 an important note on what it means to reference a variable name.
803 \item \verb|builtin_machine| -- There are several built-in machines available
804 for use. They are all two state machines for the purpose of matching common
805 classes of characters. They are:
809 \item \verb|any | -- Any character in the alphabet.
811 \item \verb|ascii | -- Ascii characters. \verb|0..127|
813 \item \verb|extend| -- Ascii extended characters. This is the range
814 \verb|-128..127| for signed alphabets and the range \verb|0..255| for unsigned
817 \item \verb|alpha | -- Alphabetic characters. \verb|[A-Za-z]|
819 \item \verb|digit | -- Digits. \verb|[0-9]|
821 \item \verb|alnum | -- Alpha numerics. \verb|[0-9A-Za-z]|
823 \item \verb|lower | -- Lowercase characters. \verb|[a-z]|
825 \item \verb|upper | -- Uppercase characters. \verb|[A-Z]|
827 \item \verb|xdigit| -- Hexadecimal digits. \verb|[0-9A-Fa-f]|
829 \item \verb|cntrl | -- Control characters. \verb|0..31|
831 \item \verb|graph | -- Graphical characters. \verb|[!-~]|
833 \item \verb|print | -- Printable characters. \verb|[ -~]|
835 \item \verb|punct | -- Punctuation. Graphical characters that are not alphanumerics.
836 \verb|[!-/:-@[-`{-~]|
838 \item \verb|space | -- Whitespace. \verb|[\t\v\f\n\r ]|
840 \item \verb|zlen | -- Zero length string. \verb|""|
842 \item \verb|empty | -- Empty set. Matches nothing. \verb|^any|
847 \section{Operator Precedence}
848 The following table shows operator precedence from lowest to highest. Operators
849 in the same precedence group are evaluated from left to right.
852 \begin{tabular}{|c|c|c|}
856 2&\verb/ | & - --/&Union, Intersection and Subtraction\\
858 3&\verb| . <: :> :>> |&Concatenation\\
862 5&\verb| -> |&Epsilon Transition\\
864 &\verb| > @ $ % |&Transitions Actions and Priorities\\
866 &\verb| >/ $/ %/ </ @/ <>/ |&EOF Actions\\
868 6&\verb| >! $! %! <! @! <>! |&Global Error Actions\\
870 &\verb| >^ $^ %^ <^ @^ <>^ |&Local Error Actions\\
872 &\verb| >~ $~ %~ <~ @~ <>~ |&To-State Actions\\
874 &\verb| >* $* %* <* @* <>* |&From-State Action\\
876 7&\verb| * ** ? + {n} {,n} {n,} {n,m} |&Repetition\\
878 8&\verb| ! ^ |&Negation and Character-Level Negation\\
880 9&\verb| ( <expr> ) |&Grouping\\
884 \section{Regular Language Operators}
887 When using Ragel it is helpful to have a sense of how it constructs machines.
888 Sometimes this the determinization process can cause results that appear unusual to someone
889 unfamiliar with it. Ragel does not make use of any nondeterministic
890 intermediate state machines. All operators accept and return deterministic
891 machines. However, to ease the discussion, the operations are defined in terms
894 To draw an epsilon transition between two states \verb|x| and \verb|y|, is to
895 copy all of the properties of \verb|y| into \verb|x|. This involves drawing in
896 all of \verb|y|'s to-state actions, EOF actions, etc., as well as its
897 transitions. If \verb|x| and \verb|y| both have a transition out on the same
898 character, then the transitions must be combined. During transition
899 combination a new transition is made which goes to a new state that is the
900 combination of both target states. The new combination state is created using
901 the same epsilon transition method. The new state has an epsilon transition
902 drawn to all the states that compose it. Since every time an epsilon transition
903 is drawn the creation of new epsilon transitions may be triggered, the process
904 of drawing epsilon transitions is repeated until there are no more epsilon
905 transitions to be made.
907 A very common error that is made when using Ragel is to make machines that do
908 too much at once. That is, to create machines that have unintentional
909 nondeterminism. This usually results from being unaware of the common strings
910 between machines that are combined together using the regular language
911 operators. This can involve never leaving a machine, causing its actions to be
912 propagated through all the following states. Or it can involve an alternation
913 where both branches are unintentionally taken simultaneously.
915 This problem forces one to think hard about the language that needs to be
916 matched. To guard against this kind of problem one must ensure that the machine
917 specification is divided up using boundaries that do not allow ambiguities from
918 one portion of the machine to the next. See Chapter
919 \ref{controlling-nondeterminism} for more on this problem and how to solve it.
921 The Graphviz tool is an immense help when debugging improperly compiled
922 machines or otherwise learning how to use Ragel. In many cases, practical
923 parsing programs will be too large to completely visualize with Graphviz. The
924 proper approach is to reduce the language to the smallest subset possible that
925 still exhibits the characteristics that one wishes to learn about or to fix.
926 This can be done without modifying the source code using the \verb|-M| and
927 \verb|-S| options at the frontend. If a machine cannot be easily reduced,
928 embeddings of unique actions can be very useful for tracing a
929 particular component of a larger machine specification, since action names are
930 written out on transition labels.
937 The union operation produces a machine that matches any string in machine one
938 or machine two. The operation first creates a new start state. Epsilon
939 transitions are drawn from the new start state to the start states of both
940 input machines. The resulting machine has a final state set equivalent to the
941 union of the final state sets of both input machines. In this operation, there
942 is the opportunity for nondeterminism among both branches. If there are
943 strings, or prefixes of strings that are matched by both machines then the new
944 machine will follow both parts of the alternation at once. The union operation is
949 \includegraphics{opor}
953 The following example demonstrates the union of three machines representing
962 # Hex digits, decimal digits, or identifiers
963 main := '0x' xdigit+ | digit+ | alpha alnum*;
971 \includegraphics[scale=0.45]{exor}
974 \subsection{Intersection}
979 Intersection produces a machine that matches any
980 string which is in both machine one and machine two. To achieve intersection, a
981 union is performed on the two machines. After the result has been made
982 deterministic, any final state that is not a combination of final states from
983 both machines has its final state status revoked. To complete the operation,
984 paths that do not lead to a final state are pruned from the machine. Therefore,
985 if there are any such paths in either of the expressions they will be removed
986 by the intersection operator. Intersection can be used to require that two
987 independent patterns be simultaneously satisfied as in the following example.
995 # Match lines four characters wide that contain
996 # words separated by whitespace.
998 /[^\n][^\n][^\n][^\n]\n/* &
999 (/[a-z][a-z]*/ | [ \n])**;
1007 \includegraphics[scale=0.45]{exinter}
1010 \subsection{Difference}
1015 The difference operation produces a machine that matches
1016 strings which are in machine one but which are not in machine two. To achieve subtraction,
1017 a union is performed on the two machines. After the result has been made
1018 deterministic, any final state that came from machine two or is a combination
1019 of states involving a final state from machine two has its final state status
1020 revoked. As with intersection, the operation is completed by pruning any path
1021 that does not lead to a final state. The following example demonstrates the
1022 use of subtraction to exclude specific cases from a set.
1032 # Subtract keywords from identifiers.
1033 main := /[a-z][a-z]*/ - ( 'for' | 'int' );
1041 \includegraphics[scale=0.45]{exsubtr}
1046 \subsection{Strong Difference}
1047 \label{strong_difference}
1052 Strong difference produces a machine that matches any string of the first
1053 machine which does not have any string of the second machine as a substring. In
1054 the following example, strong subtraction is used to excluded \verb|CRLF| from
1055 a sequence. In the corresponding visualization, the label \verb|DEF| is short
1056 for default. The default transition is taken if no other transition can be
1059 % GENERATE: exstrongsubtr
1062 % machine exstrongsubtr;
1066 main := [a-z]+ ':' ( any* -- crlf ) crlf;
1074 \includegraphics[scale=0.45]{exstrongsubtr}
1078 This operator is equivalent to the following.
1082 expr - ( any* expr any* )
1085 \subsection{Concatenation}
1090 Concatenation produces a machine that matches all the strings in machine one followed by all
1091 the strings in machine two. Concatenation draws epsilon transitions from the
1092 final states of the first machine to the start state of the second machine. The
1093 final states of the first machine loose their final state status, unless the
1094 start state of the second machine is final as well.
1095 Concatenation is the default operator. Two machines next to each other with no
1096 operator between them results in the machines being concatenated together.
1100 \includegraphics{opconcat}
1104 The opportunity for nondeterministic behaviour results from the possibility of
1105 the final states of the first machine accepting a string which is also accepted
1106 by the start state of the second machine.
1107 The most common scenario that this happens in is the
1108 concatenation of a machine that repeats some pattern with a machine that gives
1109 a termination string, but the repetition machine does not exclude the
1110 termination string. The example in Section \ref{strong_difference}
1111 guards against this. Another example is the expression \verb|("'" any* "'")|.
1112 When exectued the thread of control will
1113 never leave the \verb|any*| machine. This is a problem especially if actions
1114 are embedded to processes the characters of the \verb|any*| component.
1116 In the following example, the first machine is always active due to the
1117 nondeterministic nature of concatenation. This particular nondeterminism is intended
1118 however because we wish to permit EOF strings before the end of the input.
1120 % GENERATE: exconcat
1126 # Require an eof marker on the last line.
1127 main := /[^\n]*\n/* . 'EOF\n';
1135 \includegraphics[scale=0.45]{exconcat}
1139 \noindent {\bf Note:} There is a language
1140 ambiguity involving concatenation and subtraction. Because concatenation is the
1141 default operator for two
1142 adjacent machines there is an ambiguity between subtraction of
1143 a positive numerical literal and concatenation of a negative numerical literal.
1144 For example, \verb|(x-7)| could be interpreted as \verb|(x . -7)| or
1145 \verb|(x - 7)|. In the Ragel language, the subtraction operator always takes precedence
1146 over concatenation of a negative literal. Precedence was given to the
1147 subtraction-based interpretation so as to adhere to the rule that the default
1148 concatenation operator takes effect only when there are no other operators between
1149 two machines. Beware of writing machines such as \verb|(any -1)| when what is
1150 desired is a concatenation of \verb|any| and -1. Instead write
1151 \verb|(any . -1)| or \verb|(any (-1))|. If in doubt of the meaning of your program do not
1152 rely on the default concatenation operator, always use the \verb|.| symbol.
1155 \subsection{Kleene Star}
1160 The machine resulting from the Kleene Star operator will match zero or more
1161 repetitions of the machine it is applied to.
1162 It creates a new start state and an additional final
1163 state. Epsilon transitions are drawn between the new start state and the old start
1164 state, between the new start state and the new final state, and
1165 between the final states of the machine and the new start state. After the
1166 machine is made deterministic the effect is of the final states getting all the
1167 transitions of the start state.
1171 \includegraphics{opstar}
1175 The possibility for nondeterministic behaviour arises if the final states have
1176 transitions on any of the same characters as the start state. This is common
1177 when applying kleene star to an alternation of tokens. Like the other problems
1178 arising from nondeterministic behavior, this is discussed in more detail in Chapter
1179 \ref{controlling-nondeterminism}. This particular problem can also be solved
1180 by using the longest-match construction discussed in Section
1181 \ref{generating-scanners} on scanners.
1184 example, there is no nondeterminism introduced by the exterior kleene star due
1185 the newline at the end of the regular expression. Without the newline the
1186 exterior kleene star would be redundant and there would be ambiguity between
1187 repeating the inner range of the regular expression and the entire regular
1188 expression. Though it would not cause a problem in this case, unnecessary
1189 nondeterminism in the kleene star operator often causes undesired results for
1190 new Ragel users and must be guarded against.
1198 # Match any number of lines with only lowercase letters.
1199 main := /[a-z]*\n/*;
1207 \includegraphics[scale=0.45]{exstar}
1211 \subsection{One Or More Repetition}
1216 This operator produces the concatenation of the machine with the kleene star of
1217 itself. The result will match one or more repetitions of the machine. The plus
1218 operator is equivalent to \verb|(expr . expr*)|. The plus operator makes
1219 repetitions that cannot be zero length.
1227 # Match alpha-numeric words.
1236 \includegraphics[scale=0.45]{explus}
1240 \subsection{Optional}
1245 The {\em optional} operator produces a machine that accepts the machine
1246 given or the zero length string. The optional operator is equivalent to
1247 \verb/(expr | '' )/. In the following example the optional operator is used to
1250 % GENERATE: exoption
1256 # Match integers or floats.
1257 main := digit+ ('.' digit+)?;
1265 \includegraphics[scale=0.45]{exoption}
1270 \subsection{Repetition}
1273 \noindent \verb|expr {n}| \hspace{16pt}\=-- Exactly N copies of expr.\\
1275 \noindent \verb|expr {,n}| \>-- Zero to N copies of expr.\\
1277 \noindent \verb|expr {n,}| \>-- N or more copies of expr.\\
1279 \noindent \verb|expr {n,m}| \>-- N to M copies of expr.
1282 \subsection{Negation}
1287 Negation produces a machine that matches any string not matched by the given
1288 machine. Negation is equivalent to \verb|(any* - expr)|.
1290 % GENERATE: exnegate
1296 # Accept anything but a string beginning with a digit.
1297 main := ! ( digit any* );
1305 \includegraphics[scale=0.45]{exnegate}
1310 \subsection{Character-Level Negation}
1315 Character-level negation produces a machine that matches any single character
1316 not matched by the given machine. Character-Level Negation is equivalent to
1317 \verb|(any - expr)|.
1319 \section{State Machine Minimization}
1321 State machine minimization is the process of finding the minimal equivalent FSM accepting
1322 the language. Minimization reduces the number of states in machines
1323 by merging equivalent states. It does not change the behaviour of the machine
1324 in any way. It will cause some states to be merged into one because they are
1325 functionally equivalent. State minimization is on by default. It can be turned
1326 off with the \verb|-n| option.
1328 The algorithm implemented is similar to Hopcroft's state minimization
1329 algorithm. Hopcroft's algorithm assumes a finite alphabet that can be listed in
1330 memory, whereas Ragel supports arbitrary integer alphabets that cannot be
1331 listed in memory. Though exact analysis is very difficult, Ragel minimization
1332 runs close to $O(n \times log(n))$ and requires $O(n)$ temporary storage where
1333 $n$ is the number of states.
1335 \section{Visualization}
1337 Ragel is able to emit compiled state machines in Graphviz's Dot file format.
1338 Graphviz support allows users to perform
1339 incremental visualization of their parsers. User actions are displayed on
1340 transition labels of the graph. If the final graph is too large to be
1341 meaningful, or even drawn, the user is able to inspect portions of the parser
1342 by naming particular regular expression definitions with the \verb|-S| and
1343 \verb|-M| options to the \verb|ragel| program. Use of Graphviz greatly
1344 improves the Ragel programming experience. It allows users to learn Ragel by
1345 experimentation and also to track down bugs caused by unintended
1348 \chapter{User Actions}
1350 Ragel permits the user to embed actions into the transitions of a regular
1351 expression's corresponding state machine. These actions are executed when the
1352 generated code moves over a transition. Like the regular expression operators,
1353 the action embedding operators are fully compositional. They take a state
1354 machine and an action as input, embed the action, and yield a new state machine
1355 which can be used in the construction of other machines. Due to the
1356 compositional nature of embeddings, the user has complete freedom in the
1357 placement of actions.
1359 A machine's transitions are categorized into four classes, The action embedding
1360 operators access the transitions defined by these classes. The {\em entering
1361 transition} operator \verb|>| isolates the start state, then embeds an action
1362 into all transitions leaving it. The {\em finishing transition} operator
1363 \verb|@| embeds an action into all transitions going into a final state. The
1364 {\em all transition} operator \verb|$| embeds an action into all transitions of
1365 an expression. The {\em pending out transition} operator \verb|%| provides
1366 access to yet-unmade leaving transitions.
1368 \section{Embedding Actions}
1372 /* Code an action here. */
1378 The action statement defines a block of code that can be embedded into an FSM.
1379 Action names can be referenced by the action embedding operators in
1380 expressions. Though actions need not be named in this way (literal blocks
1381 of code can be embedded directly when building machines), defining reusable
1382 blocks of code whenever possible is good practice because it potentially increases the
1383 degree to which the machine can be minimized. Within an action some Ragel expressions
1384 and statements are parsed and translated. These allow the user to interact with the machine
1385 from action code. See Section \ref{vals} for a complete list of statements and
1386 values available in code blocks.
1388 \subsection{Entering Action}
1390 \verb|expr > action|
1393 The entering operator embeds an action into the starting transitions. The
1394 action is executed on all transitions that enter into the machine from the
1395 start state. If the start state is a final state then it is possible for the
1396 machine to never be entered and the starting transitions bypassed. In the
1397 following example, the action is executed on the first transition of the
1398 machine. If the repetition machine is bypassed the action is not executed.
1408 # Execute A at the beginning of a string of alpha.
1410 main := ( lower* >A ) . ' ';
1418 \includegraphics[scale=0.45]{exstact}
1422 \subsection{Finishing Action}
1424 \verb|expr @ action|
1427 The finishing action operator embeds an action into any transitions that go into a
1428 final state. Whether or not the machine accepts is not determined at the point
1429 the action is executed. Further input may move the machine out of the accepting
1430 state, but keep it in the machine. As in the following example, the
1431 into-final-state operator is most often used when no lookahead is necessary.
1433 % GENERATE: exdoneact
1436 % machine exdoneact;
1440 # Execute A when the trailing space is seen.
1441 main := ( lower* ' ' ) @A;
1449 \includegraphics[scale=0.45]{exdoneact}
1454 \subsection{All Transition Action}
1456 \verb|expr $ action|
1459 The all transition operator embeds an action into all transitions of a machine.
1460 The action is executed whenever a transition of the machine is taken. In the
1461 following example, A is executed on every character matched.
1463 % GENERATE: exallact
1470 # Execute A on any characters of machine one or two.
1471 main := ( 'm1' | 'm2' ) $A;
1479 \includegraphics[scale=0.45]{exallact}
1484 \subsection{Pending Out (Leaving) Actions}
1487 \verb|expr % action|
1490 The pending out action operator embeds an action into the pending out
1491 transitions of a machine. The action is first embedded into the final states of
1492 the machine and later transferred to any transitions made going out of the
1493 machine. The transfer can be caused either by a concatenation or kleene star
1494 operation. This mechanism allows one to associate an action with the
1495 termination of a sequence, without being concerned about what particular
1496 character terminates the sequence. In the following example, A is executed
1497 when leaving the alpha machine by the newline character.
1499 % GENERATE: exoutact1
1502 % machine exoutact1;
1506 # Match a word followed by an newline. Execute A when
1507 # finishing the word.
1508 main := ( lower+ %A ) . '\n';
1516 \includegraphics[scale=0.45]{exoutact1}
1520 In the following example, the \verb|term_word| action could be used to register
1521 the appearance of a word and to clear the buffer that the \verb|lower| action used
1522 to store the text of it.
1524 % GENERATE: exoutact2
1527 % machine exoutact2;
1530 % action term_word {}
1534 word = ( [a-z] @lower )+ %term_word;
1535 main := word ( ' ' @space word )* '\n' @newline;
1543 \includegraphics[scale=0.45]{exoutact2}
1548 In this final example of the action embedding operators, A is executed upon
1549 entering the alpha machine, B is executed on all transitions of the alpha
1550 machine, C is executed when the alpha machine accepts by moving into the
1551 newline machine and N is executed when the newline machine moves into a final
1554 % GENERATE: exaction
1564 # Execute A on starting the alpha machine, B on every transition
1565 # moving through it and C upon finishing. Execute N on the newline.
1566 main := ( lower* >A $B %C ) . '\n' @N;
1574 \includegraphics[scale=0.45]{exaction}
1579 \section{State Action Embedding Operators}
1581 The state embedding operators allow one to embed actions into states. Like the
1582 transition embedding operators, there are several different classes of states
1583 that the operators access. The meanings of the symbols are partially related to
1584 the meanings of the symbols used by the transition embedding operators.
1586 The state embedding operators are different from the transition embedding
1587 operators in that there are various kinds of events that embedded actions can
1588 be associated with, requiring them to be distinguished by these different types
1589 of events. The state embedding operators have two components. The first, which
1590 is the first one or two characters, specifies the class of states that the
1591 action will be embedded into. The second component specifies the type of event
1592 the action will be executed on.
1594 \def\fakeitem{\hspace*{12pt}$\bullet$\hspace*{10pt}}
1596 \begin{minipage}{\textwidth}
1597 \begin{multicols}{2}
1599 \noindent The different classes of states are:\\
1600 \fakeitem \verb|> | -- the start state \\
1601 \fakeitem \verb|$ | -- all states\\
1602 \fakeitem \verb|% | -- final states\\
1603 \fakeitem \verb|< | -- any state except the start state\\
1604 \fakeitem \verb|@ | -- any state except final states\\
1605 \fakeitem \verb|<>| -- any except start and final (middle)
1609 \noindent The different kinds of embeddings are:\\
1610 \fakeitem \verb|~| -- to-state actions\\
1611 \fakeitem \verb|*| -- from-state actions\\
1612 \fakeitem \verb|/| -- EOF actions\\
1613 \fakeitem \verb|!| -- error actions\\
1614 \fakeitem \verb|^| -- local error actions\\
1617 %\label{state-act-embed}
1618 %\caption{The two components of state embedding operators. The class of states
1619 %to select comes first, followed by the type of embedding.}
1623 %\includegraphics{stembed}
1624 %\caption{Summary of state manipulation operators}
1625 %\label{state-act-embed-chart}
1628 %\noindent Putting these two components together we get a matrix of state
1629 %embedding operators. The entire set is given in Figure \ref{state-act-embed-chart}.
1632 \subsection{To-State and From-State Actions}
1634 \subsubsection{To-State Actions}
1636 \verb| >~ $~ %~ <~ @~ <>~ |
1639 To-state actions are executed whenever the state machine moves into the
1640 specified state, either by a natural movement over a transition or by an
1641 action-based transfer of control such as \verb|fgoto|. They are executed after the
1642 in-transition's actions but before the current character is advanced and
1643 tested against the end of the input block. To-state embeddings stay with the
1644 state. They are irrespective of the state's current set of transitions and any
1645 future transitions that may be added in or out of the state.
1647 Note that the setting of the current state variable \verb|cs| outside of the
1648 execute code is not considered by Ragel as moving into a state and consequently
1649 the to-state actions of the new current state are not executed. This includes
1650 the initialization of the current state when the machine begins. This is
1651 because the entry point into the machine execution code is after the execution
1652 of to-state actions.
1654 \subsubsection{From-State Actions}
1656 \verb| >* $* %* <* @* <>* |
1659 From-state actions are executed whenever the state machine takes a transition from a
1660 state, either to itself or to some other state. These actions are executed
1661 immediately after the current character is tested against the input block end
1662 marker and before the transition to take is sought based on the current
1663 character. From-state actions are therefore executed even if a transition
1664 cannot be found and the machine moves into the error state. Like to-state
1665 embeddings, from-state embeddings stay with the state.
1667 \subsection{EOF Actions}
1669 \verb| >/ $/ %/ </ @/ <>/ |
1672 The EOF action embedding operators enable the user to embed EOF actions into
1673 different classes of
1674 states. EOF actions are stored in states and generated with the \verb|write eof|
1675 statement. The generated EOF code switches on the current state and executes the EOF
1676 actions associated with it.
1678 \subsection{Handling Errors}
1680 \subsubsection{Global Error Actions}
1682 \verb| >! $! %! <! @! <>! |
1685 Error actions are stored in states until the final state machine has been fully
1686 constructed. They are then transferred to the transitions that move into the
1687 error state. This transfer entails the creation of a transition from the state
1688 to the error state that is taken on all input characters which are not already
1689 covered by the state's transitions. In other words it provides a default
1690 action. Error actions can induce a recovery by altering \verb|p| and then jumping back
1691 into the machine with \verb|fgoto|.
1693 \subsubsection{Local Error Actions}
1695 \verb| >^ $^ %^ <^ @^ <>^ |
1698 Like global error actions, local error actions are also stored in states until
1699 a transfer point. The transfer point is different however. Each local error action
1700 embedding is associated with a name. When a machine definition has been fully
1701 constructed, all local error actions embeddings associated the same name as the
1702 machine are transferred to error transitions. Local error actions can be used
1703 to specify an action to take when a particular section of a larger state
1704 machine fails to make a match. A particular machine definition's ``thread'' may
1705 die and the local error actions executed, however the machine as a whole may
1706 continue to match input.
1708 There are two forms of local error action embeddings. In the first form the name defaults
1709 to the current machine. In the second form the machine name can be specified. This
1710 is useful when it is more convenient to specify the local error action in a
1711 sub-definition that is used to construct the machine definition where the
1712 transfer should happen. To embed local error actions and explicitly state the
1713 machine on which the transfer is to happen use \verb|(name, action)| as the
1718 \setlength{\parskip}{0in}
1719 \item \verb|expr >^ (name, action) | -- Start state.
1720 \item \verb|expr $^ (name, action) | -- All states.
1721 \item \verb|expr %^ (name, action) | -- Final states.
1722 \item \verb|expr <^ (name, action) | -- Not start state.
1723 \item \verb|expr <>^ (name, action)| -- Not start and not final states.
1727 \section{Action Ordering and Duplicates}
1729 When building a parser by combining smaller expressions which themselves have
1730 embedded actions, it is often the case that transitions are made which need to
1731 execute a number of actions on one input character. For example when we leave
1732 an expression, we may execute the expression's pending out action and the
1733 subsequent expression's starting action on the same input character. We must
1734 therefore devise a method for ordering actions that is both intuitive and
1735 predictable for the user and repeatable by the state machine compiler. The
1736 determinization processes cannot simply order actions by the time at which they
1737 are introduced into a transition -- otherwise the programmer will be at the
1740 We associate with the embedding of each action a distinct timestamp which is
1741 used to order actions that appear together on a single transition in the final
1742 compiled state machine. To accomplish this we traverse the parse tree of
1743 regular expressions and assign timestamps to action embeddings. This algorithm
1744 is recursive in nature and quite simple. When it visits a parse tree node it
1745 assigns timestamps to all {\em starting} action embeddings, recurses on the
1746 parse tree, then assigns timestamps to the remaining {\em all}, {\em
1747 finishing}, and {\em leaving} embeddings in the order in which they appear.
1749 Ragel does not permit actions (defined or unnamed) to appear multiple times in
1750 an action list. When the final machine has been created, actions which appear
1751 more than once in single transition or EOF action list have their duplicates
1752 removed. The first appearance of the action is preserved. This is useful in a
1753 number of scenarios. First, it allows us to union machines with common
1754 prefixes without worrying about the action embeddings in the prefix being
1755 duplicated. Second, it prevents pending out actions from being transferred multiple times
1756 when a concatenation follows a kleene star and the two machines begin with a common
1762 main := word ( '\n' word )* '\n\n';
1765 \section{Values and Statements Available in Code Blocks}
1768 \noindent The following values are available in code blocks:
1771 \item \verb|fpc| -- A pointer to the current character. This is equivalent to
1772 accessing the \verb|p| variable.
1774 \item \verb|fc| -- The current character. This is equivalent to the expression \verb|(*p)|.
1776 \item \verb|fcurs| -- An integer value representing the current state. This
1777 value should only be read from. To move to a different place in the machine
1778 from action code use the \verb|fgoto|, \verb|fnext| or \verb|fcall| statements.
1779 Outside of the machine execution code the \verb|cs| variable may be modified.
1781 \item \verb|ftargs| -- An integer value representing the target state. This
1782 value should only be read from. Again, \verb|fgoto|, \verb|fnext| and
1783 \verb|fcall| can be used to move to a specific entry point.
1785 \item \verb|fentry(<label>)| -- Retrieve an integer value representing the
1786 entry point \verb|label|. The integer value returned will be a compile time
1787 constant. This number is suitable for later use in control flow transfer
1788 statements that take an expression. This value should not be compared against
1789 the current state because any given label can have multiple states representing
1790 it. The value returned by \verb|fentry| will be one of the possibly multiple states the
1794 \noindent The following statements are available in code blocks:
1798 \item \verb|fhold;| -- Do not advance over the current character. If processing
1799 data in multiple buffer blocks, the \verb|fhold| statement should only be used
1800 once in the set of actions executed on a character. Multiple calls may result
1801 in backing up over the beginning of the buffer block. The \verb|fhold|
1802 statement does not imply any transfer of control. In actions embedded into
1803 transitions, it is equivalent to the \verb|p--;| statement. In scanner pattern
1804 actions any changes made to \verb|p| are lost. In this context, \verb|fhold| is
1805 equivalent to \verb|tokend--;|.
1807 \item \verb|fexec <expr>;| -- Set the next character to process. This can be
1808 used to backtrack to previous input or advance ahead.
1809 Unlike \verb|fhold|, which can be used
1810 anywhere, \verb|fexec| requires the user to ensure that the target of the
1811 backtrack is in the current buffer block or is known to be somewhere ahead of
1812 it. The machine will continue iterating forward until \verb|pe| is arrived,
1813 \verb|fbreak| is called or the machine moves into the error state. In actions
1814 embedded into transitions, the \verb|fexec| statement is equivalent to setting
1815 \verb|p| to one position ahead of the next character to process. If the user
1816 also modifies \verb|pe|, it is possible to change the buffer block entirely.
1817 In scanner pattern actions any changes made to \verb|p| are lost. In this
1818 context, \verb|fexec| is equivalent to setting \verb|tokend| to the next
1819 character to process.
1821 \item \verb|fgoto <label>;| -- Jump to an entry point defined by
1822 \verb|<label>|. The \verb|fgoto| statement immediately transfers control to
1823 the destination state.
1825 \item \verb|fgoto *<expr>;| -- Jump to an entry point given by \verb|<expr>|.
1826 The expression must evaluate to an integer value representing a state.
1828 \item \verb|fnext <label>;| -- Set the next state to be the entry point defined
1829 by \verb|label|. The \verb|fnext| statement does not immediately jump to the
1830 specified state. Any action code following the statement is executed.
1832 \item \verb|fnext *<expr>;| -- Set the next state to be the entry point given
1833 by \verb|<expr>|. The expression must evaluate to an integer value representing
1836 \item \verb|fcall <label>;| -- Push the target state and jump to the entry
1837 point defined by \verb|<label>|. The next \verb|fret| will jump to the target
1838 of the transition on which the call was made. Use of \verb|fcall| requires
1839 the declaration of a call stack. An array of integers named \verb|stack| and a
1840 single integer named \verb|top| must be declared. With the \verb|fcall|
1841 construct, control is immediately transferred to the destination state.
1843 \item \verb|fcall *<expr>;| -- Push the current state and jump to the entry
1844 point given by \verb|<expr>|. The expression must evaluate to an integer value
1845 representing a state.
1847 \item \verb|fret;| -- Return to the target state of the transition on which the
1848 last \verb|fcall| was made. Use of \verb|fret| requires the declaration of a
1849 call stack with \verb|fstack| in the struct block. Control is immediately
1850 transferred to the destination state.
1852 \item \verb|fbreak;| -- Save the current state and immediately break out of the
1853 execute loop. This statement is useful in conjunction with the \verb|noend|
1854 write option. Rather than process input until the end marker of the input
1855 buffer is arrived at, the fbreak statement can be used to stop processing input
1856 upon seeing some end-of-string marker. It can also be used for handling
1857 exceptional circumstances. The fbreak statement does not change the pointer to
1858 the current character. After an \verb|fbreak| call the \verb|p| variable will point to
1859 the character that was being traversed over when the action was
1860 executed. The current state will be the target of the current transition.
1864 \noindent {\bf Note:} Once actions with control-flow commands are embedded into a
1865 machine, the user must exercise caution when using the machine as the operand
1866 to other machine construction operators. If an action jumps to another state
1867 then unioning any transition that executes that action with another transition
1868 that follows some other path will cause that other path to be lost. Using
1869 commands that manually jump around a machine takes us out of the domain of
1870 regular languages because transitions that may be conditional and that the
1871 machine construction operators are not aware of are introduced. These
1872 commands should therefore be used with caution.
1875 \chapter{Controlling Nondeterminism}
1876 \label{controlling-nondeterminism}
1878 Along with the flexibility of arbitrary action embeddings comes a need to
1879 control nondeterminism in regular expressions. If a regular expression is
1880 ambiguous, then sup-components of a parser other than the intended parts may become
1881 active. This means that actions which are irrelevant to the
1882 current subset of the parser may be executed, causing problems for the
1885 Tools which are based on regular expression engines and which are used for
1886 recognition tasks will usually function as intended regardless of the presence
1887 of ambiguities. It is quite common for users of scripting languages to write
1888 regular expressions that are heavily ambiguous and it generally does not
1889 matter. As long as one of the potential matches is recognized, there can be any
1890 number of other matches present. In some parsing systems the run-time engine
1891 can employ a strategy for resolving ambiguities, for example always pursuing
1892 the longest possible match and discarding others.
1894 In Ragel, there is no regular expression run-time engine, just a simple state
1895 machine execution model. When we begin to embed actions and face the
1896 possibility of spurious action execution, it becomes clear that controlling
1897 nondeterminism at the machine construction level is very important. Consider
1898 the following example.
1910 line = word $first ( ws word $tail )* '\n';
1919 \includegraphics[scale=0.45]{lines1}
1922 Since the \verb|ws| expression includes the newline character, we will
1923 not finish the \verb|line| expression when a newline character is seen. We will
1924 simultaneously pursue the possibility of matching further words on the same
1925 line and the possibility of matching a second line. Evidence of this fact is
1926 in the state tables. On several transitions both the \verb|first| and
1927 \verb|tail| actions are executed. The solution here is simple: exclude
1928 the newline character from the \verb|ws| expression.
1940 line = word $first ( ws word $tail )* '\n';
1949 \includegraphics[scale=0.45]{lines2}
1952 Solving this kind of problem is straightforward when the ambiguity is created
1953 by strings which are a single character long. When the ambiguity is created by
1954 strings which are multiple characters long we have a more difficult problem.
1955 The following example is an incorrect attempt at a regular expression for C
1958 % GENERATE: comments1
1961 % machine comments1;
1965 comment = '/*' ( any @comm )* '*/';
1966 main := comment ' ';
1973 \includegraphics[scale=0.45]{comments1}
1976 Using standard concatenation, we will never leave the \verb|any*| expression.
1977 We will forever entertain the possibility that a \verb|'*/'| string that we see
1978 is contained in a longer comment and that, simultaneously, the comment has
1979 ended. The concatenation of the \verb|comment| machine with \verb|SP| is done
1980 to show this. When we match space, we are also still matching the comment body.
1982 One way to approach the problem is to exclude the terminating string
1983 from the \verb|any*| expression using set difference. We must be careful to
1984 exclude not just the terminating string, but any string that contains it as a
1985 substring. A verbose, but proper specification of a C comment parser is given
1986 by the following regular expression.
1988 % GENERATE: comments2
1991 % machine comments2;
1995 comment = '/*' ( ( any @comm )* - ( any* '*/' any* ) ) '*/';
2003 \includegraphics[scale=0.45]{comments2}
2007 We have phrased the problem of controlling non-determinism in terms of
2008 excluding strings common to two expressions which interact when combined.
2009 We can also phrase the problem in terms of the transitions of the state
2010 machines that implement these expressions. During the concatenation of
2011 \verb|any*| and \verb|'*/'| we will be making transitions that are composed of
2012 both the loop of the first expression and the final character of the second.
2013 At this time we want the transition on the \verb|'/'| character to take precedence
2014 over and disallow the transition that originated in the \verb|any*| loop.
2016 In another parsing problem, we wish to implement a lightweight tokenizer that we can
2017 utilize in the composition of a larger machine. For example, some HTTP headers
2018 have a token stream as a sub-language. The following example is an attempt
2019 at a regular expression-based tokenizer that does not function correctly due to
2020 unintended nondeterminism.
2022 % GENERATE: smallscanner
2025 % machine smallscanner;
2026 % action start_str {}
2028 % action finish_str {}
2032 lower+ >start_str $on_char %finish_str |
2037 % main := header_contents;
2042 \includegraphics[scale=0.45]{smallscanner}
2045 In this case, the problem with using a standard kleene star operation is that
2046 there is an ambiguity between extending a token and wrapping around the machine
2047 to begin a new token. Using the standard operator, we get an undesirable
2048 nondeterministic behaviour. Evidence of this can be seen on the transition out
2049 of state one to itself. The transition extends the string, and simultaneously,
2050 finishes the string only to immediately begin a new one. What is required is
2052 transitions that represent an extension of a token to take precedence over the
2053 transitions that represent the beginning of a new token. For this problem
2054 there is no simple solution that uses standard regular expression operators.
2056 \section{Priorities}
2058 A priority mechanism was devised and built into the determinization
2059 process, specifically for the purpose of allowing the user to control
2060 nondeterminism. Priorities are integer values embedded into transitions. When
2061 the determinization process is combining transitions that have different
2062 priorities, the transition with the higher priority is preserved and the
2063 transition with the lower priority is dropped.
2065 Unfortunately, priorities can have unintended side effects because their
2066 operation requires that they linger in transitions indefinitely. They must linger
2067 because the Ragel program cannot know when the user is finished with a priority
2068 embedding. A solution whereby they are explicitly deleted after use is
2069 conceivable; however this is not very user-friendly. Priorities were therefore
2070 made into named entities. Only priorities with the same name are allowed to
2071 interact. This allows any number of priorities to coexist in one machine for
2072 the purpose of controlling various different regular expression operations and
2073 eliminates the need to ever delete them. Such a scheme allows the user to
2074 choose a unique name, embed two different priority values using that name
2075 and be confident that the priority embedding will be free of any side effects.
2077 \section{Priority Assignment}
2079 Priorities are integer values assigned to names within transitions.
2080 Only priorities with the same name are allowed to interact. When the machine
2081 construction process is combining transitions that have different priorities
2082 assiged to the same name, the transition with the higher priority is preserved
2083 and the lower priority is dropped.
2085 In the first form of priority embedding the name defaults to the name of the machine
2086 definition that the priority is assigned in. In this sense priorities are by
2087 default local to the current machine definition or instantiation. Beware of
2088 using this form in a longest-match machine, since there is only one name for
2089 the entire set of longest match patterns. In the second form the priority's
2090 name can be specified, allowing priority interaction across machine definition
2094 \setlength{\parskip}{0in}
2095 \item \verb|expr > int| -- Sets starting transitions to have priority int.
2096 \item \verb|expr @ int| -- Sets transitions that go into a final state to have priority int.
2097 \item \verb|expr $ int| -- Sets all transitions to have priority int.
2098 \item \verb|expr % int| -- Sets pending out transitions from final states to
2099 have priority int.\\ When a transition is made going out of the machine (either
2100 by concatenation or kleene star) its priority is immediately set to the pending
2104 The second form of priority assignment allows the programmer to specify the name
2105 to which the priority is assigned.
2108 \setlength{\parskip}{0in}
2109 \item \verb|expr > (name, int)| -- Entering transitions.
2110 \item \verb|expr @ (name, int)| -- Transitions into final state.
2111 \item \verb|expr $ (name, int)| -- All transitions.
2112 \item \verb|expr % (name, int)| -- Pending out transitions.
2115 \section{Guarded Operators that Encapsulate Priorities}
2117 Priorities embeddings are a very expressive mechanism. At the same time they
2118 can be very confusing for the user. They force the user to imagine
2119 the transitions inside two interacting expressions and work out the precise
2120 effects of the operations between them. When we consider
2121 that this problem is worsened by the
2122 potential for side effects caused by unintended priority name collisions, we
2123 see that exposing the user to priorities is rather undesirable.
2125 Fortunately, in practice the use of priorities has been necessary only in a
2126 small number of scenarios. This allows us to encapsulate their functionality
2127 into a small set of operators and fully hide them from the user. This is
2128 advantageous from a language design point of view because it greatly simplifies
2131 Going back to the C comment example, we can now properly specify
2132 it using a guarded concatenation operator which we call {\em finish-guarded
2133 concatenation}. From the user's point of view, this operator terminates the
2134 first machine when the second machine moves into a final state. It chooses a
2135 unique name and uses it to embed a low priority into all
2136 transitions of the first machine. A higher priority is then embedded into the
2137 transitions of the second machine which enter into a final state. The following
2138 example yields a machine identical to the example in Section \ref{priorities}
2142 comment = '/*' ( any @comm )* :>> '*/';
2146 Another guarded operator is {\em left-guarded concatenation}, given by the
2147 \verb|<:| compound symbol. This operator places a higher priority on all
2148 transitions of the first machine. This is useful if one must forcibly separate
2149 two lists that contain common elements. For example, one may need to tokenize a
2150 stream, but first consume leading whitespace.
2152 Ragel also includes a {\em longest-match kleene star} operator, given by the
2153 \verb|**| compound symbol. This
2154 guarded operator embeds a high
2155 priority into all transitions of the machine.
2156 A lower priority is then embedded into pending out transitions
2157 (in a manner similar to pending out action embeddings, described in Section
2158 \ref{out-actions}). When the kleene star operator makes the epsilon transitions from
2159 the final states into the start state, the lower priority will be transferred
2160 to the epsilon transitions. In cases where following an epsilon transition
2161 out of a final state conflicts with an existing transition out of a final
2162 state, the epsilon transition will be dropped.
2164 Other guarded operators are conceivable, such as guards on union that cause one
2165 alternative to take precedence over another. These may be implemented when it
2166 is clear they constitute a frequently used operation.
2167 In the next section we discuss the explicit specification of state machines
2170 \subsection{Entry-Guarded Contatenation}
2175 This operator concatenates two machines, but first assigns a low
2176 priority to all transitions
2177 of the first machine and a high priority to the entering transitions of the
2178 second machine. This operator is useful if from the final states of the first
2179 machine, it is possible to accept the characters in the start transitions of
2180 the second machine. This operator effectively terminates the first machine
2181 immediately upon entering the second machine, where otherwise they would be
2182 pursued concurrently. In the following example, entry-guarded concatenation is
2183 used to move out of a machine that matches everything at the first sign of an
2184 end-of-input marker.
2186 % GENERATE: entryguard
2189 % machine entryguard;
2192 # Leave the catch-all machine on the first character of FIN.
2193 main := any* :> 'FIN';
2200 \includegraphics[scale=0.45]{entryguard}
2204 Entry-guarded concatenation is equivalent to the following:
2208 expr $(unique_name,0) . expr >(unique_name,1)
2211 \subsection{Finish-Guarded Contatenation}
2213 \verb|expr :>> expr|
2217 like the previous operator, except the higher priority is placed on the final
2218 transitions of the second machine. This is useful if one wishes to entertain
2219 the possibility of continuing to match the first machine right up until the
2220 second machine enters a final state. In other words it terminates the first
2221 machine only when the second accepts. In the following example, finish-guarded
2222 concatenation causes the move out of the machine that matches everything to be
2223 delayed until the full end-of-input marker has been matched.
2225 % GENERATE: finguard
2231 # Leave the catch-all machine on the last character of FIN.
2232 main := any* :>> 'FIN';
2239 \includegraphics[scale=0.45]{finguard}
2242 Finish-guarded concatenation is equivalent to the following:
2246 expr $(unique_name,0) . expr @(unique_name,1)
2249 \subsection{Left-Guarded Concatenation}
2254 This operator places
2255 a higher priority on the left expression. It is useful if you want to prefix a
2256 sequence with another sequence composed of some of the same characters. For
2257 example, one can consume leading whitespace before tokenizing a sequence of
2258 whitespace-separated words as in:
2260 % GENERATE: leftguard
2263 % machine leftguard;
2270 main := ( ' '* >start %fin ) <: ( ' ' $ws | [a-z] $alpha )*;
2277 \includegraphics[scale=0.45]{leftguard}
2280 Left-guarded concatenation is equivalent to the following:
2284 expr $(unique_name,1) . expr >(unique_name,0)
2288 \subsection{Longest-Match Kleene Star}
2289 \label{longest_match_kleene_star}
2294 This version of kleene star puts a higher priority on staying in the
2295 machine versus wrapping around and starting over. The LM kleene star is useful
2296 when writing simple tokenizers. These machines are built by applying the
2297 longest-match kleene star to an alternation of token patterns, as in the
2302 % GENERATE: lmkleene
2310 # Repeat tokens, but make sure to get the longest match.
2312 lower ( lower | digit )* %A |
2322 \includegraphics[scale=0.45]{lmkleene}
2325 If a regular kleene star were used the machine above would not be able to
2326 distinguish between extending a word and beginning a new one. This operator is
2331 ( expr $(unique_name,1) %(unique_name,0) )*
2335 When the kleene star is applied, transitions are made out of the machine which
2336 go back into it. These are assigned a priority of zero by the pending out
2337 transition mechanism. This is less than the priority of the transitions out of
2338 the final states that do not leave the machine. When two transitions clash on
2339 the same character, the differing priorities causes the transition which
2340 stays in the machine to take precedence. The transition that wraps around is
2343 Note that this operator does not build a scanner in the traditional sense
2344 because there is never any backtracking. To build a scanner in the traditional
2345 sense use the Longest-Match machine construction described Section
2346 \ref{generating-scanners}.
2348 \chapter{Interface to Host Program}
2350 \section{Alphtype Statement}
2353 alphtype unsigned int;
2357 The alphtype statement specifies the alphabet data type that the machine
2358 operates on. During the compilation of the machine, integer literals are expected to
2359 be in the range of possible values of the alphtype. Supported alphabet types
2360 are \verb|char|, \verb|unsigned char|, \verb|short|, \verb|unsigned short|,
2361 \verb|int|, \verb|unsigned int|, \verb|long|, and \verb|unsigned long|.
2362 The default is \verb|char|.
2364 \section{Getkey Statement}
2371 Specify to Ragel how to retrieve the character that the machine operates on
2372 from the pointer to the current element (\verb|p|). Any expression that returns
2373 a value of the alphabet type
2374 may be used. The getkey statement may be used for looking into element
2375 structures or for translating the character to process. The getkey expression
2376 defaults to \verb|(*p)|. In goto-driven machines the getkey expression may be
2377 evaluated more than once per element processed, therefore it should not incur a
2378 large cost and preclude optimization.
2380 \section{Access Statement}
2387 The access statement allows one to tell Ragel how the generated code should
2388 access the machine data that is persistent across processing buffer blocks.
2389 This includes all variables except \verb|p| and \verb|pe|. This includes
2390 \verb|cs|, \verb|top|, \verb|stack|, \verb|tokstart|, \verb|tokend| and \verb|act|.
2391 This is useful if a machine is to be encapsulated inside a
2392 structure in C code. The access statement can be used to give the name of
2393 a pointer to the structure.
2395 \section{Write Statement}
2396 \label{write-statement}
2399 write <component> [options];
2404 The write statement is used to generate parts of the machine.
2406 components that can be generated by a write statement. These components are the
2407 state machine's data, initialization code, execution code and EOF action
2408 execution code. A write statement may appear before a machine is fully defined.
2409 This allows one to write out the data first then later define the machine where
2410 it is used. An example of this is show in Figure \ref{fbreak-example}.
2412 \subsection{Write Data}
2414 write data [options];
2418 The write data statement causes Ragel to emit the constant static data needed
2419 by the machine. In table-driven output styles (see Section \ref{genout}) this
2420 is a collection of arrays that represent the states and transitions of the
2421 machine. In goto-driven machines much less data is emitted. At the very
2422 minimum a start state \verb|name_start| is generated. All variables written
2423 out in machine data have both the \verb|static| and \verb|const| properties and
2424 are prefixed with the name of the machine and an
2425 underscore. The data can be placed inside a class, inside a function, or it can
2426 be defined as global data.
2428 Two variables are written that may be used to test the state of the machine
2429 after a buffer block has been processed. The \verb|name_error| variable gives
2430 the id of the state that the machine moves into when it cannot find a valid
2431 transition to take. The machine immediately breaks out of the processing loop when
2432 it finds itself in the error state. The error variable can be compared to the
2433 current state to determine if the machine has failed to parse the input. If the
2434 machine is complete, that is from every state there is a transition to a proper
2435 state on every possible character of the alphabet, then no error state is required
2436 and this variable will be set to -1.
2438 The \verb|name_first_final| variable stores the id of the first final state. All of the
2439 machine's states are sorted by their final state status before having their ids
2440 assigned. Checking if the machine has accepted its input can then be done by
2441 checking if the current state is greater-than or equal to the first final
2444 Data generation has several options:
2447 \item \verb|noerror| - Do not generate the integer variable that gives the
2448 id of the error state.
2449 \item \verb|nofinal| - Do not generate the integer variable that gives the
2450 id of the first final state.
2451 \item \verb|noprefix| - Do not prefix the variable names with the name of the
2455 \subsection{Write Init}
2461 The write init statement causes Ragel to emit initialization code. This should
2462 be executed once before the machine is started. At a very minimum this sets the
2463 current state to the start state. If other variables are needed by the
2464 generated code, such as call
2465 stack variables or longest-match management variables, they are also
2468 \subsection{Write Exec}
2470 write exec [options];
2474 The write exec statement causes Ragel to emit the state machine's execution code.
2475 Ragel expects several variables to be available to this code. At a very minimum, the
2476 generated code needs access to the current character position \verb|p|, the ending
2477 position \verb|pe| and the current state \verb|cs|, though \verb|pe|
2478 can be excluded by specifying the \verb|noend| write option.
2479 The \verb|p| variable is the cursor that the execute code will
2480 used to traverse the input. The \verb|pe| variable should be set up to point to one
2481 position past the last valid character in the buffer.
2483 Other variables are needed when certain features are used. For example using
2484 the \verb|fcall| or \verb|fret| statements requires \verb|stack| and
2485 \verb|top| variables to be defined. If a longest-match construction is used,
2486 variables for managing backtracking are required.
2488 The write exec statement has one option. The \verb|noend| option tells Ragel
2489 to generate code that ignores the end position \verb|pe|. In this
2490 case the user must explicitly break out of the processing loop using
2491 \verb|fbreak|, otherwise the machine will continue to process characters until
2492 it moves into the error state. This option is useful if one wishes to process a
2493 null terminated string. Rather than traverse the string to discover then length
2494 before processing the input, the user can break out when the null character is
2495 seen. The example in Figure \ref{fbreak-example} shows the use of the
2496 \verb|noend| write option and the \verb|fbreak| statement for processing a string.
2503 int main( int argc, char **argv )
2505 %% write data noerror nofinal;
2512 0 @{ res = 1; fbreak; };
2517 printf("execute = %i\n", res );
2521 \caption{Use of {\tt noend} write option and the {\tt fbreak} statement for
2522 processing a string.}
2523 \label{fbreak-example}
2527 \subsection{Write EOF Actions}
2533 The write EOF statement causes Ragel to emit code that executes EOF actions.
2534 This write statement is only relevant if EOF actions have been embedded,
2535 otherwise it does not generate anything. The EOF action code requires access to
2538 \section{Maintaining Pointers to Input Data}
2540 In the creation of any parser it is not uncommon to require the collection of
2541 the data being parsed. It is always possible to collect data into a growable
2542 buffer as the machine moves over it, however the copying of data is a somewhat
2543 wasteful use of processor cycles. The most efficient way to collect data
2544 from the parser is to set pointers into the input. This poses a problem for
2545 uses of Ragel where the input data arrives in blocks, such as over a socket or
2546 from a file. The program will error if a pointer is set in one buffer block but
2547 must be used while parsing a following buffer block.
2549 The scanner constructions exhibit this problem, requiring the maintenance
2550 code described in Section \ref{generating-scanners}. If a longest-match
2551 construction has been used somewhere in the machine then it is possible to
2552 take advantage of the required prefix maintenance code in the driver program to
2553 ensure pointers to the input are always valid. If laying down a pointer one can
2554 set \verb|tokstart| at the same spot or ahead of it. When data is shifted in
2555 between loops the user must also shift the pointer. In this way it is possible
2556 to maintain pointers to the input that will always be consistent.
2563 char *p, *pe, *data = buf + have;
2564 int len, space = BUFSIZE - have;
2567 fprintf(stderr, "BUFFER OUT OF SPACE\n");
2571 len = fread( data, 1, space, stdin );
2575 /* Find the last newline by searching backwards. */
2577 pe = data + len - 1;
2578 while ( *pe != '\n' && pe >= buf )
2584 /* How much is still in the buffer? */
2585 have = data + len - pe;
2587 memmove( buf, pe, have );
2593 \caption{An example of line-oriented processing.}
2594 \label{line-oriented}
2597 In general, there are two approaches for guaranteeing the consistency of
2598 pointers to input data. The first approach is the one just described;
2599 lay down a marker from an action,
2600 then later ensure that the data the marker points to is preserved ahead of
2601 the buffer on the next execute invocation. This approach is good because it
2602 allows the parser to decide on the pointer-use boundaries, which can be
2603 arbitrarily complex parsing conditions. A downside is that it requires any
2604 pointers that are set to be corrected in between execute invocations.
2606 The alternative is to find the pointer-use boundaries before invoking the execute
2607 routine, then pass in the data using these boundaries. For example, if the
2608 program must perform line-oriented processing, the user can scan backwards from
2609 the end of an input block that has just been read in and process only up to the
2610 first found newline. On the next input read, the new data is placed after the
2611 partially read line and processing continues from the beginning of the line.
2612 An example of line-oriented processing is given in Figure \ref{line-oriented}.
2615 \section{Running the Executables}
2617 Ragel is broken down into two executables: a frontend which compiles machines
2618 and emits them in an XML format, and a backend which generates code or a
2619 Graphviz Dot file from the XML data. The purpose of the XML-based intermediate
2620 format is to allow users to inspect their compiled state machines and to
2621 interface Ragel to other tools such as custom visualizers, code generators or
2622 analysis tools. The intermediate format will provide a better platform for
2623 extending Ragel to support new host languages. The split also serves to reduce
2624 complexity of the Ragel program by strictly separating the data structures and
2625 algorithms that are used to compile machines from those that are used to
2630 [user@host] myproj: ragel file.rl | rlcodegen -G2 -o file.c
2633 \section{Choosing a Generated Code Style}
2636 The Ragel code generator is very flexible. Following the lead of Re2C, the
2637 generated code has no dependencies and can be inserted in any function, perhaps
2638 inside a loop if so desired. The user is responsible for declaring and
2639 initializing a number of required variables, including the current state and
2640 the pointer to the input stream. The user may break out of the processing loop
2641 and return to it at any time.
2643 Ragel is able to generate very fast-running code that implements state machines
2644 as directly executable code. Since very large files strain the host language
2645 compiler, table-based code generation is also supported. In the future we hope
2646 to provide a partitioned, directly executable format which is able to reduce the
2647 burden on the host compiler by splitting large machines across multiple functions.
2649 Ragel can be used to parse input in one block, or it can be used to parse input
2650 in a sequence of blocks as it arrives from a file or socket. Parsing the
2651 input in a sequence of blocks brings with it a few responsibilities. If the parser
2652 utilizes a scanner, care must be taken to not break the input stream anywhere
2653 but token boundaries. If pointers to the input stream are taken during parsing,
2654 care must be taken to not use a pointer which has been invalidated by movement
2655 to a subsequent block.
2656 If the current input data pointer is moved backwards it must not be moved
2657 past the beginning of the current block.
2658 Strategies for handling these scenarios are given in Ragel's manual.
2660 There are three styles of code output to choose from. Code style affects the
2661 size and speed of the compiled binary. Changing code style does not require any
2662 change to the Ragel program. There are two table-driven formats and a goto
2665 In addition to choosing a style to emit, there are various levels of action
2666 code reuse to choose from. The maximum reuse levels (\verb|-T0|, \verb|-F0|
2667 and \verb|-G0|) ensure that no FSM action code is ever duplicated by encoding
2668 each transition's action list as static data and iterating
2669 through the lists on every transition. This will normally result in a smaller
2670 binary. The less action reuse options (\verb|-T1|, \verb|-F1| and \verb|-G1|)
2671 will usually produce faster running code by expanding each transition's action
2672 list into a single block of code, eliminating the need to iterate through the
2673 lists. This duplicates action code instead of generating the logic necessary
2674 for reuse. Consequently the binary will be larger. However, this tradeoff applies to
2675 machines with moderate to dense action lists only. If a machine's transitions
2676 frequently have less than two actions then the less reuse options will actually
2677 produce both a smaller and a faster running binary due to less action sharing
2678 overhead. The best way to choose the appropriate code style for your
2679 application is to perform your own tests.
2681 The table-driven FSM represents the state machine as constant static data. There are
2682 tables of states, transitions, indices and actions. The current state is
2683 stored in a variable. The execution is simply a loop that looks up the current
2684 state, looks up the transition to take, executes any actions and moves to the
2685 target state. In general, the table-driven FSM can handle any machine, produces
2686 a smaller binary and requires a less expensive host language compile, but
2687 results in slower running code. Since the table-driven format is the most
2688 flexible it is the default code style.
2690 The flat table-driven machine is a table-based machine that is optimized for
2691 small alphabets. Where the regular table machine uses the current character as
2692 the key in a binary search for the transition to take, the flat table machine
2693 uses the current character as an index into an array of transitions. This is
2694 faster in general, however is only suitable if the span of possible characters
2697 The goto-driven FSM represents the state machine using goto and switch
2698 statements. The execution is a flat code block where the transition to take is
2699 computed using switch statements and directly executable binary searches. In
2700 general, the goto FSM produces faster code but results in a larger binary and a
2701 more expensive host language compile.
2703 The goto-driven format has an additional action reuse level (\verb|-G2|) that
2704 writes actions directly into the state transitioning logic rather than putting
2705 all the actions together into a single switch. Generally this produces faster
2706 running code because it allows the machine to encode the current state using
2707 the processor's instruction pointer. Again, sparse machines may actually
2708 compile to smaller binaries when \verb|-G2| is used due to less state and
2709 action management overhead. For many parsing applications \verb|-G2| is the
2710 preferred output format.
2714 \begin{tabular}{|c|c|}
2716 \multicolumn{2}{|c|}{\bf Code Output Style Options} \\
2718 \verb|-T0|&binary search table-driven\\
2720 \verb|-T1|&binary search, expanded actions\\
2722 \verb|-F0|&flat table-driven\\
2724 \verb|-F1|&flat table, expanded actions\\
2726 \verb|-G0|&goto-driven\\
2728 \verb|-G1|&goto, expanded actions\\
2730 \verb|-G2|&goto, in-place actions\\
2735 \chapter{Beyond the Basic Model}
2737 \section{Parser Modularization}
2739 It is possible to use Ragel's machine construction and action embedding
2740 operators to specify an entire parser using a single regular expression. An
2741 example is given in Section \ref{examples}. In many cases this is the desired
2742 way to specify a parser in Ragel. However, in some scenarios, the language to
2743 parse may be so large that it is difficult to think about it as a single
2744 regular expression. It may shift between distinct parsing strategies,
2745 in which case modularization into several coherent blocks of the language may
2748 It may also be the case that patterns which compile to a large number of states
2749 must be used in a number of different contexts and referencing them in each
2750 context results in a very large state machine. In this case, an ability to reuse
2751 parsers would reduce code size.
2753 To address this, distinct regular expressions may be instantiated and linked
2754 together by means of a jumping and calling mechanism. This mechanism is
2755 analogous to the jumping to and calling of processor instructions. A jump
2756 command, given in action code, causes control to be immediately passed to
2757 another portion of the machine by way of setting the current state variable. A
2758 call command causes the target state of the current transition to be pushed to
2759 a state stack before control is transferred. Later on, the original location
2760 may be returned to with a return statement. In the following example, distinct
2761 state machines are used to handle the parsing of two types of headers.
2768 action return { fret; }
2769 action call_date { fcall date; }
2770 action call_name { fcall name; }
2772 # A parser for date strings.
2773 date := [0-9][0-9] '/'
2775 [0-9][0-9][0-9][0-9] '\n' @return;
2777 # A parser for name strings.
2778 name := ( [a-zA-Z]+ | ' ' )** '\n' @return;
2782 ( 'from' | 'to' ) ':' @call_name |
2783 ( 'departed' | 'arrived' ) ':' @call_date;
2797 Calling and jumping should be used carefully as they are operations which take
2798 one out of the domain
2799 of regular languages. A machine that contains a call or jump statement in one
2800 of its actions should be used as an argument to a machine construction operator
2801 only with considerable care. Since DFA transitions may actually
2802 represent several NFA transitions, a call or jump embedded in one machine can
2803 inadvertently terminate another machine that it shares prefixes with. Despite
2804 this danger, theses statements have proven useful for tying together
2805 sub-parsers of a language into a parser for the full language, especially for
2806 the purpose of modularization and reducing the number of states when the
2807 machine contains frequently recurring patterns.
2808 \section{Referencing Names}
2811 This section describes how to reference names in epsilon transitions and
2812 action-based control-flow statements such as \verb|fgoto|. There is a hierarchy
2813 of names implied in a Ragel specification. At the top level are the machine
2814 instantiations. Beneath the instantiations are labels and references to machine
2815 definitions. Beneath those are more labels and references to definitions, and
2818 Any name reference may contain multiple components separated with the \verb|::|
2819 compound symbol. The search for the first component of a name reference is
2820 rooted at the join expression that the epsilon transition or action embedding
2821 is contained in. If the name reference is not not contained in a join,
2822 the search is rooted at the machine definition that that the epsilon transition or
2823 action embedding is contained in. Each component after the first is searched
2824 for beginning at the location in the name tree that the previous reference
2825 component refers to.
2827 In the case of action-based references, if the action is embedded more than
2828 once, the local search is performed for each embedding and the result is the
2829 union of all the searches. If no result is found for action-based references then
2830 the search is repeated at the root of the name tree. Any action-based name
2831 search may be forced into a strictly global search by prefixing the name
2832 reference with \verb|::|.
2834 The final component of the name reference must resolve to a unique entry point.
2835 If a name is unique in the entire name tree it can be referenced as is. If it
2836 is not unique it can be specified by qualifying it with names above it in the
2837 name tree. However, it can always be renamed.
2839 % FIXME: Should fit this in somewhere.
2840 % Some kinds of name references are illegal. Cannot call into longest-match
2841 % machine, can only call its start state. Cannot make a call to anywhere from
2842 % any part of a longest-match machine except a rule's action. This would result
2843 % in an eventual return to some point inside a longest-match other than the
2844 % start state. This is banned for the same reason a call into the LM machine is
2850 Scanners are very much intertwinded with regular-languages and their
2851 corresponding processors. For this reason Ragel supports the definition of
2852 Scanners. The generated code will repeatedly attempt to match patterns from a
2853 list, favouring longer patterns over shorter patterns. In the case of
2854 equal-length matches, the generated code will favour patterns that appear ahead
2855 of others. When a scanner makes a match it executes the user code associated
2856 with the match, consumes the input then resumes scanning.
2860 <machine_name> := |*
2861 pattern1 => action1;
2862 pattern2 => action2;
2868 On the surface, Ragel scanners are similar to those defined by Lex. Though
2869 there is a key distinguishing feature: patterns may be arbitrary Ragel
2870 expressions and can therefore contain embedded code. With a Ragel-based scanner
2871 the user need not wait until the end of a pattern before user code can be
2874 Scanners can be used to processes sub-languages, as well as for tokenizing
2875 programming languages. In the following example a scanner is used to tokenize
2876 the contents of header field.
2881 head_name = 'Header';
2889 main := ( head_name ':' @{ fcall header; } )*;
2894 The scanner construction has a purpose similar to the longest-match kleene star
2895 operator \verb|**|. The key
2896 difference is that a scanner is able to backtrack to match a previously matched
2897 shorter string when the pursuit of a longer string fails. For this reason the
2898 scanner construction operator is not a pure state machine construction
2899 operator. It relies on several variables which enable it to backtrack and make
2900 pointers to the matched input text available to the user. For this reason
2901 scanners must be immediately instantiated. They cannot be defined inline or
2902 referenced by another expression. Scanners must be jumped to or called.
2904 Scanners rely on the \verb|tokstart|, \verb|tokend| and \verb|act|
2905 variables to be present so that it can backtrack and make pointers to the
2906 matched text available to the user. If input is processed using multiple calls
2907 to the execute code then the user must ensure that when a token is only
2908 partially matched that the prefix is preserved on the subsequent invocation of
2911 The \verb|tokstart| variable must be defined as a pointer to the input data.
2912 It is used for recording where the current token match begins. This variable
2913 may be used in action code for retrieving the text of the current match. Ragel
2914 ensures that in between tokens and outside of the longest-match machines that
2915 this pointer is set to null. In between calls to the execute code the user must
2916 check if \verb|tokstart| is set and if so, ensure that the data it points to is
2917 preserved ahead of the next buffer block. This is described in more detail
2920 The \verb|tokend| variable must also be defined as a pointer to the input data.
2921 It is used for recording where a match ends and where scanning of the next
2922 token should begin. This can also be used in action code for retrieving the
2923 text of the current match.
2925 The \verb|act| variable must be defined as an integer type. It is used for
2926 recording the identity of the last pattern matched when the scanner must go
2927 past a matched pattern in an attempt to make a longer match. If the longer
2928 match fails it may need to consult the act variable. In some cases use of the act
2929 variable can be avoided because the value of the current state is enough
2930 information to determine which token to accept, however in other cases this is
2931 not enough and so the \verb|act| variable is used.
2933 When the longest-match operator is in use, the user's driver code must take on
2934 some buffer management functions. The following algorithm gives an overview of
2935 the steps that should be taken to properly use the longest-match operator.
2938 \setlength{\parskip}{0pt}
2939 \item Read a block of input data.
2940 \item Run the execute code.
2941 \item If \verb|tokstart| is set, the execute code will expect the incomplete
2942 token to be preserved ahead of the buffer on the next invocation of the execute
2945 \item Shift the data beginning at \verb|tokstart| and ending at \verb|pe| to the
2946 beginning of the input buffer.
2947 \item Reset \verb|tokstart| to the beginning of the buffer.
2948 \item Shift \verb|tokend| by the distance from the old value of \verb|tokstart|
2949 to the new value. The \verb|tokend| variable may or may not be valid. There is
2950 no way to know if it holds a meaningful value because it is not kept at null
2951 when it is not in use. It can be shifted regardless.
2953 \item Read another block of data into the buffer, immediately following any
2955 \item Run the scanner on the new data.
2958 Figure \ref{preserve_example} shows the required handling of an input stream in
2959 which a token is broken by the input block boundaries. After processing up to
2960 and including the ``t'' of ``characters'', the prefix of the string token must be
2961 retained and processing should resume at the ``e'' on the next iteration of
2964 If one uses a large input buffer for collecting input then the number of times
2965 the shifting must be done will be small. Furthermore, if one takes care not to
2966 define tokens that are allowed to be very long and instead processes these
2967 items using pure state machines or sub-scanners, then only a small amount of
2968 data will ever need to be shifted.
2972 a) A stream "of characters" to be scanned.
2976 b) "of characters" to be scanned.
2980 \caption{Following an invocation of the execute code there may be a partially
2981 matched token (a). The data of the partially matched token
2982 must be preserved ahead of the new data on the next invocation (b).}
2983 \label{preserve_example}
2986 Since scanners attempt to make the longest possible match of input, in some
2987 cases they are not able to identify a token upon parsing its final character,
2988 they must wait for a lookahead character. For example if trying to match words,
2989 the token match must be triggered on following whitespace in case more
2990 characters of the word have yet to come. The user must therefore arrange for an
2991 EOF character to be sent to the scanner to flush out any token that has not yet
2992 been matched. The user can exclude a single character from the entire scanner
2993 and use this character as the EOF character, possibly specifying an EOF action.
2994 For most scanners, zero is a suitable choice for the EOF character.
2996 Alternatively, if whitespace is not significant and ignored by the scanner, the
2997 final real token can be flushed out by simply sending an additional whitespace
2998 character on the end of the stream. If the real stream ends with whitespace
2999 then it will simply be extended and ignored. If it does not, then the last real token is
3000 guaranteed to be flushed and the dummy EOF whitespace ignored.
3001 An example scanner processing loop is given in Figure \ref{scanner-loop}.
3009 /* How much space is in the buffer? */
3010 int space = BUFSIZE - have;
3012 /* Buffer is full. */
3013 cerr << "TOKEN TOO BIG" << endl;
3017 /* Read in a block after any data we already have. */
3018 char *p = inbuf + have;
3019 cin.read( p, space );
3020 int len = cin.gcount();
3022 /* If no data was read, send the EOF character.
3031 if ( cs == RagelScan_error ) {
3032 /* Machine failed before finding a token. */
3033 cerr << "PARSE ERROR" << endl;
3037 if ( tokstart == 0 )
3040 /* There is a prefix to preserve, shift it over. */
3041 have = pe - tokstart;
3042 memmove( inbuf, tokstart, have );
3043 tokend = inbuf + (tokend-tokstart);
3048 \caption{A processing loop for a scanner.}
3049 \label{scanner-loop}
3052 \section{State Charts}
3054 In addition to supporting the construction of state machines using regular
3055 languages, Ragel provides a way to manually specify state machines using
3056 state charts. The comma operator wombines machines together without any
3057 implied transitions. The user can then manually link machines by specifying
3058 epsilon transitions with the \verb|->| operator. Epsilon transitions are drawn
3059 between the final states of a machine and entry points defined by labels. This
3060 makes it possible to build machines using the explicit state-chart method while
3061 making minimal changes to the Ragel language.
3063 An interesting feature of Ragel's state chart construction method is that it
3064 can be mixed freely with regular expression constructions. A state chart may be
3065 referenced from within a regular expression, or a regular expression may be
3066 used in the definition of a state chart transition.
3070 \verb|expr , expr , ...|
3073 Join a list of machines together without
3074 drawing any transitions, without setting up a start state, and without
3075 designating any final states. Transitions between the machines may be specified
3076 using labels and epsilon transitions. The start state must be explicity
3077 specified with the ``start'' label. Final states may be specified with the an
3078 epsilon transition to the implicitly created ``final'' state. The join
3079 operation allows one to build machines using a state chart model.
3086 Attaches a label to an expression. Labels can be
3087 used as the target of epsilon transitions and explicit control transfer
3088 statements such \verb|fgoto| and \verb|fnext| in action
3091 \subsection{Epsilon}
3093 \verb|expr -> label|
3096 Draws an epsilon transition to the state defined
3097 by \verb|label|. Epsilon transitions are made deterministic when join
3098 operators are evaluated. Epsilon transitions that are not in a join operation
3099 are made deterministic when the machine definition that contains the epsilon is
3100 complete. See Section \ref{labels} for information on referencing labels.
3102 \subsection{Simplifying State Charts}
3104 There are two benefits to providing state charts in Ragel. The first is that it
3105 allows us to take a state chart with a full listing of states and transitions
3106 and simplifly it in selective places using regular expressions.
3108 The state chart method of specifying parsers is a very common. It is an
3109 effective programming technique for producing robust code. The key disadvantage
3110 becomes clear when one attempts to comprehend a large parser specified in this
3111 way. These programs usually require many lines, causing logic to be spread out
3112 over large distances in the source file. Remembering the function of a large
3113 number of states can be difficult and organizing the parser in a sensible way
3114 requires discipline because branches and repetition present many file layout
3115 options. This kind of programming takes a specification with inherent
3116 structure such as looping, alternation and concatenation and expresses it in a
3119 If we could take an isolated component of a manually programmed state chart,
3120 that is, a subset of states that has only one entry point, and implement it
3121 using regular language operators then we could eliminate all the explicit
3122 naming of the states contained in it. By eliminating explicitly named states
3123 and replacing them with higher-level specifications we simplify a state machine
3126 For example, sometimes chains of states are needed, with only a small number of
3127 possible characters appearing along the chain. These can easily be replaced
3128 with a concatenation of characters. Sometimes a group of common states
3129 implement a loop back to another single portion of the machine. Rather than
3130 manually duplicate all the transitions that loop back, we may be able to
3131 express the loop using a kleene star operator.
3133 Ragel allows one to take this state map simplification approach. We can build
3134 state machines using a state map model and implement portions of the state map
3135 using regular languages. In place of any transition in the state machine,
3136 entire sub-state machines can be given. These can encapsulate functionality
3137 defined elsewhere. An important aspect of the Ragel approach is that when we
3138 wrap up a collection of states using a regular expression we do not loose
3139 access to the states and transitions. We can still execute code on the
3140 transitions that we have encapsulated.
3142 \subsection{Dropping Down One Level of Abstraction}
3145 The second benefit of incorporating state charts into Ragel is that it permits
3146 us to bypass the regular language abstraction if we need to. Ragel's action
3147 embedding operators are sometimes insufficient for expressing certain parsing
3148 tasks. In the same way that is useful for C language programmers to drop down
3149 to assembly language programming using embedded assembler, it is sometimes
3150 useful for the Ragel programmer to drop down to programming with state charts.
3152 In the following example, we wish to buffer the characters of an XML CDATA
3153 sequence. The sequence is terminated by the string \verb|]]>|. The challenge
3154 in our application is that we do not wish the terminating characters to be
3155 buffered. An expression of the form \verb|any* @buffer :>> ']]>'| will not work
3156 because the buffer will alway contain the characters \verb|]]| on the end.
3157 Instead, what we need is to delay the buffering of \hspace{0.25mm} \verb|]|
3158 characters until a time when we
3159 abandon the terminating sequence and go back into the main loop. There is no
3160 easy way to express this using Ragel's regular expression and action embedding
3161 operators, and so an ability to drop down to the state chart method is useful.
3163 % GENERATE: dropdown
3169 action bchar { buff( fpc ); } # Buffer the current character.
3170 action bbrack1 { buff( "]" ); }
3171 action bbrack2 { buff( "]]" ); }
3176 (any-']') @bchar ->start
3180 [^\]] @bbrack1 @bchar ->start
3184 ']' @bbrack1 -> two |
3185 [^>\]] @bbrack2 @bchar ->start
3189 % main := CDATA_body;
3194 \includegraphics[scale=0.45]{dropdown}
3198 \section{Semantic Conditions}
3201 Many communication protocols contain variable-length fields, where the length
3202 of the field is given ahead of the field as a value. This
3203 problem cannot be expressed using regular languages because of its
3204 context-dependent nature. The prevalence of variable-length fields in
3205 communication protocols motivated us to introduce semantic conditions into
3208 A semantic condition is a block of user code which is executed immediately
3209 before a transition is taken. If the code returns a value of true, the
3210 transition may be taken. We can now embed code which extracts the length of a
3211 field, then proceed to match $n$ data values.
3220 action rec_num { i = 0; n = getnumber(); }
3221 action test_len { i++ < n }
3226 ( [a-z] when test_len )*
3230 % main := data_fields;
3235 \includegraphics[scale=0.45]{conds1}
3238 The Ragel implementation of semantic conditions does not force us to give up the
3239 compositional property of Ragel definitions. For example, a machine which tests
3240 the length of a field using conditions can be unioned with another machine
3241 which accepts some of the same strings, without the two machines interfering with
3242 another. The user need not be concerned about whether or not the result of the
3243 semantic condition will affect the matching of the second machine.
3245 To see this, first consider that when a user associates a condition with an
3246 existing transition, the transition's label is translated from the base character
3247 to its corresponding value in the space which represents ``condition $c$ true''. Should
3248 the determinization process combine a state that has a conditional transition
3249 with another state has a transition on the same input character but
3250 without a condition, then the condition-less transition first has its label
3251 translated into two values, one to its corresponding value in the space which
3252 represents ``condition $c$ true'' and another to its corresponding value in the
3253 space which represents ``condition $c$ false''. It
3254 is then safe to combine the two transitions. This is shown in the following
3255 example. Two intersecting patterns are unioned, one with a condition and one
3256 without. The condition embedded in the first pattern does not affect the second
3266 action test_len { i++ < n }
3267 action one { /* accept pattern one */ }
3268 action two { /* accept pattern two */ }
3270 ( [a-z] when test_len )+ %one |
3271 [a-z][a-z0-9]* %two;
3272 main := patterns '\n';
3279 \includegraphics[scale=0.45]{conds2}
3282 There are many more potential uses for semantic conditions. The user is free to
3283 use arbitrary code and may therefore perform actions such as looking up names
3284 in dictionaries, validating input using external parsing mechanisms or
3285 performing checks on the semantic structure of input seen so far. In the
3286 next section we describe how Ragel accommodates several common parser
3287 engineering problems.
3289 \section{Implementing Lookahead}
3291 There are a few strategies for implementing lookahead in Ragel programs.
3292 Pending out actions, which were described in Section \ref{out-actions}, can be
3293 used as a form of lookahead. Ragel also provides the \verb|fhold| directive
3294 which can be used in actions to prevent the machine from advancing over the
3295 current character. It is also possible to manually adjust the current
3296 character position by shifting it backwards.
3298 \section{Handling Errors}
3300 In many applications it is useful to be able to react to parsing errors. The
3301 user may wish to print an error message which depends on the context. It
3302 may also be desirable to consume input in an attempt to return the input stream
3303 to some known state and resume parsing.
3305 To support error handling and recovery, Ragel provides error action embedding
3306 operators. Error actions are embedded into an expression's states. When the
3307 final machine has been constructed and it is being made complete, error actions
3308 are transfered from their place of embedding within a state to the transitions
3309 which go to the error
3310 state. When the machine fails and is about to move into the error state, the
3311 current state's error actions get executed.
3313 Error actions can be used to simply report errors, or by jumping to a machine
3314 instantiation which consumes input, can attempt to recover from errors. Like
3315 the action embedding operators, there are several classes of states which
3316 error action embedding operators can access. For example, the \verb|@err|
3317 operator embeds an error action into non-final states. The \verb|$err| operator
3318 embeds an error action into all states. Other operators access the start state,
3319 final states, and states which are neither the start state nor are final. The
3320 design of the state selections was driven by a need to cover the states of an
3321 expression with a single error action.
3323 The following example uses error actions to report an error and jump to a
3324 machine which consumes the remainder of the line when parsing fails. After
3325 consuming the line, the error recovery machine returns to the main loop.
3331 % address = 'foo@bar.com';
3332 % date = 'Monday May 12';
3336 printf( "command error\n" );
3340 printf( "from error\n" );
3344 printf( "to error\n" );
3348 line := [^\n]* '\n' @{ fgoto main; };
3353 ( ws+ address ws+ date '\n' ) $err from_err |
3355 ( ws+ address '\n' ) $err to_err