03672a7bced00aec48367a9f01bf408f0e3cebfd
[external/ragel.git] / doc / ragel-guide.tex
1 %
2 %   Copyright 2001-2007 Adrian Thurston <thurston@cs.queensu.ca>
3 %
4
5 %   This file is part of Ragel.
6 %
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.
11 %
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.
16 %
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 
20
21 % TODO: Need a section on the different strategies for handline recursion.
22
23 \documentclass[letterpaper,11pt,oneside]{book}
24 \usepackage{graphicx}
25 \usepackage{comment}
26 \usepackage{multicol}
27
28 \topmargin -0.20in
29 \oddsidemargin 0in
30 \textwidth 6.5in
31 \textheight 9in
32
33 \setlength{\parskip}{0pt}
34 \setlength{\topsep}{0pt}
35 \setlength{\partopsep}{0pt}
36 \setlength{\itemsep}{0pt}
37
38 \input{version}
39
40 \newcommand{\verbspace}{\vspace{10pt}}
41 \newcommand{\graphspace}{\vspace{10pt}}
42
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}
50
51 \newenvironment{inline_code}{\def\baselinestretch{1}\vspace{12pt}\small}{}
52
53 \begin{document}
54
55 %
56 % Title page
57 %
58 \thispagestyle{empty}
59 \begin{center}
60 \vspace*{3in}
61 {\huge Ragel State Machine Compiler}\\
62 \vspace*{12pt}
63 {\Large User Guide}\\
64 \vspace{1in}
65 by\\
66 \vspace{12pt}
67 {\large Adrian Thurston}\\
68 \end{center}
69 \clearpage
70
71 \pagenumbering{roman}
72
73 %
74 % License page
75 %
76 \chapter*{License}
77 Ragel version \version, \pubdate\\
78 Copyright \copyright\ 2003-2007 Adrian Thurston
79 \vspace{6mm}
80
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)
84 any later version.}
85
86 \vspace{5pt}
87
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
91 details.}
92
93 \vspace{5pt}
94
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}
98
99 %
100 % Table of contents
101 %
102 \clearpage
103 \tableofcontents
104 \clearpage
105
106 %
107 % Chapter 1
108 %
109
110 \pagenumbering{arabic}
111
112 \chapter{Introduction}
113
114 \section{Abstract}
115
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. 
122
123 Ragel is a software development tool that 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 expression.  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, D, Java or Ruby.
132
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 is small and
138 runs very fast. Ragel can handle integer-sized alphabets and can compile very
139 large state machines.
140
141 \section{Motivation}
142
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
152 languages is wasted.
153
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.
165
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 that 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 that 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
178 disrupt its syntax.
179
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's state machine
182 in support of the
183 definition of entire parsers or large sections of parsers using a single
184 regular expression.  From the
185 regular expression we gain a clear and concise statement of our language. From
186 the state machine we obtain a very fast and robust executable that lends itself
187 to many kinds of analysis and visualization.
188
189 \section{Overview}
190
191 Ragel is a language for specifying state machines. The Ragel program is a
192 compiler that assembles a state machine definition to executable code.  Ragel
193 is based on the principle that any regular language can be converted to a
194 deterministic finite state automaton. Since every regular language has a state
195 machine representation and vice versa, the terms regular language and state
196 machine (or just machine) will be used interchangeably in this document.
197
198 Ragel outputs machines to C, C++, Objective-C, D, Java or Ruby code. The output is
199 designed to be generic and is not bound to any particular input or processing
200 method. A Ragel machine expects to have data passed to it in buffer blocks.
201 When there is no more input, the machine can be queried for acceptance.  In
202 this way, a Ragel machine can be used to simply recognize a regular language
203 like a regular expression library. By embedding code into the regular language,
204 a Ragel machine can also be used to parse input.
205
206 The Ragel language has many operators for constructing and manipulating
207 machines. Machines are built up from smaller machines, to bigger ones, to the
208 final machine representing the language that needs to be recognized or parsed.
209
210 The core state machine construction operators are those found in most theory
211 of computation textbooks. They date back to the 1950s and are widely studied.
212 They are based on set operations and permit one to think of languages as a set
213 of strings. They are Union, Intersection, Difference, Concatenation and Kleene
214 Star. Put together, these operators make up what most people know as regular
215 expressions. Ragel also provides a scanner construction operator 
216 and provides operators for explicitly constructing machines
217 using a state chart method. In the state chart method, one joins machines
218 together without any implied transitions and then explicitly specifies where
219 epsilon transitions should be drawn.
220
221 The state machine manipulation operators are specific to Ragel. They allow the
222 programmer to access the states and transitions of regular language's
223 corresponding machine. There are two uses of the manipulation operators. The
224 first and primary use is to embed code into transitions and states, allowing
225 the programmer to specify the actions of the state machine.
226
227 Ragel attempts to make the action embedding facility as intuitive as possible.
228 To do so, a number of issues need to be addressed.  For example, when making a
229 nondeterministic specification into a DFA using machines that have embedded
230 actions, new transitions are often made that have the combined actions of
231 several source transitions. Ragel ensures that multiple actions associated with
232 a single transition are ordered consistently with respect to the order of
233 reference and the natural ordering implied by the construction operators.
234
235 The second use of the manipulation operators is to assign priorities in
236 transitions. Priorities provide a convenient way of controlling any
237 nondeterminism introduced by the construction operators. Suppose two
238 transitions leave from the same state and go to distinct target states on the
239 same character. If these transitions are assigned conflicting priorities, then
240 during the determinization process the transition with the higher priority will
241 take precedence over the transition with the lower priority. The lower priority
242 transition gets abandoned. The transitions would otherwise be combined into a new
243 transition that goes to a new state that is a combination of the original
244 target states. Priorities are often required for segmenting machines. The most
245 common uses of priorities have been encoded into a set of simple operators
246 that should be used instead of priority embeddings whenever possible.
247
248 For the purposes of embedding, Ragel divides transitions and states into
249 different classes. There are four operators for embedding actions and
250 priorities into the transitions of a state machine. It is possible to embed
251 into start transitions, finishing transitions, all transitions and pending out
252 transitions.  The embedding of pending out transitions is a special case.
253 These transition embeddings get stored in the final states of a machine.  They
254 are transferred to any transitions that may be made going out of the machine by
255 a concatenation or kleene star operator.
256
257 There are several more operators for embedding actions into states. Like the
258 transition embeddings, there are various different classes of states that the
259 embedding operators access. For example, one can access start states, final
260 states or all states, among others. Unlike the transition embeddings, there are
261 several different types of state action embeddings. These are executed at
262 various different times during the processing of input. It is possible to embed
263 actions which are exectued on all transitions that enter into a state, all
264 transitions out of a state, transitions taken on the error event, or
265 transitions taken on the EOF event.
266
267 Within actions, it is possible to influence the behaviour of the state machine.
268 The user can write action code that jumps or calls to another portion of the
269 machine, changes the current character being processed, or breaks out of the
270 processing loop. With the state machine calling feature Ragel can be used to
271 parse languages that are not regular. For example, one can parse balanced
272 parentheses by calling into a parser when an open bracket character is seen and
273 returning to the state on the top of the stack when the corresponding closing
274 bracket character is seen. More complicated context-free languages such as
275 expressions in C, are out of the scope of Ragel. 
276
277 Ragel also provides a scanner construction operator which can be used to build scanners
278 much the same way that Lex is used. The Ragel generated code, which relies on
279 user-defined variables for
280 backtracking, repeatedly tries to match patterns to the input, favouring longer
281 patterns over shorter ones and patterns that appear ahead of others when the
282 lengths of the possible matches are identical. When a pattern is matched the
283 associated action is executed. 
284
285 The key distinguishing feature between scanners in Ragel and scanners in Lex is
286 that Ragel patterns may be arbitrary Ragel expressions and can therefore
287 contain embedded code. With a Ragel-based scanner the user need not wait until
288 the end of a pattern before user code can be executed.
289
290 Scanners do take Ragel out of the domain of pure state machines and require the
291 user to maintain the backtracking related variables.  However, scanners
292 integrate well with regular state machine instantiations. They can be called to
293 or jumped to only when needed, or they can be called out of or jumped out of
294 when a simpler, pure state machine model is appropriate.
295
296 Two types of output code style are available. Ragel can produce a table-driven
297 machine or a directly executable machine. The directly executable machine is
298 much faster than the table-driven. On the other hand, the table-driven machine
299 is more compact and less demanding on the host language compiler. It is better
300 suited to compiling large state machines.
301
302 \section{Related Work}
303
304 Lex is perhaps the best-known tool for constructing parsers from regular
305 expressions. In the Lex processing model, generated code attempts to match one
306 of the user's regular expression patterns, favouring longer matches over
307 shorter ones. Once a match is made it then executes the code associated with
308 the pattern and consumes the matching string.  This process is repeated until
309 the input is fully consumed. 
310
311 Through the use of start conditions, related sets of patterns may be defined.
312 The active set may be changed at any time.  This allows the user to define
313 different lexical regions. It also allows the user to link patterns together by
314 requiring that some patterns come before others.  This is quite like a
315 concatenation operation. However, use of Lex for languages that require a
316 considerable amount of pattern concatenation is inappropriate. In such cases a
317 Lex program deteriorates into a manually specified state machine, where start
318 conditions define the states and pattern actions define the transitions.  Lex
319 is therefore best suited to parsing tasks where the language to be parsed can
320 be described in terms of regions of tokens. 
321
322 Lex is useful in many scenarios and has undoubtedly stood the test of time.
323 There are, however, several drawbacks to using Lex.  Lex can impose too much
324 overhead for parsing applications where buffering is not required because all
325 the characters are available in a single string.  In these cases there is
326 structure to the language to be parsed and a parser specification tool can
327 help, but employing a heavyweight processing loop that imposes a stream
328 ``pull'' model and dynamic input buffer allocation is inappropriate.  An
329 example of this kind of scenario is the conversion of floating point numbers
330 contained in a string to their corresponding numerical values.
331
332 Another drawback is the very issue that Ragel attempts to solve.
333 It is not possbile to execute a user action while
334 matching a character contained inside a pattern. For example, if scanning a
335 programming language and string literals can contain newlines which must be
336 counted, a Lex user must break up a string literal pattern so as to associate
337 an action with newlines. This forces the definition of a new start condition.
338 Alternatively the user can reprocess the text of the matched string literal to
339 count newlines. 
340
341 \begin{comment}
342 How ragel is different from Lex.
343
344 %Like Re2c, Ragel provides a simple execution model that does not make any
345 %assumptions as to how the input is collected.  Also, Ragel does not do any
346 %buffering in the generated code. Consequently there are no dependencies on
347 %external functions such as \verb|malloc|. 
348
349 %If buffering is required it can be manually implemented by embedding actions
350 %that copy the current character to a buffer, or data can be passed to the
351 %parser using known block boundaries. If the longest-match operator is used,
352 %Ragel requires the user to ensure that the ending portion of the input buffer
353 %is preserved when the buffer is exhaused before a token is fully matched. The
354 %user should move the token prefix to a new memory location, such as back to the
355 %beginning of the input buffer, then place the subsequently read input
356 %immediately after the prefix.
357
358 %These properties of Ragel make it more work to write a program that requires
359 %the longest-match operator or buffering of input, however they make Ragel a
360 %more flexible tool that can produce very simple and fast-running programs under
361 %a variety of input acquisition arrangements.
362
363 %In Ragel, it is not necessary
364 %to introduce start conditions to concatenate tokens and retain action
365 %execution. Ragel allows one to structure a parser as a series of tokens, but
366 %does not require it.
367
368 %Like Lex and Re2C, Ragel is able to process input using a longest-match
369 %execution model, however the core of the Ragel language specifies parsers at a
370 %much lower level. This core is built around a pure state machine model. When
371 %building basic machines there is no implied algorithm for processing input
372 %other than to move from state to state on the transitions of the machine. This
373 %core of pure state machine operations makes Ragel well suited to handling
374 %parsing problems not based on token scanning. Should one need to use a
375 %longest-match model, the functionality is available and the lower level state
376 %machine construction facilities can be used to specify the patterns of a
377 %longest-match machine.
378
379 %This is not possible in Ragel. One can only program
380 %a longest-match instantiation with a fixed set of rules. One can jump to
381 %another longest-match machine that employs the same machine definitions in the
382 %construction of its rules, however no states will be shared.
383
384 %In Ragel, input may be re-parsed using a
385 %different machine, but since the action to be executed is associated with
386 %transitions of the compiled state machine, the longest-match construction does
387 %not permit a single rule to be excluded from the active set. It cannot be done
388 %ahead of time nor in the excluded rule's action.
389 \end{comment}
390
391 The Re2C program defines an input processing model similar to that of Lex.
392 Re2C focuses on making generated state machines run very fast and
393 integrate easily into any program, free of dependencies.  Re2C generates
394 directly executable code and is able to claim that generated parsers run nearly
395 as fast as their hand-coded equivalents.  This is very important for user
396 adoption, as programmers are reluctant to use a tool when a faster alternative
397 exists.  A consideration to ease of use is also important because developers
398 need the freedom to integrate the generated code as they see fit. 
399
400 Many scripting languages provide ways of composing parsers by linking regular
401 expressions using program logic. For example, Sed and Awk are two established
402 Unix scripting tools that allow the programmer to exploit regular expressions
403 for the purpose of locating and extracting text of interest. High-level
404 programming languages such as Perl, Python, PHP and Ruby all provide regular
405 expression libraries that allow the user to combine regular expressions with
406 arbitrary code.
407
408 In addition to supporting the linking of regular expressions with arbitrary
409 program logic, the Perl programming language permits the embedding of code into
410 regular expressions. Perl embeddings do not translate into the embedding of
411 code into deterministic state machines. Perl regular expressions are in fact
412 not fully compiled to deterministic machines when embedded code is involved.
413 They are instead interpreted and involve backtracking. This is shown by the
414 following Perl program. When it is fed the input \verb|abcd| the interpretor
415 attempts to match the first alternative, printing \verb|a1 b1|.  When this
416 possibility fails it backtracks and tries the second possibility, printing
417 \verb|a2 b2|, at which point it succeeds.
418
419 \begin{inline_code}
420 \begin{verbatim}
421 print "YES\n" if ( <STDIN> =~
422         /( a (?{ print "a1 "; }) b (?{ print "b1 "; }) cX ) |
423          ( a (?{ print "a2 "; }) b (?{ print "b2 "; }) cd )/x )
424 \end{verbatim}
425 \end{inline_code}
426 \verbspace
427
428 In Ragel there is no regular expression interpretor. Aside from the scanner
429 operator, all Ragel expressions are made into deterministic machines and the
430 run time simply moves from state to state as it consumes input. An equivalent
431 parser expressed in Ragel would attempt both of the alternatives concurrently,
432 printing \verb|a1 a2 b1 b2|.
433
434 \section{Development Status}
435
436 Ragel is a relatively new tool and is under continuous development. As a rough
437 release guide, minor revision number changes are for implementation
438 improvements and feature additions. Major revision number changes are for
439 implementation and language changes that do not preserve backwards
440 compatibility. Though in the past this has not always held true: changes that
441 break code have crept into minor version number changes. Typically, the
442 documentation lags behind the development in the interest of documenting only
443 the lasting features. The latest changes are always documented in the ChangeLog
444 file. 
445
446 \chapter{Constructing State Machines}
447
448 \section{Ragel State Machine Specifications}
449
450 A Ragel input file consists of a host language code file with embedded machine
451 specifications.  Ragel normally passes input straight to output.  When it sees
452 a machine specification it stops to read the Ragel statements and possibly generate
453 code in place of the specification.
454 Afterwards it continues to pass input through.  There
455 can be any number of FSM specifications in an input file. A multi-line FSM spec
456 starts with \verb|%%{| and ends with \verb|}%%|. A single-line FSM spec starts
457 with \verb|%%| and ends at the first newline.  
458
459 While Ragel is looking for FSM specifications it does basic lexical analysis on
460 the surrounding input. It interprets literal strings and comments so a
461 \verb|%%| sequence in either of those will not trigger the parsing of an FSM
462 specification. Ragel does not pass the input through any preprocessor nor does it
463 interpret preprocessor directives itself so includes, defines and ifdef logic
464 cannot be used to alter the parse of a Ragel input file. It is therefore not
465 possible to use an \verb|#if 0| directive to comment out a machine as is
466 commonly done in C code. As an alternative, a machine can be prevented from
467 causing any generated output by commenting out the write statements.
468
469 In Figure \ref{cmd-line-parsing}, a multi-line machine is used to define the
470 machine and single line machines are used to trigger the writing of the machine
471 data and execution code.
472
473 \begin{figure}
474 \begin{multicols}{2}
475 \small
476 \begin{verbatim}
477 #include <string.h>
478 #include <stdio.h>
479
480 %%{ 
481     machine foo;
482     main := 
483         ( 'foo' | 'bar' ) 
484         0 @{ res = 1; };
485 }%%
486
487 %% write data;
488 \end{verbatim}
489 \columnbreak
490 \begin{verbatim}
491 int main( int argc, char **argv )
492 {
493     int cs, res = 0;
494     if ( argc > 1 ) {
495         char *p = argv[1];
496         char *pe = p + strlen(p) + 1;
497         %% write init;
498         %% write exec;
499     }
500     printf("result = %i\n", res );
501     return 0;
502 }
503 \end{verbatim}
504 \end{multicols}
505 \caption{Parsing a command line argument.}
506 \label{cmd-line-parsing}
507 \end{figure}
508
509 \subsection{Naming Ragel Blocks}
510
511 \begin{verbatim}
512 machine fsm_name;
513 \end{verbatim}
514 \verbspace
515
516 The \verb|machine| statement gives the name of the FSM. If present in a
517 specification, this statement must appear first. If a machine specification
518 does not have a name then Ragel uses the previous specification name.  If no
519 previous specification name exists then this is an error. Because FSM
520 specifications persist in memory, a machine's statements can be spread across
521 multiple machine specifications.  This allows one to break up a machine across
522 several files or draw in statements that are common to multiple machines using
523 the \verb|include| statement.
524
525 \subsection{Machine Definition}
526 \label{definition}
527
528 \begin{verbatim}
529 <name> = <expression>;
530 \end{verbatim}
531 \verbspace
532
533 The machine definition statement associates an FSM expression with a name.  Machine
534 expressions assigned to names can later be referenced by other expressions.  A
535 definition statement on its own does not cause any states to be generated. It is simply a
536 description of a machine to be used later. States are generated only when a definition is
537 instantiated, which happens when a definition is referenced in an instantiated
538 expression. 
539
540 \subsection{Machine Instantiation}
541 \label{instantiation}
542
543 \begin{verbatim}
544 <name> := <expression>;
545 \end{verbatim}
546 \verbspace
547
548 The machine instantiation statement generates a set of states representing an
549 expression. Each instantiation generates a distinct set of states.  The entry
550 point is written in the generated code using the instantiation name.  If the
551 \verb|main| machine is instantiated, its start state is used as the
552 specification's start state and is assigned to the \verb|cs| variable by the
553 \verb|write init| command. If no \verb|main| machine is given, the start state
554 of the last machine instantiation is used as the specification's start state.
555
556 From outside the execution loop, control may be passed to any machine by
557 assigning the entry point to the \verb|cs| variable.  From inside the execution
558 loop, control may be passed to any machine instantiation using \verb|fcall|,
559 \verb|fgoto| or \verb|fnext| statements.
560
561 \subsection{Including Ragel Code}
562
563 \begin{verbatim}
564 include FsmName "inputfile.rl";
565 \end{verbatim}
566 \verbspace
567
568 The \verb|include| statement can be used to draw in the statements of another FSM
569 specification. Both the name and input file are optional, however at least one
570 must be given. Without an FSM name, the given input file is searched for an FSM
571 of the same name as the current specification. Without an input file the
572 current file is searched for a machine of the given name. If both are present,
573 the given input file is searched for a machine of the given name.
574
575 \subsection{Importing Definitions}
576 \label{import}
577
578 \begin{verbatim}
579 import "inputfile.h";
580 \end{verbatim}
581 \verbspace
582
583 The \verb|import| statement takes a literal string as an argument, interprets
584 it as a file name, then scrapes the file for sequences of tokens that match the
585 following forms. If the input file is a Ragel program then tokens inside the
586 Ragel sections are ignored. See Section \ref{export} for a description of
587 exporting machine definitions.
588
589 \begin{itemize}
590         \setlength{\itemsep}{-2mm}
591     \item \verb|name = number|
592     \item \verb|name = lit_string|
593     \item \verb|"define" name number|
594     \item \verb|"define" name lit_string|
595 \end{itemize}
596
597
598 \section{Lexical Analysis of a Ragel Block}
599 \label{lexing}
600
601 Within a machine specification the following lexical rules apply to the parse
602 of the input.
603
604 \begin{itemize}
605
606 \item The \verb|#| symbol begins a comment that terminates at the next newline.
607
608 \item The symbols \verb|""|, \verb|''|, \verb|//|, \verb|[]| behave as the
609 delimiters of literal strings. With them, the following escape sequences are interpreted: 
610
611 \verb|    \0 \a \b \t \n \v \f \r|
612
613 A backslash at the end of a line joins the following line onto the current. A
614 backslash preceding any other character removes special meaning. This applies
615 to terminating characters and to special characters in regular expression
616 literals. As an exception, regular expression literals do not support escape
617 sequences as the operands of a range within a list. See the bullet on regular
618 expressions in Section \ref{basic}.
619
620 \item The symbols \verb|{}| delimit a block of host language code that will be
621 embedded into the machine as an action.  Within the block of host language
622 code, basic lexical analysis of C/C++ comments and strings is done in order to
623 correctly find the closing brace of the block. With the exception of FSM
624 commands embedded in code blocks, the entire block is preserved as is for
625 identical reproduction in the output code.
626
627 \item The pattern \verb|[+-]?[0-9]+| denotes an integer in decimal format.
628 Integers used for specifying machines may be negative only if the alphabet type
629 is signed. Integers used for specifying priorities may be positive or negative.
630
631 \item The pattern \verb|0x[0-9A-Fa-f]+| denotes an integer in hexadecimal
632 format.
633
634 \item The keywords are \verb|access|, \verb|action|, \verb|alphtype|,
635 \verb|getkey|, \verb|write|, \verb|machine| and \verb|include|.
636
637 \item The pattern \verb|[a-zA-Z_][a-zA-Z_0-9]*| denotes an identifier.
638
639 %\item The allowable symbols are:
640 %
641 %\verb/    ( ) ! ^ * ? + : -> - | & . , := = ; > @ $ % /\\
642 %\verb|    >/  $/  %/  </  @/  <>/ >!  $!  %!  <!  @!  <>!|\\
643 %\verb|    >^  $^  %^  <^  @^  <>^ >~  $~  %~  <~  @~  <>~|\\
644 %\verb|    >*  $*  %*  <*  @*  <>*|
645
646 \item Any amount of whitespace may separate tokens.
647
648 \end{itemize}
649
650 %\section{Parse of an FSM Specification}
651
652 %The following statements are possible within an FSM specification. The
653 %requirements for trailing semicolons loosely follow that of C. 
654 %A block
655 %specifying code does not require a trailing semicolon. An expression
656 %statement does require a trailing semicolon.
657
658
659 \section{Basic Machines}
660 \label{basic}
661
662 The basic machines are the base operands of regular language expressions. They
663 are the smallest unit to which machine construction and manipulation operators
664 can be applied.
665
666 In the diagrams that follow the symbol \verb|df| represents
667 the default transition, which is taken if no other transition can be taken. The
668 symbol \verb|cr| represents the carriage return character, \verb|nl| represents the newline character (aka line feed) and the symbol
669 \verb|sp| represents the space character.
670
671 \begin{itemize}
672
673 \item \verb|'hello'| -- Concatenation Literal. Produces a machine that matches
674 the sequence of characters in the quoted string. If there are 5 characters
675 there will be 6 states chained together with the characters in the string. See
676 Section \ref{lexing} for information on valid escape sequences. 
677
678 % GENERATE: bmconcat
679 % OPT: -p
680 % %%{
681 % machine bmconcat;
682 \begin{comment}
683 \begin{verbatim}
684 main := 'hello';
685 \end{verbatim}
686 \end{comment}
687 % }%%
688 % END GENERATE
689
690 \begin{center}
691 \includegraphics[scale=0.55]{bmconcat}
692 \end{center}
693
694 It is possible
695 to make a concatenation literal case-insensitive by appending an \verb|i| to
696 the string, for example \verb|'cmd'i|.
697
698 \item \verb|"hello"| -- Identical to the single quoted version.
699
700 \item \verb|[hello]| -- Or Expression. Produces a union of characters.  There
701 will be two states with a transition for each unique character between the two states.
702 The \verb|[]| delimiters behave like the quotes of a literal string. For example, 
703 \verb|[ \t]| means tab or space. The \verb|or| expression supports character ranges
704 with the \verb|-| symbol as a separator. The meaning of the union can be negated
705 using an initial \verb|^| character as in standard regular expressions. 
706 See Section \ref{lexing} for information on valid escape sequences
707 in \verb|or| expressions.
708
709 % GENERATE: bmor
710 % OPT: -p
711 % %%{
712 % machine bmor;
713 \begin{comment}
714 \begin{verbatim}
715 main := [hello];
716 \end{verbatim}
717 \end{comment}
718 % }%%
719 % END GENERATE
720
721 \begin{center}
722 \includegraphics[scale=0.55]{bmor}
723 \end{center}
724
725 \item \verb|''|, \verb|""|, and \verb|[]| -- Zero Length Machine.  Produces a machine
726 that matches the zero length string. Zero length machines have one state that is both
727 a start state and a final state.
728
729 % GENERATE: bmnull
730 % OPT: -p
731 % %%{
732 % machine bmnull;
733 \begin{comment}
734 \begin{verbatim}
735 main := '';
736 \end{verbatim}
737 \end{comment}
738 % }%%
739 % END GENERATE
740
741 \begin{center}
742 \includegraphics[scale=0.55]{bmnull}
743 \end{center}
744
745 % FIXME: More on the range of values here.
746 \item \verb|42| -- Numerical Literal. Produces a two state machine with one
747 transition on the given number. The number may be in decimal or hexadecimal
748 format and should be in the range allowed by the alphabet type. The minimum and
749 maximum values permitted are defined by the host machine that Ragel is compiled
750 on. For example, numbers in a \verb|short| alphabet on an i386 machine should
751 be in the range \verb|-32768| to \verb|32767|.
752
753 % GENERATE: bmnum
754 % %%{
755 % machine bmnum;
756 \begin{comment}
757 \begin{verbatim}
758 main := 42;
759 \end{verbatim}
760 \end{comment}
761 % }%%
762 % END GENERATE
763
764 \begin{center}
765 \includegraphics[scale=0.55]{bmnum}
766 \end{center}
767
768 \item \verb|/simple_regex/| -- Regular Expression. Regular expressions are
769 parsed as a series of expressions that will be concatenated together. Each
770 concatenated expression
771 may be a literal character, the any character specified by the \verb|.|
772 symbol, or a union of characters specified by the \verb|[]| delimiters. If the
773 first character of a union is \verb|^| then it matches any character not in the
774 list. Within a union, a range of characters can be given by separating the first
775 and last characters of the range with the \verb|-| symbol. Each
776 concatenated machine may have repetition specified by following it with the
777 \verb|*| symbol. The standard escape sequences described in Section
778 \ref{lexing} are supported everywhere in regular expressions except as the
779 operands of a range within in a list. This notation also supports the \verb|i|
780 trailing option. Use it to produce case-insensitive machines, as in \verb|/GET/i|.
781
782 Ragel does not support very complex regular expressions because the desired
783 results can always be achieved using the more general machine construction
784 operators listed in Section \ref{machconst}. The following diagram shows the
785 result of compiling \verb|/ab*[c-z].*[123]/|.
786
787 % GENERATE: bmregex
788 % OPT: -p
789 % %%{
790 % machine bmregex;
791 \begin{comment}
792 \begin{verbatim}
793 main := /ab*[c-z].*[123]/;
794 \end{verbatim}
795 \end{comment}
796 % }%%
797 % END GENERATE
798
799 \begin{center}
800 \includegraphics[scale=0.55]{bmregex}
801 \end{center}
802
803 \item \verb|'a' .. 'z'| -- Range. Produces a machine that matches any
804 characters in the specified range.  Allowable upper and lower bounds of the
805 range are concatenation literals of length one and numerical literals.  For
806 example, \verb|0x10..0x20|, \verb|0..63|, and \verb|'a'..'z'| are valid ranges.
807 The bounds should be in the range allowed by the alphabet type.
808
809 % GENERATE: bmrange
810 % OPT: -p
811 % %%{
812 % machine bmrange;
813 \begin{comment}
814 \begin{verbatim}
815 main := 'a' .. 'z';
816 \end{verbatim}
817 \end{comment}
818 % }%%
819 % END GENERATE
820
821 \begin{center}
822 \includegraphics[scale=0.55]{bmrange}
823 \end{center}
824
825
826 \item \verb|variable_name| -- Lookup the machine definition assigned to the
827 variable name given and use an instance of it. See Section \ref{definition} for
828 an important note on what it means to reference a variable name.
829
830 \item \verb|builtin_machine| -- There are several built-in machines available
831 for use. They are all two state machines for the purpose of matching common
832 classes of characters. They are:
833
834 \begin{itemize}
835
836 \item \verb|any   | -- Any character in the alphabet.
837
838 \item \verb|ascii | -- Ascii characters. \verb|0..127|
839
840 \item \verb|extend| -- Ascii extended characters. This is the range
841 \verb|-128..127| for signed alphabets and the range \verb|0..255| for unsigned
842 alphabets.
843
844 \item \verb|alpha | -- Alphabetic characters. \verb|[A-Za-z]|
845
846 \item \verb|digit | -- Digits. \verb|[0-9]|
847
848 \item \verb|alnum | -- Alpha numerics. \verb|[0-9A-Za-z]|
849
850 \item \verb|lower | -- Lowercase characters. \verb|[a-z]|
851
852 \item \verb|upper | -- Uppercase characters. \verb|[A-Z]|
853
854 \item \verb|xdigit| -- Hexadecimal digits. \verb|[0-9A-Fa-f]|
855
856 \item \verb|cntrl | -- Control characters. \verb|0..31|
857
858 \item \verb|graph | -- Graphical characters. \verb|[!-~]|
859
860 \item \verb|print | -- Printable characters. \verb|[ -~]|
861
862 \item \verb|punct | -- Punctuation. Graphical characters that are not alphanumerics.
863 \verb|[!-/:-@[-`{-~]|
864
865 \item \verb|space | -- Whitespace. \verb|[\t\v\f\n\r ]|
866
867 \item \verb|zlen  | -- Zero length string. \verb|""|
868
869 \item \verb|empty | -- Empty set. Matches nothing. \verb|^any|
870
871 \end{itemize}
872 \end{itemize}
873
874 \section{Operator Precedence}
875 The following table shows operator precedence from lowest to highest. Operators
876 in the same precedence group are evaluated from left to right.
877
878 \verbspace
879 \begin{tabular}{|c|c|c|}
880 \hline
881 1&\verb| , |&Join\\
882 \hline
883 2&\verb/ | & - --/&Union, Intersection and Subtraction\\
884 \hline
885 3&\verb| . <: :> :>> |&Concatenation\\
886 \hline
887 4&\verb| : |&Label\\
888 \hline
889 5&\verb| -> |&Epsilon Transition\\
890 \hline
891 &\verb| >  @  $  % |&Transitions Actions and Priorities\\
892 \cline{2-3}
893 &\verb| >/  $/  %/  </  @/  <>/ |&EOF Actions\\
894 \cline{2-3}
895 6&\verb| >!  $!  %!  <!  @!  <>! |&Global Error Actions\\
896 \cline{2-3}
897 &\verb| >^  $^  %^  <^  @^  <>^ |&Local Error Actions\\
898 \cline{2-3}
899 &\verb| >~  $~  %~  <~  @~  <>~ |&To-State Actions\\
900 \cline{2-3}
901 &\verb| >*  $*  %*  <*  @*  <>* |&From-State Action\\
902 \hline
903 7&\verb| * ** ? + {n} {,n} {n,} {n,m} |&Repetition\\
904 \hline
905 8&\verb| ! ^ |&Negation and Character-Level Negation\\
906 \hline
907 9&\verb| ( <expr> ) |&Grouping\\
908 \hline
909 \end{tabular}
910
911 \section{Regular Language Operators}
912 \label{machconst}
913
914 When using Ragel it is helpful to have a sense of how it constructs machines.
915 The determinization process can produce results that seem unusual to someone
916 not familiar with the NFA to DFA conversion algorithm. In this section we
917 describe Ragel's state machine operators. Though the operators are defined
918 using epsilon transitions, it should be noted that this is for discussion only.
919 The epsilon transitions described in this section do not persist, but are
920 immediately removed by the determinization process which is executed in every
921 operation. Ragel does not make use of any nondeterministic intermediate state
922 machines. 
923
924 To create an epsilon transition between two states \verb|x| and \verb|y| is to
925 copy all of the properties of \verb|y| into \verb|x|. This involves drawing in
926 all of \verb|y|'s to-state actions, EOF actions, etc., in addition to its
927 transitions. If \verb|x| and \verb|y| both have a transition out on the same
928 character, then the transitions must be combined.  During transition
929 combination a new transition is made that goes to a new state that is the
930 combination of both target states. The new combination state is created using
931 the same epsilon transition method.  The new state has an epsilon transition
932 drawn to all the states that compose it. Since every time an epsilon transition
933 is drawn the creation of new epsilon transitions may be triggered, the process
934 of drawing epsilon transitions is repeated until there are no more epsilon
935 transitions to be made.
936
937 A very common error that is made when using Ragel is to make machines that do
938 too much at once. That is, to create machines that have unintentional
939 nondeterminism. This usually results from being unaware of the common strings
940 between machines that are combined together using the regular language
941 operators. This can involve never leaving a machine, causing its actions to be
942 propagated through all the following states. Or it can involve an alternation
943 where both branches are unintentionally taken simultaneously.
944
945 This problem forces one to think hard about the language that needs to be
946 matched. To guard against this kind of problem one must ensure that the machine
947 specification is divided up using boundaries that do not allow ambiguities from
948 one portion of the machine to the next. See Chapter
949 \ref{controlling-nondeterminism} for more on this problem and how to solve it.
950
951 The Graphviz tool is an immense help when debugging improperly compiled
952 machines or otherwise learning how to use Ragel. In many cases, practical
953 parsing programs will be too large to completely visualize with Graphviz.  The
954 proper approach is to reduce the language to the smallest subset possible that
955 still exhibits the characteristics that one wishes to learn about or to fix.
956 This can be done without modifying the source code using the \verb|-M| and
957 \verb|-S| options at the frontend. If a machine cannot be easily reduced,
958 embeddings of unique actions can be very useful for tracing a
959 particular component of a larger machine specification, since action names are
960 written out on transition labels.
961
962 \subsection{Union}
963
964 \verb/expr | expr/
965 \verbspace
966
967 The union operation produces a machine that matches any string in machine one
968 or machine two. The operation first creates a new start state. Epsilon
969 transitions are drawn from the new start state to the start states of both
970 input machines.  The resulting machine has a final state set equivalent to the
971 union of the final state sets of both input machines. In this operation, there
972 is the opportunity for nondeterminism among both branches. If there are
973 strings, or prefixes of strings that are matched by both machines then the new
974 machine will follow both parts of the alternation at once. The union operation is
975 shown below.
976
977 \graphspace
978 \begin{center}
979 \includegraphics{opor}
980 \end{center}
981 \graphspace
982
983 The following example demonstrates the union of three machines representing
984 common tokens.
985
986 % GENERATE: exor
987 % OPT: -p
988 % %%{
989 % machine exor;
990 \begin{inline_code}
991 \begin{verbatim}
992 # Hex digits, decimal digits, or identifiers
993 main := '0x' xdigit+ | digit+ | alpha alnum*;
994 \end{verbatim}
995 \end{inline_code}
996 % }%%
997 % END GENERATE
998
999 \graphspace
1000 \begin{center}
1001 \includegraphics[scale=0.55]{exor}
1002 \end{center}
1003
1004 \subsection{Intersection}
1005
1006 \verb|expr & expr|
1007 \verbspace
1008
1009 Intersection produces a machine that matches any
1010 string that is in both machine one and machine two. To achieve intersection, a
1011 union is performed on the two machines. After the result has been made
1012 deterministic, any final state that is not a combination of final states from
1013 both machines has its final state status revoked. To complete the operation,
1014 paths that do not lead to a final state are pruned from the machine. Therefore,
1015 if there are any such paths in either of the expressions they will be removed
1016 by the intersection operator.  Intersection can be used to require that two
1017 independent patterns be simultaneously satisfied as in the following example.
1018
1019 % GENERATE: exinter
1020 % OPT: -p
1021 % %%{
1022 % machine exinter;
1023 \begin{inline_code}
1024 \begin{verbatim}
1025 # Match lines four characters wide that contain 
1026 # words separated by whitespace.
1027 main :=
1028     /[^\n][^\n][^\n][^\n]\n/* &
1029     (/[a-z][a-z]*/ | [ \n])**;
1030 \end{verbatim}
1031 \end{inline_code}
1032 % }%%
1033 % END GENERATE
1034
1035 \graphspace
1036 \begin{center}
1037 \includegraphics[scale=0.55]{exinter}
1038 \end{center}
1039
1040 \subsection{Difference}
1041
1042 \verb|expr - expr|
1043 \verbspace
1044
1045 The difference operation produces a machine that matches
1046 strings that are in machine one but are not in machine two. To achieve subtraction,
1047 a union is performed on the two machines. After the result has been made
1048 deterministic, any final state that came from machine two or is a combination
1049 of states involving a final state from machine two has its final state status
1050 revoked. As with intersection, the operation is completed by pruning any path
1051 that does not lead to a final state.  The following example demonstrates the
1052 use of subtraction to exclude specific cases from a set.
1053
1054 \verbspace
1055
1056 % GENERATE: exsubtr
1057 % OPT: -p
1058 % %%{
1059 % machine exsubtr;
1060 \begin{inline_code}
1061 \begin{verbatim}
1062 # Subtract keywords from identifiers.
1063 main := /[a-z][a-z]*/ - ( 'for' | 'int' );
1064 \end{verbatim}
1065 \end{inline_code}
1066 % }%%
1067 % END GENERATE
1068
1069 \graphspace
1070 \begin{center}
1071 \includegraphics[scale=0.55]{exsubtr}
1072 \end{center}
1073 \graphspace
1074
1075
1076 \subsection{Strong Difference}
1077 \label{strong_difference}
1078
1079 \verb|expr -- expr|
1080 \verbspace
1081
1082 Strong difference produces a machine that matches any string of the first
1083 machine that does not have any string of the second machine as a substring. In
1084 the following example, strong subtraction is used to excluded \verb|CRLF| from
1085 a sequence. In the corresponding visualization, the label \verb|DEF| is short
1086 for default. The default transition is taken if no other transition can be
1087 taken.
1088
1089 % GENERATE: exstrongsubtr
1090 % OPT: -p
1091 % %%{
1092 % machine exstrongsubtr;
1093 \begin{inline_code}
1094 \begin{verbatim}
1095 crlf = '\r\n';
1096 main := [a-z]+ ':' ( any* -- crlf ) crlf;
1097 \end{verbatim}
1098 \end{inline_code}
1099 % }%%
1100 % END GENERATE
1101
1102 \graphspace
1103 \begin{center}
1104 \includegraphics[scale=0.55]{exstrongsubtr}
1105 \end{center}
1106 \graphspace
1107
1108 This operator is equivalent to the following.
1109
1110 \verbspace
1111 \begin{verbatim}
1112 expr - ( any* expr any* )
1113 \end{verbatim}
1114
1115 \subsection{Concatenation}
1116
1117 \verb|expr . expr|
1118 \verbspace
1119
1120 Concatenation produces a machine that matches all the strings in machine one followed by all
1121 the strings in machine two.  Concatenation draws epsilon transitions from the
1122 final states of the first machine to the start state of the second machine. The
1123 final states of the first machine lose their final state status, unless the
1124 start state of the second machine is final as well. 
1125 Concatenation is the default operator. Two machines next to each other with no
1126 operator between them results in the machines being concatenated together.  
1127
1128 \graphspace
1129 \begin{center}
1130 \includegraphics{opconcat}
1131 \end{center}
1132 \graphspace
1133
1134 The opportunity for nondeterministic behaviour results from the possibility of
1135 the final states of the first machine accepting a string that is also accepted
1136 by the start state of the second machine.
1137 The most common scenario that this happens in is the
1138 concatenation of a machine that repeats some pattern with a machine that gives
1139 a termination string, but the repetition machine does not exclude the
1140 termination string. The example in Section \ref{strong_difference}
1141 guards against this. Another example is the expression \verb|("'" any* "'")|.
1142 When executed the thread of control will
1143 never leave the \verb|any*| machine.  This is a problem especially if actions
1144 are embedded to process the characters of the \verb|any*| component.
1145
1146 In the following example, the first machine is always active due to the
1147 nondeterministic nature of concatenation. This particular nondeterminism is intended
1148 however because we wish to permit EOF strings before the end of the input.
1149
1150 % GENERATE: exconcat
1151 % OPT: -p
1152 % %%{
1153 % machine exconcat;
1154 \begin{inline_code}
1155 \begin{verbatim}
1156 # Require an eof marker on the last line.
1157 main := /[^\n]*\n/* . 'EOF\n';
1158 \end{verbatim}
1159 \end{inline_code}
1160 % }%%
1161 % END GENERATE
1162
1163 \graphspace
1164 \begin{center}
1165 \includegraphics[scale=0.55]{exconcat}
1166 \end{center}
1167 \graphspace
1168
1169 \noindent {\bf Note:} There is a language
1170 ambiguity involving concatenation and subtraction. Because concatenation is the 
1171 default operator for two
1172 adjacent machines there is an ambiguity between subtraction of
1173 a positive numerical literal and concatenation of a negative numerical literal.
1174 For example, \verb|(x-7)| could be interpreted as \verb|(x . -7)| or 
1175 \verb|(x - 7)|. In the Ragel language, the subtraction operator always takes precedence
1176 over concatenation of a negative literal. Precedence was given to the
1177 subtraction-based interpretation so as to adhere to the rule that the default
1178 concatenation operator takes effect only when there are no other operators between
1179 two machines. Beware of writing machines such as \verb|(any -1)| when what is
1180 desired is a concatenation of \verb|any| and -1. Instead write 
1181 \verb|(any .  -1)| or \verb|(any (-1))|. If in doubt of the meaning of your program do not
1182 rely on the default concatenation operator; always use the \verb|.| symbol.
1183
1184
1185 \subsection{Kleene Star}
1186
1187 \verb|expr*|
1188 \verbspace
1189
1190 The machine resulting from the Kleene Star operator will match zero or more
1191 repetitions of the machine it is applied to.
1192 It creates a new start state and an additional final
1193 state.  Epsilon transitions are drawn between the new start state and the old start
1194 state, between the new start state and the new final state, and
1195 between the final states of the machine and the new start state.  After the
1196 machine is made deterministic the effect is of the final states getting all the
1197 transitions of the start state. 
1198
1199 \graphspace
1200 \begin{center}
1201 \includegraphics{opstar}
1202 \end{center}
1203 \graphspace
1204
1205 The possibility for nondeterministic behaviour arises if the final states have
1206 transitions on any of the same characters as the start state.  This is common
1207 when applying kleene star to an alternation of tokens. Like the other problems
1208 arising from nondeterministic behavior, this is discussed in more detail in Chapter
1209 \ref{controlling-nondeterminism}. This particular problem can also be solved
1210 by using the longest-match construction discussed in Section 
1211 \ref{generating-scanners} on scanners.
1212
1213 In this simple
1214 example, there is no nondeterminism introduced by the exterior kleene star due to
1215 the newline at the end of the regular expression. Without the newline the
1216 exterior kleene star would be redundant and there would be ambiguity between
1217 repeating the inner range of the regular expression and the entire regular
1218 expression. Though it would not cause a problem in this case, unnecessary
1219 nondeterminism in the kleene star operator often causes undesired results for
1220 new Ragel users and must be guarded against.
1221
1222 % GENERATE: exstar
1223 % OPT: -p
1224 % %%{
1225 % machine exstar;
1226 \begin{inline_code}
1227 \begin{verbatim}
1228 # Match any number of lines with only lowercase letters.
1229 main := /[a-z]*\n/*;
1230 \end{verbatim}
1231 \end{inline_code}
1232 % }%%
1233 % END GENERATE
1234
1235 \graphspace
1236 \begin{center}
1237 \includegraphics[scale=0.55]{exstar}
1238 \end{center}
1239 \graphspace
1240
1241 \subsection{One Or More Repetition}
1242
1243 \verb|expr+|
1244 \verbspace
1245
1246 This operator produces the concatenation of the machine with the kleene star of
1247 itself. The result will match one or more repetitions of the machine. The plus
1248 operator is equivalent to \verb|(expr . expr*)|.  The plus operator makes
1249 repetitions that cannot be zero length.
1250
1251 % GENERATE: explus
1252 % OPT: -p
1253 % %%{
1254 % machine explus;
1255 \begin{inline_code}
1256 \begin{verbatim}
1257 # Match alpha-numeric words.
1258 main := alnum+;
1259 \end{verbatim}
1260 \end{inline_code}
1261 % }%%
1262 % END GENERATE
1263
1264 \graphspace
1265 \begin{center}
1266 \includegraphics[scale=0.55]{explus}
1267 \end{center}
1268 \graphspace
1269
1270 \subsection{Optional}
1271
1272 \verb|expr?|
1273 \verbspace
1274
1275 The {\em optional} operator produces a machine that accepts the machine
1276 given or the zero length string. The optional operator is equivalent to
1277 \verb/(expr | '' )/. In the following example the optional operator is used to
1278 extend a token.
1279
1280 % GENERATE: exoption
1281 % OPT: -p
1282 % %%{
1283 % machine exoption;
1284 \begin{inline_code}
1285 \begin{verbatim}
1286 # Match integers or floats.
1287 main := digit+ ('.' digit+)?;
1288 \end{verbatim}
1289 \end{inline_code}
1290 % }%%
1291 % END GENERATE
1292
1293 \graphspace
1294 \begin{center}
1295 \includegraphics[scale=0.55]{exoption}
1296 \end{center}
1297 \graphspace
1298
1299
1300 \subsection{Repetition}
1301
1302 \begin{tabbing}
1303 \noindent \verb|expr {n}| \hspace{16pt}\=-- Exactly N copies of expr.\\
1304
1305 \noindent \verb|expr {,n}| \>-- Zero to N copies of expr.\\
1306
1307 \noindent \verb|expr {n,}| \>-- N or more copies of expr.\\
1308
1309 \noindent \verb|expr {n,m}| \>-- N to M copies of expr.
1310 \end{tabbing}
1311
1312 \subsection{Negation}
1313
1314 \verb|!expr|
1315 \verbspace
1316
1317 Negation produces a machine that matches any string not matched by the given
1318 machine. Negation is equivalent to \verb|(any* - expr)|.
1319
1320 % GENERATE: exnegate
1321 % OPT: -p
1322 % %%{
1323 % machine exnegate;
1324 \begin{inline_code}
1325 \begin{verbatim}
1326 # Accept anything but a string beginning with a digit.
1327 main := ! ( digit any* );
1328 \end{verbatim}
1329 \end{inline_code}
1330 % }%%
1331 % END GENERATE
1332
1333 \graphspace
1334 \begin{center}
1335 \includegraphics[scale=0.55]{exnegate}
1336 \end{center}
1337 \graphspace
1338
1339
1340 \subsection{Character-Level Negation}
1341
1342 \verb|^expr|
1343 \verbspace
1344
1345 Character-level negation produces a machine that matches any single character
1346 not matched by the given machine. Character-Level Negation is equivalent to
1347 \verb|(any - expr)|.
1348
1349 \section{State Machine Minimization}
1350
1351 State machine minimization is the process of finding the minimal equivalent FSM accepting
1352 the language. Minimization reduces the number of states in machines
1353 by merging equivalent states. It does not change the behaviour of the machine
1354 in any way. It will cause some states to be merged into one because they are
1355 functionally equivalent. State minimization is on by default. It can be turned
1356 off with the \verb|-n| option.
1357
1358 The algorithm implemented is similar to Hopcroft's state minimization
1359 algorithm. Hopcroft's algorithm assumes a finite alphabet that can be listed in
1360 memory, whereas Ragel supports arbitrary integer alphabets that cannot be
1361 listed in memory. Though exact analysis is very difficult, Ragel minimization
1362 runs close to $O(n \times log(n))$ and requires $O(n)$ temporary storage where
1363 $n$ is the number of states.
1364
1365 \section{Visualization}
1366
1367 Ragel is able to emit compiled state machines in Graphviz's Dot file format.
1368 Graphviz support allows users to perform
1369 incremental visualization of their parsers. User actions are displayed on
1370 transition labels of the graph. If the final graph is too large to be
1371 meaningful, or even drawn, the user is able to inspect portions of the parser
1372 by naming particular regular expression definitions with the \verb|-S| and
1373 \verb|-M| options to the \verb|ragel| program. Use of Graphviz greatly
1374 improves the Ragel programming experience. It allows users to learn Ragel by
1375 experimentation and also to track down bugs caused by unintended
1376 nondeterminism.
1377
1378 \chapter{User Actions}
1379
1380 Ragel permits the user to embed actions into the transitions of a regular
1381 expression's corresponding state machine. These actions are executed when the
1382 generated code moves over a transition.  Like the regular expression operators,
1383 the action embedding operators are fully compositional. They take a state
1384 machine and an action as input, embed the action, and yield a new state machine
1385 that can be used in the construction of other machines. Due to the
1386 compositional nature of embeddings, the user has complete freedom in the
1387 placement of actions.
1388
1389 A machine's transitions are categorized into four classes, The action embedding
1390 operators access the transitions defined by these classes.  The {\em starting
1391 transition} operator \verb|>| isolates the start state, then embeds an action
1392 into all transitions leaving it. The {\em finishing transition} operator
1393 \verb|@| embeds an action into all transitions going into a final state.  The
1394 {\em all transition} operator \verb|$| embeds an action into all transitions of
1395 an expression. The {\em pending out transition} operator \verb|%| provides
1396 access to yet-unmade leaving transitions. 
1397
1398 \section{Embedding Actions}
1399
1400 \begin{verbatim}
1401 action ActionName {
1402     /* Code an action here. */
1403     count += 1;
1404 }
1405 \end{verbatim}
1406 \verbspace
1407
1408 The action statement defines a block of code that can be embedded into an FSM.
1409 Action names can be referenced by the action embedding operators in
1410 expressions. Though actions need not be named in this way (literal blocks
1411 of code can be embedded directly when building machines), defining reusable
1412 blocks of code whenever possible is good practice because it potentially increases the
1413 degree to which the machine can be minimized. Within an action some Ragel expressions
1414 and statements are parsed and translated. These allow the user to interact with the machine
1415 from action code. See Section \ref{vals} for a complete list of statements and
1416 values available in code blocks. 
1417
1418 \subsection{Starting Action}
1419
1420 \verb|expr > action| 
1421 \verbspace
1422
1423 The starting transition operator embeds an action into all transitions that
1424 leave the start state. In some machines the start state has in transtions from
1425 within the machine and the start state is effectively reused. In these cases
1426 the start state is first isolated from the rest of the machine and the starting
1427 actions do not get re-executed.
1428
1429 If the start state is a final state then it is possible for the machine to
1430 never be started and the starting transitions by-passed.  In the following
1431 example, the action is executed on the first transition of the machine. If the
1432 repetition machine is bypassed the action is not executed.
1433
1434 \verbspace
1435
1436 % GENERATE: exstact
1437 % OPT: -p
1438 % %%{
1439 % machine exstact;
1440 \begin{inline_code}
1441 \begin{verbatim}
1442 # Execute A at the beginning of a string of alpha.
1443 action A {}
1444 main := ( lower* >A ) . ' ';
1445 \end{verbatim}
1446 \end{inline_code}
1447 % }%%
1448 % END GENERATE
1449
1450 \graphspace
1451 \begin{center}
1452 \includegraphics[scale=0.55]{exstact}
1453 \end{center}
1454 \graphspace
1455
1456 \subsection{Finishing Action}
1457
1458 \verb|expr @ action|
1459 \verbspace
1460
1461 The finishing action operator embeds an action into any transitions that go into a
1462 final state. Whether or not the machine accepts is not determined at the point
1463 the action is executed. Further input may move the machine out of the accepting
1464 state, but keep it in the machine. As in the following example, the
1465 into-final-state operator is most often used when no lookahead is necessary.
1466
1467 % GENERATE: exdoneact
1468 % OPT: -p
1469 % %%{
1470 % machine exdoneact;
1471 % action A {}
1472 \begin{inline_code}
1473 \begin{verbatim}
1474 # Execute A when the trailing space is seen.
1475 main := ( lower* ' ' ) @A;
1476 \end{verbatim}
1477 \end{inline_code}
1478 % }%%
1479 % END GENERATE
1480
1481 \graphspace
1482 \begin{center}
1483 \includegraphics[scale=0.55]{exdoneact}
1484 \end{center}
1485 \graphspace
1486
1487
1488 \subsection{All Transition Action}
1489
1490 \verb|expr $ action|
1491 \verbspace
1492
1493 The all transition operator embeds an action into all transitions of a machine.
1494 The action is executed whenever a transition of the machine is taken. In the
1495 following example, A is executed on every character matched.
1496
1497 % GENERATE: exallact
1498 % OPT: -p
1499 % %%{
1500 % machine exallact;
1501 % action A {}
1502 \begin{inline_code}
1503 \begin{verbatim}
1504 # Execute A on any characters of machine one or two.
1505 main := ( 'm1' | 'm2' ) $A;
1506 \end{verbatim}
1507 \end{inline_code}
1508 % }%%
1509 % END GENERATE
1510
1511 \graphspace
1512 \begin{center}
1513 \includegraphics[scale=0.55]{exallact}
1514 \end{center}
1515 \graphspace
1516
1517
1518 \subsection{Pending Out (Leaving) Actions}
1519 \label{out-actions}
1520
1521 \verb|expr % action|
1522 \verbspace
1523
1524 The pending out action operator embeds an action into the pending out
1525 transitions of a machine. The action is first embedded into the final states of
1526 the machine and later transferred to any transitions made going out of the
1527 machine. The transfer can be caused either by a concatenation or kleene star
1528 operation.  This mechanism allows one to associate an action with the
1529 termination of a sequence, without being concerned about what particular
1530 character terminates the sequence.  In the following example, A is executed
1531 when leaving the alpha machine by the newline character.
1532
1533 % GENERATE: exoutact1
1534 % OPT: -p
1535 % %%{
1536 % machine exoutact1;
1537 % action A {}
1538 \begin{inline_code}
1539 \begin{verbatim}
1540 # Match a word followed by a newline. Execute A when 
1541 # finishing the word.
1542 main := ( lower+ %A ) . '\n';
1543 \end{verbatim}
1544 \end{inline_code}
1545 % }%%
1546 % END GENERATE
1547
1548 \graphspace
1549 \begin{center}
1550 \includegraphics[scale=0.55]{exoutact1}
1551 \end{center}
1552 \graphspace
1553
1554 In the following example, the \verb|term_word| action could be used to register
1555 the appearance of a word and to clear the buffer that the \verb|lower| action used
1556 to store the text of it.
1557
1558 % GENERATE: exoutact2
1559 % OPT: -p
1560 % %%{
1561 % machine exoutact2;
1562 % action lower {}
1563 % action space {}
1564 % action term_word {}
1565 % action newline {}
1566 \begin{inline_code}
1567 \begin{verbatim}
1568 word = ( [a-z] @lower )+ %term_word;
1569 main := word ( ' ' @space word )* '\n' @newline;
1570 \end{verbatim}
1571 \end{inline_code}
1572 % }%%
1573 % END GENERATE
1574
1575 \graphspace
1576 \begin{center}
1577 \includegraphics[scale=0.55]{exoutact2}
1578 \end{center}
1579 \graphspace
1580
1581
1582 In this final example of the action embedding operators, A is executed upon the
1583 first character of the alpha machine, B is executed on all transitions of the
1584 alpha machine, C is executed when the alpha machine is exited by moving into the
1585 newline machine and N is executed when the newline machine moves into a final
1586 state.  
1587
1588 % GENERATE: exaction
1589 % OPT: -p
1590 % %%{
1591 % machine exaction;
1592 % action A {}
1593 % action B {}
1594 % action C {}
1595 % action N {}
1596 \begin{inline_code}
1597 \begin{verbatim}
1598 # Execute A on starting the alpha machine, B on every transition 
1599 # moving through it and C upon finishing. Execute N on the newline.
1600 main := ( lower* >A $B %C ) . '\n' @N;
1601 \end{verbatim}
1602 \end{inline_code}
1603 % }%%
1604 % END GENERATE
1605
1606 \graphspace
1607 \begin{center}
1608 \includegraphics[scale=0.55]{exaction}
1609 \end{center}
1610 \graphspace
1611
1612
1613 \section{State Action Embedding Operators}
1614
1615 The state embedding operators allow one to embed actions into states. Like the
1616 transition embedding operators, there are several different classes of states
1617 that the operators access. The meanings of the symbols are similar to the
1618 meanings of the symbols used by the transition embedding operators. The design
1619 of the state selections was driven by a need to cover the states of an
1620 expression with a single error action.
1621
1622 Unlike the transition embedding operators, the state embedding operators are
1623 also distinguished by the different kinds of events that embedded actions can
1624 be associated with. Therefore the state embedding operators have two
1625 components.  The first, which is the first one or two characters, specifies the
1626 class of states that the action will be embedded into. The second component
1627 specifies the type of event the action will be executed on. The symbols of the
1628 second component also have equivalent kewords. 
1629
1630 \def\fakeitem{\hspace*{12pt}$\bullet$\hspace*{10pt}}
1631
1632 \begin{minipage}{\textwidth}
1633 \begin{multicols}{2}
1634 \raggedcolumns
1635 \noindent The different classes of states are:\\
1636 \fakeitem \verb|> | -- the start state \\
1637 \fakeitem \verb|$ | -- all states\\
1638 \fakeitem \verb|% | -- final states\\
1639 \fakeitem \verb|< | -- any state except the start state\\
1640 \fakeitem \verb|@ | -- any state except final states\\
1641 \fakeitem \verb|<>| -- any except start and final (middle)
1642
1643 \columnbreak
1644
1645 \noindent The different kinds of embeddings are:\\
1646 \fakeitem \verb|~| -- to-state actions (\verb|to|)\\
1647 \fakeitem \verb|*| -- from-state actions (\verb|from|)\\
1648 \fakeitem \verb|/| -- EOF actions (\verb|eof|)\\
1649 \fakeitem \verb|!| -- error actions (\verb|err|)\\
1650 \fakeitem \verb|^| -- local error actions (\verb|lerr|)\\
1651 \end{multicols}
1652 \end{minipage}
1653 %\label{state-act-embed}
1654 %\caption{The two components of state embedding operators. The class of states
1655 %to select comes first, followed by the type of embedding.}
1656 %
1657 %\begin{figure}[t]
1658 %\centering
1659 %\includegraphics{stembed}
1660 %\caption{Summary of state manipulation operators}
1661 %\label{state-act-embed-chart}
1662 %\end{figure}
1663
1664 %\noindent Putting these two components together we get a matrix of state
1665 %embedding operators. The entire set is given in Figure \ref{state-act-embed-chart}.
1666
1667
1668 \subsection{To-State and From-State Actions}
1669
1670 \subsubsection{To-State Actions}
1671
1672 \noindent\verb|>~action     <~action     $~action    %~action      @~action      <>~action|\\
1673 \\
1674 \noindent Verbose forms:\\
1675 \noindent\verb|>to(act)     <to(act)     $to(na)     %to(name)     @to(name)     <>to(name)|\\
1676 \noindent\verb|>to{...}     <to{...}     $to{...}    %to{...}      @to{...}      <>to{...}|
1677 \\
1678
1679
1680 To-state actions are executed whenever the state machine moves into the
1681 specified state, either by a natural movement over a transition or by an
1682 action-based transfer of control such as \verb|fgoto|. They are executed after the
1683 in-transition's actions but before the current character is advanced and
1684 tested against the end of the input block. To-state embeddings stay with the
1685 state. They are irrespective of the state's current set of transitions and any
1686 future transitions that may be added in or out of the state.
1687
1688 Note that the setting of the current state variable \verb|cs| outside of the
1689 execute code is not considered by Ragel as moving into a state and consequently
1690 the to-state actions of the new current state are not executed. This includes
1691 the initialization of the current state when the machine begins.  This is
1692 because the entry point into the machine execution code is after the execution
1693 of to-state actions.
1694
1695 \subsubsection{From-State Actions}
1696
1697 \noindent\verb|>*action     <*action     $*action    %*action      @*action      <>*action|\\
1698 \\
1699 \noindent Verbose forms:\\
1700 \noindent\verb|>from(act)   <from(act)   $from(na)   %from(name)   @from(name)   <>from(name)|\\
1701 \noindent\verb|>from{...}   <from{...}   $from{...}  %from{...}    @from{...}    <>from{...}|
1702 \\
1703
1704 From-state actions are executed whenever the state machine takes a transition from a
1705 state, either to itself or to some other state. These actions are executed
1706 immediately after the current character is tested against the input block end
1707 marker and before the transition to take is sought based on the current
1708 character. From-state actions are therefore executed even if a transition
1709 cannot be found and the machine moves into the error state.  Like to-state
1710 embeddings, from-state embeddings stay with the state.
1711
1712 \subsection{EOF Actions}
1713
1714 \noindent\verb|>/action     </action     $/action    %/action      @/action      <>/action|\\
1715 \\
1716 \noindent Verbose forms:\\
1717 \noindent\verb|>eof(act)    <eof(act)    $eof(na)    %eof(name)    @eof(name)    <>eof(name)|\\
1718 \noindent\verb|>eof{...}    <eof{...}    $eof{...}   %eof{...}     @eof{...}     <>eof{...}|
1719 \\
1720
1721
1722 The EOF action embedding operators enable the user to embed EOF actions into
1723 different classes of
1724 states.  EOF actions are stored in states and generated with the \verb|write eof|
1725 statement. The generated EOF code switches on the current state and executes the EOF
1726 actions associated with it.
1727
1728 \subsection{Handling Errors}
1729
1730 In many applications it is useful to be able to react to parsing errors.  The
1731 user may wish to print an error message that depends on the context.  It
1732 may also be desirable to consume input in an attempt to return the input stream
1733 to some known state and resume parsing. To support error handling and recovery,
1734 Ragel provides error action embedding operators. There are two kinds of error
1735 actions, regular (global) error actions and local error actions.
1736 Error actions can be used to simply report errors, or by jumping to a machine
1737 instantiation that consumes input, can attempt to recover from errors.  
1738
1739 \subsubsection{Global Error Actions}
1740
1741 \noindent\verb|>!action     <!action     $!action    %!action      @!action      <>!action|\\
1742 \\
1743 \noindent Verbose forms:\\
1744 \noindent\verb|>err(act)    <err(act)    $err(na)    %err(name)    @err(name)    <>err(name)|\\
1745 \noindent\verb|>err{...}    <err{...}    $err{...}   %err{...}     @err{...}     <>err{...}|
1746 \\
1747
1748 Error actions are stored in states until the final state machine has been fully
1749 constructed. They are then transferred to the transitions that move into the
1750 error state. This transfer entails the creation of a transition from the state
1751 to the error state that is taken on all input characters that are not already
1752 covered by the state's transitions. In other words it provides a default
1753 action. Error actions can induce a recovery by altering \verb|p| and then jumping back
1754 into the machine with \verb|fgoto|.
1755
1756 \subsubsection{Local Error Actions}
1757
1758 \noindent\verb|>^action     <^action     $^action    %^action      @^action      <>^action|\\
1759 \\
1760 \noindent Verbose forms:\\
1761 \noindent\verb|>lerr(act)   <lerr(act)   $lerr(na)   %lerr(name)   @lerr(name)   <>lerr(name)|\\
1762 \noindent\verb|>lerr{...}   <lerr{...}   $lerr{...}  %lerr{...}    @lerr{...}    <>lerr{...}|
1763 \\
1764
1765 Like global error actions, local error actions are also stored in states until
1766 a transfer point. The transfer point is different however. Each local error action
1767 embedding is associated with a name. When a machine definition has been fully
1768 constructed, all local error action embeddings associated the same name as the
1769 machine are transferred to error transitions. Local error actions can be used
1770 to specify an action to take when a particular section of a larger state
1771 machine fails to make a match. A particular machine definition's ``thread'' may
1772 die and the local error actions executed, however the machine as a whole may
1773 continue to match input.
1774
1775 There are two forms of local error action embeddings. In the first form the name defaults
1776 to the current machine. In the second form the machine name can be specified.  This
1777 is useful when it is more convenient to specify the local error action in a
1778 sub-definition that is used to construct the machine definition where the
1779 transfer should happen. To embed local error actions and explicitly state the
1780 machine on which the transfer is to happen use \verb|(name, action)| as the
1781 action.
1782
1783 \begin{comment}
1784 \begin{itemize}
1785 \setlength{\parskip}{0in}
1786 \item \verb|expr >^ (name, action) | -- Start state.
1787 \item \verb|expr $^ (name, action) | -- All states.
1788 \item \verb|expr %^ (name, action) | -- Final states.
1789 \item \verb|expr <^ (name, action) | -- Not start state.
1790 \item \verb|expr <>^ (name, action)| -- Not start and not final states.
1791 \end{itemize}
1792 \end{comment}
1793
1794 \subsubsection{Example}
1795
1796 The following example uses error actions to report an error and jump to a
1797 machine that consumes the remainder of the line when parsing fails. After
1798 consuming the line, the error recovery machine returns to the main loop.
1799
1800 % GENERATE: erract
1801 % %%{
1802 %       machine erract;
1803 %       ws = ' ';
1804 %       address = 'foo@bar.com';
1805 %       date = 'Monday May 12';
1806 \begin{inline_code}
1807 \begin{verbatim}
1808 action cmd_err { 
1809     printf( "command error\n" ); 
1810     fhold; fgoto line;
1811 }
1812 action from_err { 
1813     printf( "from error\n" ); 
1814     fhold; fgoto line; 
1815 }
1816 action to_err { 
1817     printf( "to error\n" ); 
1818     fhold; fgoto line;
1819 }
1820
1821 line := [^\n]* '\n' @{ fgoto main; };
1822
1823 main := (
1824     (
1825         'from' @err(cmd_err) 
1826             ( ws+ address ws+ date '\n' ) $err(from_err) |
1827         'to' @err(cmd_err)
1828             ( ws+ address '\n' ) $err(to_err)
1829     ) 
1830 )*;
1831 \end{verbatim}
1832 \end{inline_code}
1833 % }%%
1834 % %% write data;
1835 % void f()
1836 % {
1837 %       %% write init;
1838 %       %% write exec;
1839 % }
1840 % END GENERATE
1841
1842
1843
1844 \section{Action Ordering and Duplicates}
1845
1846 When building a parser by combining smaller expressions that themselves have
1847 embedded actions, it is often the case that transitions that need to
1848 execute a number of actions on one input character are made. For example when we leave
1849 an expression, we may execute the expression's pending out action and the
1850 subsequent expression's starting action on the same input character.  We must
1851 therefore devise a method for ordering actions that is both intuitive and
1852 predictable for the user and repeatable by the state machine compiler. The
1853 determinization processes cannot simply order actions by the time at which they
1854 are introduced into a transition -- otherwise the programmer will be at the
1855 mercy of luck.
1856
1857 We associate with the embedding of each action a distinct timestamp that is
1858 used to order actions that appear together on a single transition in the final
1859 compiled state machine. To accomplish this we traverse the parse tree of
1860 regular expressions and assign timestamps to action embeddings. This algorithm
1861 is recursive in nature and quite simple. When it visits a parse tree node it
1862 assigns timestamps to all {\em starting} action embeddings, recurses on the
1863 parse tree, then assigns timestamps to the remaining {\em all}, {\em
1864 finishing}, and {\em leaving} embeddings in the order in which they appear.
1865
1866 Ragel does not permit actions (defined or unnamed) to appear multiple times in
1867 an action list.  When the final machine has been created, actions that appear
1868 more than once in a single transition or EOF action list have their duplicates
1869 removed. The first appearance of the action is preserved. This is useful in a
1870 number of scenarios.  First, it allows us to union machines with common
1871 prefixes without worrying about the action embeddings in the prefix being
1872 duplicated.  Second, it prevents pending out actions from being transferred multiple times
1873 when a concatenation follows a kleene star and the two machines begin with a common
1874 character.
1875
1876 \verbspace
1877 \begin{verbatim}
1878 word = [a-z]+ %act;
1879 main := word ( '\n' word )* '\n\n';
1880 \end{verbatim}
1881
1882 \section{Values and Statements Available in Code Blocks}
1883 \label{vals}
1884
1885 \noindent The following values are available in code blocks:
1886
1887 \begin{itemize}
1888 \item \verb|fpc| -- A pointer to the current character. This is equivalent to
1889 accessing the \verb|p| variable.
1890
1891 \item \verb|fc| -- The current character. This is equivalent to the expression \verb|(*p)|.
1892
1893 \item \verb|fcurs| -- An integer value representing the current state. This
1894 value should only be read from. To move to a different place in the machine
1895 from action code use the \verb|fgoto|, \verb|fnext| or \verb|fcall| statements.
1896 Outside of the machine execution code the \verb|cs| variable may be modified.
1897
1898 \item \verb|ftargs| -- An integer value representing the target state. This
1899 value should only be read from. Again, \verb|fgoto|, \verb|fnext| and
1900 \verb|fcall| can be used to move to a specific entry point.
1901
1902 \item \verb|fentry(<label>)| -- Retrieve an integer value representing the
1903 entry point \verb|label|. The integer value returned will be a compile time
1904 constant. This number is suitable for later use in control flow transfer
1905 statements that take an expression. This value should not be compared against
1906 the current state because any given label can have multiple states representing
1907 it. The value returned by \verb|fentry| will be one of the possibly multiple states the
1908 label represents.
1909 \end{itemize}
1910
1911 \noindent The following statements are available in code blocks:
1912
1913 \begin{itemize}
1914
1915 \item \verb|fhold;| -- Do not advance over the current character. If processing
1916 data in multiple buffer blocks, the \verb|fhold| statement should only be used
1917 once in the set of actions executed on a character.  Multiple calls may result
1918 in backing up over the beginning of the buffer block. The \verb|fhold|
1919 statement does not imply any transfer of control. It is equivalent to the
1920 \verb|p--;| statement. 
1921
1922 \item \verb|fexec <expr>;| -- Set the next character to process. This can be
1923 used to backtrack to previous input or advance ahead.
1924 Unlike \verb|fhold|, which can be used
1925 anywhere, \verb|fexec| requires the user to ensure that the target of the
1926 backtrack is in the current buffer block or is known to be somewhere ahead of
1927 it. The machine will continue iterating forward until \verb|pe| is arrived at,
1928 \verb|fbreak| is called or the machine moves into the error state. In actions
1929 embedded into transitions, the \verb|fexec| statement is equivalent to setting
1930 \verb|p| to one position ahead of the next character to process.  If the user
1931 also modifies \verb|pe|, it is possible to change the buffer block entirely.
1932
1933 \item \verb|fgoto <label>;| -- Jump to an entry point defined by
1934 \verb|<label>|.  The \verb|fgoto| statement immediately transfers control to
1935 the destination state.
1936
1937 \item \verb|fgoto *<expr>;| -- Jump to an entry point given by \verb|<expr>|.
1938 The expression must evaluate to an integer value representing a state.
1939
1940 \item \verb|fnext <label>;| -- Set the next state to be the entry point defined
1941 by \verb|label|.  The \verb|fnext| statement does not immediately jump to the
1942 specified state. Any action code following the statement is executed.
1943
1944 \item \verb|fnext *<expr>;| -- Set the next state to be the entry point given
1945 by \verb|<expr>|. The expression must evaluate to an integer value representing
1946 a state.
1947
1948 \item \verb|fcall <label>;| -- Push the target state and jump to the entry
1949 point defined by \verb|<label>|.  The next \verb|fret| will jump to the target
1950 of the transition on which the call was made. Use of \verb|fcall| requires
1951 the declaration of a call stack. An array of integers named \verb|stack| and a
1952 single integer named \verb|top| must be declared. With the \verb|fcall|
1953 construct, control is immediately transferred to the destination state.
1954
1955 \item \verb|fcall *<expr>;| -- Push the current state and jump to the entry
1956 point given by \verb|<expr>|. The expression must evaluate to an integer value
1957 representing a state.
1958
1959 \item \verb|fret;| -- Return to the target state of the transition on which the
1960 last \verb|fcall| was made.  Use of \verb|fret| requires the declaration of a
1961 call stack with \verb|fstack| in the struct block.  Control is immediately
1962 transferred to the destination state.
1963
1964 \item \verb|fbreak;| -- Save the current state and immediately break out of the
1965 execute loop. This statement is useful in conjunction with the \verb|noend|
1966 write option. Rather than process input until the end marker of the input
1967 buffer is arrived at, the fbreak statement can be used to stop processing input
1968 upon seeing some end-of-string marker.  It can also be used for handling
1969 exceptional circumstances.  The fbreak statement does not change the pointer to
1970 the current character. After an \verb|fbreak| call the \verb|p| variable will point to
1971 the character that was being traversed over when the action was
1972 executed. The current state will be the target of the current transition.
1973
1974 \end{itemize}
1975
1976 \noindent {\bf Note:} Once actions with control-flow commands are embedded into a
1977 machine, the user must exercise caution when using the machine as the operand
1978 to other machine construction operators. If an action jumps to another state
1979 then unioning any transition that executes that action with another transition
1980 that follows some other path will cause that other path to be lost. Using
1981 commands that manually jump around a machine takes us out of the domain of
1982 regular languages because transitions that may be conditional and that the
1983 machine construction operators are not aware of are introduced.  These
1984 commands should therefore be used with caution.
1985
1986
1987 \chapter{Controlling Nondeterminism}
1988 \label{controlling-nondeterminism}
1989
1990 Along with the flexibility of arbitrary action embeddings comes a need to
1991 control nondeterminism in regular expressions. If a regular expression is
1992 ambiguous, then sub-components of a parser other than the intended parts may become
1993 active. This means that actions that are irrelevant to the
1994 current subset of the parser may be executed, causing problems for the
1995 programmer.
1996
1997 Tools that are based on regular expression engines and used for
1998 recognition tasks will usually function as intended regardless of the presence
1999 of ambiguities. It is quite common for users of scripting languages to write
2000 regular expressions that are heavily ambiguous and it generally does not
2001 matter. As long as one of the potential matches is recognized, there can be any
2002 number of other matches present.  In some parsing systems the run-time engine
2003 can employ a strategy for resolving ambiguities, for example always pursuing
2004 the longest possible match and discarding others.
2005
2006 In Ragel, there is no regular expression run-time engine, just a simple state
2007 machine execution model. When we begin to embed actions and face the
2008 possibility of spurious action execution, it becomes clear that controlling
2009 nondeterminism at the machine construction level is very important. Consider
2010 the following example.
2011
2012 % GENERATE: lines1
2013 % OPT: -p
2014 % %%{
2015 % machine lines1;
2016 % action first {}
2017 % action tail {}
2018 % word = [a-z]+;
2019 \begin{inline_code}
2020 \begin{verbatim}
2021 ws = [\n\t ];
2022 line = word $first ( ws word $tail )* '\n';
2023 lines = line*;
2024 \end{verbatim}
2025 \end{inline_code}
2026 % main := lines;
2027 % }%%
2028 % END GENERATE
2029
2030 \begin{center}
2031 \includegraphics[scale=0.53]{lines1}
2032 \end{center}
2033 \graphspace
2034
2035 Since the \verb|ws| expression includes the newline character, we will
2036 not finish the \verb|line| expression when a newline character is seen. We will
2037 simultaneously pursue the possibility of matching further words on the same
2038 line and the possibility of matching a second line. Evidence of this fact is 
2039 in the state tables. On several transitions both the \verb|first| and
2040 \verb|tail| actions are executed.  The solution here is simple: exclude
2041 the newline character from the \verb|ws| expression. 
2042
2043 % GENERATE: lines2
2044 % OPT: -p
2045 % %%{
2046 % machine lines2;
2047 % action first {}
2048 % action tail {}
2049 % word = [a-z]+;
2050 \begin{inline_code}
2051 \begin{verbatim}
2052 ws = [\t ];
2053 line = word $first ( ws word $tail )* '\n';
2054 lines = line*;
2055 \end{verbatim}
2056 \end{inline_code}
2057 % main := lines;
2058 % }%%
2059 % END GENERATE
2060
2061 \begin{center}
2062 \includegraphics[scale=0.55]{lines2}
2063 \end{center}
2064 \graphspace
2065
2066 Solving this kind of problem is straightforward when the ambiguity is created
2067 by strings that are a single character long.  When the ambiguity is created by
2068 strings that are multiple characters long we have a more difficult problem.
2069 The following example is an incorrect attempt at a regular expression for C
2070 language comments. 
2071
2072 % GENERATE: comments1
2073 % OPT: -p
2074 % %%{
2075 % machine comments1;
2076 % action comm {}
2077 \begin{inline_code}
2078 \begin{verbatim}
2079 comment = '/*' ( any @comm )* '*/';
2080 main := comment ' ';
2081 \end{verbatim}
2082 \end{inline_code}
2083 % }%%
2084 % END GENERATE
2085
2086 \begin{center}
2087 \includegraphics[scale=0.55]{comments1}
2088 \end{center}
2089 \graphspace
2090
2091 Using standard concatenation, we will never leave the \verb|any*| expression.
2092 We will forever entertain the possibility that a \verb|'*/'| string that we see
2093 is contained in a longer comment and that, simultaneously, the comment has
2094 ended.  The concatenation of the \verb|comment| machine with \verb|SP| is done
2095 to show this. When we match space, we are also still matching the comment body.
2096
2097 One way to approach the problem is to exclude the terminating string
2098 from the \verb|any*| expression using set difference. We must be careful to
2099 exclude not just the terminating string, but any string that contains it as a
2100 substring. A verbose, but proper specification of a C comment parser is given
2101 by the following regular expression. 
2102
2103 % GENERATE: comments2
2104 % OPT: -p
2105 % %%{
2106 % machine comments2;
2107 % action comm {}
2108 \begin{inline_code}
2109 \begin{verbatim}
2110 comment = '/*' ( ( any @comm )* - ( any* '*/' any* ) ) '*/';
2111 \end{verbatim}
2112 \end{inline_code}
2113 % main := comment;
2114 % }%%
2115 % END GENERATE
2116
2117 \graphspace
2118 \begin{center}
2119 \includegraphics[scale=0.55]{comments2}
2120 \end{center}
2121 \graphspace
2122
2123 Note that Ragel's strong subtraction operator \verb|--| can also be used here.
2124 In doing this subtraction we have phrased the problem of controlling non-determinism in
2125 terms of excluding strings common to two expressions that interact when
2126 combined.
2127 We can also phrase the problem in terms of the transitions of the state
2128 machines that implement these expressions. During the concatenation of
2129 \verb|any*| and \verb|'*/'| we will be making transitions that are composed of
2130 both the loop of the first expression and the final character of the second.
2131 At this time we want the transition on the \verb|'/'| character to take precedence
2132 over and disallow the transition that originated in the \verb|any*| loop.
2133
2134 In another parsing problem, we wish to implement a lightweight tokenizer that we can
2135 utilize in the composition of a larger machine. For example, some HTTP headers
2136 have a token stream as a sub-language. The following example is an attempt
2137 at a regular expression-based tokenizer that does not function correctly due to
2138 unintended nondeterminism.
2139
2140 \newpage
2141
2142 % GENERATE: smallscanner
2143 % OPT: -p
2144 % %%{
2145 % machine smallscanner;
2146 % action start_str {}
2147 % action on_char {}
2148 % action finish_str {}
2149 \begin{inline_code}
2150 \begin{verbatim}
2151 header_contents = ( 
2152     lower+ >start_str $on_char %finish_str | 
2153     ' '
2154 )*;
2155 \end{verbatim}
2156 \end{inline_code}
2157 % main := header_contents;
2158 % }%%
2159 % END GENERATE
2160
2161 \begin{center}
2162 \includegraphics[scale=0.55]{smallscanner}
2163 \end{center}
2164 \graphspace
2165
2166 In this case, the problem with using a standard kleene star operation is that
2167 there is an ambiguity between extending a token and wrapping around the machine
2168 to begin a new token. Using the standard operator, we get an undesirable
2169 nondeterministic behaviour. Evidence of this can be seen on the transition out
2170 of state one to itself.  The transition extends the string, and simultaneously,
2171 finishes the string only to immediately begin a new one.  What is required is
2172 for the
2173 transitions that represent an extension of a token to take precedence over the
2174 transitions that represent the beginning of a new token. For this problem
2175 there is no simple solution that uses standard regular expression operators.
2176
2177 \section{Priorities}
2178
2179 A priority mechanism was devised and built into the determinization
2180 process, specifically for the purpose of allowing the user to control
2181 nondeterminism.  Priorities are integer values embedded into transitions. When
2182 the determinization process is combining transitions that have different
2183 priorities, the transition with the higher priority is preserved and the
2184 transition with the lower priority is dropped.
2185
2186 Unfortunately, priorities can have unintended side effects because their
2187 operation requires that they linger in transitions indefinitely. They must linger
2188 because the Ragel program cannot know when the user is finished with a priority
2189 embedding.  A solution whereby they are explicitly deleted after use is
2190 conceivable; however this is not very user-friendly.  Priorities were therefore
2191 made into named entities. Only priorities with the same name are allowed to
2192 interact.  This allows any number of priorities to coexist in one machine for
2193 the purpose of controlling various different regular expression operations and
2194 eliminates the need to ever delete them. Such a scheme allows the user to
2195 choose a unique name, embed two different priority values using that name
2196 and be confident that the priority embedding will be free of any side effects.
2197
2198 In the first form of priority embedding the name defaults to the name of the machine
2199 definition that the priority is assigned in. In this sense priorities are by
2200 default local to the current machine definition or instantiation. Beware of
2201 using this form in a longest-match machine, since there is only one name for
2202 the entire set of longest match patterns. In the second form the priority's
2203 name can be specified, allowing priority interaction across machine definition
2204 boundaries.
2205
2206 \begin{itemize}
2207 \setlength{\parskip}{0in}
2208 \item \verb|expr > int| -- Sets starting transitions to have priority int.
2209 \item \verb|expr @ int| -- Sets transitions that go into a final state to have priority int. 
2210 \item \verb|expr $ int| -- Sets all transitions to have priority int.
2211 \item \verb|expr % int| -- Sets pending out transitions from final states to
2212 have priority int.\\ When a transition is made going out of the machine (either
2213 by concatenation or kleene star) its priority is immediately set to the pending
2214 out priority.  
2215 \end{itemize}
2216
2217 The second form of priority assignment allows the programmer to specify the name
2218 to which the priority is assigned.
2219
2220 \begin{itemize}
2221 \setlength{\parskip}{0in}
2222 \item \verb|expr > (name, int)| -- Starting transitions.
2223 \item \verb|expr @ (name, int)| -- Finishing transitions (into a final state).
2224 \item \verb|expr $ (name, int)| -- All transitions.
2225 \item \verb|expr % (name, int)| -- Pending out transitions.
2226 \end{itemize}
2227
2228 \section{Guarded Operators that Encapsulate Priorities}
2229
2230 Priority embeddings are a very expressive mechanism. At the same time they
2231 can be very confusing for the user. They force the user to imagine
2232 the transitions inside two interacting expressions and work out the precise
2233 effects of the operations between them. When we consider
2234 that this problem is worsened by the
2235 potential for side effects caused by unintended priority name collisions, we
2236 see that exposing the user to priorities is rather undesirable.
2237
2238 Fortunately, in practice the use of priorities has been necessary only in a
2239 small number of scenarios.  This allows us to encapsulate their functionality
2240 into a small set of operators and fully hide them from the user. This is
2241 advantageous from a language design point of view because it greatly simplifies
2242 the design.  
2243
2244 Going back to the C comment example, we can now properly specify
2245 it using a guarded concatenation operator which we call {\em finish-guarded
2246 concatenation}. From the user's point of view, this operator terminates the
2247 first machine when the second machine moves into a final state.  It chooses a
2248 unique name and uses it to embed a low priority into all
2249 transitions of the first machine. A higher priority is then embedded into the
2250 transitions of the second machine that enter into a final state. The following
2251 example yields a machine identical to the example in Section 
2252 \ref{controlling-nondeterminism}.
2253
2254 \begin{inline_code}
2255 \begin{verbatim}
2256 comment = '/*' ( any @comm )* :>> '*/';
2257 \end{verbatim}
2258 \end{inline_code}
2259
2260 \graphspace
2261 \begin{center}
2262 \includegraphics[scale=0.55]{comments2}
2263 \end{center}
2264 \graphspace
2265
2266 Another guarded operator is {\em left-guarded concatenation}, given by the
2267 \verb|<:| compound symbol. This operator places a higher priority on all
2268 transitions of the first machine. This is useful if one must forcibly separate
2269 two lists that contain common elements. For example, one may need to tokenize a
2270 stream, but first consume leading whitespace.
2271
2272 Ragel also includes a {\em longest-match kleene star} operator, given by the
2273 \verb|**| compound symbol. This 
2274 guarded operator embeds a high
2275 priority into all transitions of the machine. 
2276 A lower priority is then embedded into pending out transitions
2277 (in a manner similar to pending out action embeddings, described in Section
2278 \ref{out-actions}).  When the kleene star operator makes the epsilon transitions from
2279 the final states into the start state, the lower priority will be transferred
2280 to the epsilon transitions. In cases where following an epsilon transition
2281 out of a final state conflicts with an existing transition out of a final
2282 state, the epsilon transition will be dropped.
2283
2284 Other guarded operators are conceivable, such as guards on union that cause one
2285 alternative to take precedence over another. These may be implemented when it
2286 is clear they constitute a frequently used operation.
2287 In the next section we discuss the explicit specification of state machines
2288 using state charts.
2289
2290 \subsection{Entry-Guarded Concatenation}
2291
2292 \verb|expr :> expr| 
2293 \verbspace
2294
2295 This operator concatenates two machines, but first assigns a low
2296 priority to all transitions
2297 of the first machine and a high priority to the starting transitions of the
2298 second machine. This operator is useful if from the final states of the first
2299 machine, it is possible to accept the characters in the start transitions of
2300 the second machine. This operator effectively terminates the first machine
2301 immediately upon starting the second machine, where otherwise they would be
2302 pursued concurrently. In the following example, entry-guarded concatenation is
2303 used to move out of a machine that matches everything at the first sign of an
2304 end-of-input marker.
2305
2306 % GENERATE: entryguard
2307 % OPT: -p
2308 % %%{
2309 % machine entryguard;
2310 \begin{inline_code}
2311 \begin{verbatim}
2312 # Leave the catch-all machine on the first character of FIN.
2313 main := any* :> 'FIN';
2314 \end{verbatim}
2315 \end{inline_code}
2316 % }%%
2317 % END GENERATE
2318
2319 \begin{center}
2320 \includegraphics[scale=0.55]{entryguard}
2321 \end{center}
2322 \graphspace
2323
2324 Entry-guarded concatenation is equivalent to the following:
2325
2326 \verbspace
2327 \begin{verbatim}
2328 expr $(unique_name,0) . expr >(unique_name,1)
2329 \end{verbatim}
2330
2331 \subsection{Finish-Guarded Concatenation}
2332
2333 \verb|expr :>> expr|
2334 \verbspace
2335
2336 This operator is
2337 like the previous operator, except the higher priority is placed on the final
2338 transitions of the second machine. This is useful if one wishes to entertain
2339 the possibility of continuing to match the first machine right up until the
2340 second machine enters a final state. In other words it terminates the first
2341 machine only when the second accepts. In the following example, finish-guarded
2342 concatenation causes the move out of the machine that matches everything to be
2343 delayed until the full end-of-input marker has been matched.
2344
2345 % GENERATE: finguard
2346 % OPT: -p
2347 % %%{
2348 % machine finguard;
2349 \begin{inline_code}
2350 \begin{verbatim}
2351 # Leave the catch-all machine on the last character of FIN.
2352 main := any* :>> 'FIN';
2353 \end{verbatim}
2354 \end{inline_code}
2355 % }%%
2356 % END GENERATE
2357
2358 \begin{center}
2359 \includegraphics[scale=0.55]{finguard}
2360 \end{center}
2361 \graphspace
2362
2363 Finish-guarded concatenation is equivalent to the following:
2364
2365 \verbspace
2366 \begin{verbatim}
2367 expr $(unique_name,0) . expr @(unique_name,1)
2368 \end{verbatim}
2369
2370 \subsection{Left-Guarded Concatenation}
2371
2372 \verb|expr <: expr| 
2373 \verbspace
2374
2375 This operator places
2376 a higher priority on the left expression. It is useful if you want to prefix a
2377 sequence with another sequence composed of some of the same characters. For
2378 example, one can consume leading whitespace before tokenizing a sequence of
2379 whitespace-separated words as in:
2380
2381 % GENERATE: leftguard
2382 % OPT: -p
2383 % %%{
2384 % machine leftguard;
2385 % action alpha {}
2386 % action ws {}
2387 % action start {}
2388 % action fin {}
2389 \begin{inline_code}
2390 \begin{verbatim}
2391 main := ( ' '* >start %fin ) <: ( ' ' $ws | [a-z] $alpha )*;
2392 \end{verbatim}
2393 \end{inline_code}
2394 % }%%
2395 % END GENERATE
2396
2397 \graphspace
2398 \begin{center}
2399 \includegraphics[scale=0.55]{leftguard}
2400 \end{center}
2401 \graphspace
2402
2403 Left-guarded concatenation is equivalent to the following:
2404
2405 \verbspace
2406 \begin{verbatim}
2407 expr $(unique_name,1) . expr >(unique_name,0)
2408 \end{verbatim}
2409 \verbspace
2410
2411 \subsection{Longest-Match Kleene Star}
2412 \label{longest_match_kleene_star}
2413
2414 \verb|expr**| 
2415 \verbspace
2416
2417 This version of kleene star puts a higher priority on staying in the
2418 machine versus wrapping around and starting over. The LM kleene star is useful
2419 when writing simple tokenizers.  These machines are built by applying the
2420 longest-match kleene star to an alternation of token patterns, as in the
2421 following.
2422
2423 \verbspace
2424
2425 % GENERATE: lmkleene
2426 % OPT: -p
2427 % %%{
2428 % machine exfinpri;
2429 % action A {}
2430 % action B {}
2431 \begin{inline_code}
2432 \begin{verbatim}
2433 # Repeat tokens, but make sure to get the longest match.
2434 main := (
2435     lower ( lower | digit )* %A | 
2436     digit+ %B | 
2437     ' '
2438 )**;
2439 \end{verbatim}
2440 \end{inline_code}
2441 % }%%
2442 % END GENERATE
2443
2444 \begin{center}
2445 \includegraphics[scale=0.55]{lmkleene}
2446 \end{center}
2447 \graphspace
2448
2449 If a regular kleene star were used the machine above would not be able to
2450 distinguish between extending a word and beginning a new one.  This operator is
2451 equivalent to:
2452
2453 \verbspace
2454 \begin{verbatim}
2455 ( expr $(unique_name,1) %(unique_name,0) )*
2456 \end{verbatim}
2457 \verbspace
2458
2459 When the kleene star is applied, transitions that go out of the machine and
2460 back into it are made. These are assigned a priority of zero by the pending out
2461 transition mechanism. This is less than the priority of one assigned to the
2462 transitions leaving the final states but not leaving the machine. When two of
2463 these transitions clash on the same character, the differing priorities cause
2464 the transition that stays in the machine to take precedence.  The transition
2465 that wraps around is dropped.
2466
2467 Note that this operator does not build a scanner in the traditional sense
2468 because there is never any backtracking. To build a scanner in the traditional
2469 sense use the Longest-Match machine construction described in Section
2470 \ref{generating-scanners}.
2471
2472 \chapter{Interface to Host Program}
2473
2474 The Ragel code generator is very flexible. The generated code has no
2475 dependencies and can be inserted in any function, perhaps inside a loop if so
2476 desired.  The user is responsible for declaring and initializing a number of
2477 required variables, including the current state and the pointer to the input
2478 stream. These can live in any scope. Control of the input processing loop is
2479 also possible: the user may break out of the processing loop and return to it
2480 at any time.
2481
2482 In the case of C and D host languages, Ragel is able to generate very
2483 fast-running code that implements state machines as directly executable code.
2484 Since very large files strain the host language compiler, table-based code
2485 generation is also supported. In the future we hope to provide a partitioned,
2486 directly executable format that is able to reduce the burden on the host
2487 compiler by splitting large machines across multiple functions.
2488
2489 In the case of Java and Ruby, table-based code generation is the only code
2490 style supported. In the future this may be expanded to include other code
2491 styles.
2492
2493 Ragel can be used to parse input in one block, or it can be used to parse input
2494 in a sequence of blocks as it arrives from a file or socket.  Parsing the input
2495 in a sequence of blocks brings with it a few responsibilities. If the parser
2496 utilizes a scanner, care must be taken to not break the input stream anywhere
2497 but token boundaries.  If pointers to the input stream are taken during
2498 parsing, care must be taken to not use a pointer that has been invalidated by
2499 movement to a subsequent block.  If the current input data pointer is moved
2500 backwards it must not be moved past the beginning of the current block.
2501
2502 Figure \ref{basic-example} shows a simple Ragel program that does not have any
2503 actions. The example tests the first argument of the program against a number
2504 pattern and then prints the machine's acceptance status.
2505
2506 \begin{figure}
2507 \small
2508 \begin{verbatim}
2509 #include <stdio.h>
2510 #include <string.h>
2511 %%{
2512     machine foo;
2513     write data;
2514 }%%
2515 int main( int argc, char **argv )
2516 {
2517     int cs;
2518     if ( argc > 1 ) {
2519         char *p = argv[1];
2520         char *pe = p + strlen( p );
2521         %%{ 
2522             main := [0-9]+ ( '.' [0-9]+ )?;
2523
2524             write init;
2525             write exec;
2526             write eof;
2527         }%%
2528     }
2529     printf("result = %i\n", cs >= foo_first_final );
2530     return 0;
2531 }
2532 \end{verbatim}
2533 \caption{A basic Ragel example without any actions.}
2534 \label{basic-example}
2535 \end{figure}
2536
2537 \section{Variables Used by Ragel}
2538
2539 There are a number of variables which Ragel expects the user to declare. At a
2540 very minimum the \verb|cs|, \verb|p| and \verb|pe| variables must be declared.
2541 In Java and Ruby code the \verb|data| variable must also be declared. If
2542 stack-based state machine control flow statements are used then the
2543 \verb|stack| and \verb|top| variables are required. If a scanner is declared
2544 then the \verb|act|, \verb|tokstart| and \verb|tokend| variables must be
2545 declared.
2546
2547 \begin{itemize}
2548
2549 \item \verb|cs| - Current state. This must be an integer and it should persist
2550 across invocations of the machine when the data is broken into blocks that are
2551 processed independently.
2552
2553 \item \verb|p| - Data pointer. In C/D code this variable is expected to be a
2554 pointer to the character data to process. It should be initialized to the
2555 beginning of the data block on every run of the machine. In Java and Ruby it is
2556 used as an offset to \verb|data| and must be an integer. In this case it should
2557 be initialized to zero on every run of the machine.
2558
2559 \item \verb|pe| - Data end pointer. This should be initialized to \verb|p| plus
2560 the data length on every run of the machine. In Java and Ruby code this should
2561 be initialized to the data length.
2562
2563 \item \verb|data| - This variable is only required in Java and Ruby code. It
2564 must be an array containting the data to process.
2565
2566 \item \verb|stack| - This must be an array of integers. It is used to store
2567 integer values representing states.
2568
2569 \item \verb|top| - This must be an integer value and will be used as an offset
2570 to \verb|stack|, giving the next available spot on the top of the stack.
2571
2572 \item \verb|act| - This must be an integer value. It is a variable sometimes
2573 used by scanner code to keep track of the most recent successful pattern match.
2574
2575 \item \verb|tokstart| - This must be a pointer to character data. In Java and
2576 Ruby code this must be an integer. See Section \ref{generating-scanners} for
2577 more information.
2578
2579 \item \verb|tokend| - Also a pointer to character data.
2580
2581 \end{itemize}
2582
2583 \section{Alphtype Statement}
2584
2585 \begin{verbatim}
2586 alphtype unsigned int;
2587 \end{verbatim}
2588 \verbspace
2589
2590 The alphtype statement specifies the alphabet data type that the machine
2591 operates on. During the compilation of the machine, integer literals are expected to
2592 be in the range of possible values of the alphtype.  Supported alphabet types
2593 are \verb|char|, \verb|unsigned char|, \verb|short|, \verb|unsigned short|,
2594 \verb|int|, \verb|unsigned int|, \verb|long|, and \verb|unsigned long|. 
2595 The default is \verb|char|.
2596
2597 \section{Getkey Statement}
2598
2599 \begin{verbatim}
2600 getkey fpc->id;
2601 \end{verbatim}
2602 \verbspace
2603
2604 Specify to Ragel how to retrieve the character that the machine operates on
2605 from the pointer to the current element (\verb|p|). Any expression that returns
2606 a value of the alphabet type
2607 may be used. The getkey statement may be used for looking into element
2608 structures or for translating the character to process. The getkey expression
2609 defaults to \verb|(*p)|. In goto-driven machines the getkey expression may be
2610 evaluated more than once per element processed, therefore it should not incur a
2611 large cost nor preclude optimization.
2612
2613 \section{Access Statement}
2614
2615 \begin{verbatim}
2616 access fsm->;
2617 \end{verbatim}
2618 \verbspace
2619
2620 The access statement allows one to tell Ragel how the generated code should
2621 access the machine data that is persistent across processing buffer blocks.
2622 This includes all variables except \verb|p| and \verb|pe|. This includes
2623 \verb|cs|, \verb|top|, \verb|stack|, \verb|tokstart|, \verb|tokend| and \verb|act|.
2624 This is useful if a machine is to be encapsulated inside a
2625 structure in C code. The access statement can be used to give the name of
2626 a pointer to the structure.
2627
2628 \section{Variable Statement}
2629
2630 \begin{verbatim}
2631 variable p fsm->p;
2632 \end{verbatim}
2633 \verbspace
2634
2635 The variable statement allows one to tell ragel how to access a specific
2636 variable. All of the variables that are declared by the user and
2637 used by Ragel can be changed. This includes \verb|p|, \verb|pe|, \verb|cs|,
2638 \verb|top|, \verb|stack|, \verb|tokstart|, \verb|tokend| and \verb|act|.
2639 In Ruby and Java code generation the \verb|data| variable can also be changed.
2640
2641 \section{Write Statement}
2642 \label{write-statement}
2643
2644 \begin{verbatim}
2645 write <component> [options];
2646 \end{verbatim}
2647 \verbspace
2648
2649
2650 The write statement is used to generate parts of the machine. 
2651 There are four
2652 components that can be generated by a write statement. These components are the
2653 state machine's data, initialization code, execution code and EOF action
2654 execution code. A write statement may appear before a machine is fully defined.
2655 This allows one to write out the data first then later define the machine where
2656 it is used. An example of this is shown in Figure \ref{fbreak-example}.
2657
2658 \subsection{Write Data}
2659 \begin{verbatim}
2660 write data [options];
2661 \end{verbatim}
2662 \verbspace
2663
2664 The write data statement causes Ragel to emit the constant static data needed
2665 by the machine. In table-driven output styles (see Section \ref{genout}) this
2666 is a collection of arrays that represent the states and transitions of the
2667 machine.  In goto-driven machines much less data is emitted. At the very
2668 minimum a start state \verb|name_start| is generated.  All variables written
2669 out in machine data have both the \verb|static| and \verb|const| properties and
2670 are prefixed with the name of the machine and an
2671 underscore. The data can be placed inside a class, inside a function, or it can
2672 be defined as global data.
2673
2674 Two variables are written that may be used to test the state of the machine
2675 after a buffer block has been processed. The \verb|name_error| variable gives
2676 the id of the state that the machine moves into when it cannot find a valid
2677 transition to take. The machine immediately breaks out of the processing loop when
2678 it finds itself in the error state. The error variable can be compared to the
2679 current state to determine if the machine has failed to parse the input. If the
2680 machine is complete, that is from every state there is a transition to a proper
2681 state on every possible character of the alphabet, then no error state is required
2682 and this variable will be set to -1.
2683
2684 The \verb|name_first_final| variable stores the id of the first final state. All of the
2685 machine's states are sorted by their final state status before having their ids
2686 assigned. Checking if the machine has accepted its input can then be done by
2687 checking if the current state is greater-than or equal to the first final
2688 state.
2689
2690 Data generation has several options:
2691
2692 \begin{itemize}
2693 \setlength{\itemsep}{-2mm}
2694 \item \verb|noerror  | - Do not generate the integer variable that gives the
2695 id of the error state.
2696 \item \verb|nofinal  | - Do not generate the integer variable that gives the
2697 id of the first final state.
2698 \item \verb|noprefix | - Do not prefix the variable names with the name of the
2699 machine.
2700 \end{itemize}
2701
2702 \subsection{Write Init}
2703 \begin{verbatim}
2704 write init;
2705 \end{verbatim}
2706 \verbspace
2707
2708 The write init statement causes Ragel to emit initialization code. This should
2709 be executed once before the machine is started. At a very minimum this sets the
2710 current state to the start state. If other variables are needed by the
2711 generated code, such as call stack variables or scanner management
2712 variables, they are also initialized here.
2713
2714 The \verb|nocs| option to the write init statement will cause ragel to skip
2715 intialization of the cs variable. This is useful if the user wishes to use
2716 custom logic to decide which state the specification should start in.
2717
2718 \subsection{Write Exec}
2719 \begin{verbatim}
2720 write exec [options];
2721 \end{verbatim}
2722 \verbspace
2723
2724 The write exec statement causes Ragel to emit the state machine's execution code.
2725 Ragel expects several variables to be available to this code. At a very minimum, the
2726 generated code needs access to the current character position \verb|p|, the ending
2727 position \verb|pe| and the current state \verb|cs|, though \verb|pe|
2728 can be excluded by specifying the \verb|noend| write option.
2729 The \verb|p| variable is the cursor that the execute code will
2730 used to traverse the input. The \verb|pe| variable should be set up to point to one
2731 position past the last valid character in the buffer.
2732
2733 Other variables are needed when certain features are used. For example using
2734 the \verb|fcall| or \verb|fret| statements requires \verb|stack| and
2735 \verb|top| variables to be defined. If a longest-match construction is used,
2736 variables for managing backtracking are required.
2737
2738 The write exec statement has one option. The \verb|noend| option tells Ragel
2739 to generate code that ignores the end position \verb|pe|. In this
2740 case the user must explicitly break out of the processing loop using
2741 \verb|fbreak|, otherwise the machine will continue to process characters until
2742 it moves into the error state. This option is useful if one wishes to process a
2743 null terminated string. Rather than traverse the string to discover then length
2744 before processing the input, the user can break out when the null character is
2745 seen.  The example in Figure \ref{fbreak-example} shows the use of the
2746 \verb|noend| write option and the \verb|fbreak| statement for processing a string.
2747
2748 \begin{figure}
2749 \small
2750 \begin{verbatim}
2751 #include <stdio.h>
2752 %% machine foo;
2753 int main( int argc, char **argv )
2754 {
2755     %% write data noerror nofinal;
2756     int cs, res = 0;
2757     if ( argc > 1 ) {
2758         char *p = argv[1];
2759         %%{ 
2760             main := 
2761                 [a-z]+ 
2762                 0 @{ res = 1; fbreak; };
2763             write init;
2764             write exec noend;
2765         }%%
2766     }
2767     printf("execute = %i\n", res );
2768     return 0;
2769 }
2770 \end{verbatim}
2771 \caption{Use of {\tt noend} write option and the {\tt fbreak} statement for
2772 processing a string.}
2773 \label{fbreak-example}
2774 \end{figure}
2775
2776
2777 \subsection{Write EOF Actions}
2778 \begin{verbatim}
2779 write eof;
2780 \end{verbatim}
2781 \verbspace
2782
2783 The write EOF statement causes Ragel to emit code that executes EOF actions.
2784 This write statement is only relevant if EOF actions have been embedded,
2785 otherwise it does not generate anything. The EOF action code requires access to
2786 the current state.
2787
2788 \subsection{Write Exports}
2789 \label{export}
2790
2791 \begin{verbatim}
2792 write exports;
2793 \end{verbatim}
2794 \verbspace
2795
2796 The export feature can be used to export simple machine definitions. Machine definitions
2797 are marked for export using the \verb|export| keyword.
2798
2799 \verbspace
2800 \begin{verbatim}
2801 export machine_to_export = 0x44;
2802 \end{verbatim}
2803 \verbspace
2804
2805 When the write exports statement is used these machines are 
2806 written out in the generated code. Defines are used for C and constant integers
2807 are used for D, Java and Ruby. See Section \ref{import} for a description of the
2808 import statement.
2809   
2810 \section{Maintaining Pointers to Input Data}
2811
2812 In the creation of any parser it is not uncommon to require the collection of
2813 the data being parsed.  It is always possible to collect data into a growable
2814 buffer as the machine moves over it, however the copying of data is a somewhat
2815 wasteful use of processor cycles. The most efficient way to collect data from
2816 the parser is to set pointers into the input then later reference them.  This
2817 poses a problem for uses of Ragel where the input data arrives in blocks, such
2818 as over a socket or from a file. If a pointer is set in one buffer block but
2819 must be used while parsing a following buffer block, some extra consideration
2820 to correctness must be made.
2821
2822 The scanner constructions exhibit this problem, requiring the maintenance
2823 code described in Section \ref{generating-scanners}. If a longest-match
2824 construction has been used somewhere in the machine then it is possible to
2825 take advantage of the required prefix maintenance code in the driver program to
2826 ensure pointers to the input are always valid. If laying down a pointer one can
2827 set \verb|tokstart| at the same spot or ahead of it. When data is shifted in
2828 between loops the user must also shift the pointer.  In this way it is possible
2829 to maintain pointers to the input that will always be consistent.
2830
2831 \begin{figure}
2832 \small
2833 \begin{verbatim}
2834     int have = 0;
2835     while ( 1 ) {
2836         char *p, *pe, *data = buf + have;
2837         int len, space = BUFSIZE - have;
2838
2839         if ( space == 0 ) { 
2840             fprintf(stderr, "BUFFER OUT OF SPACE\n");
2841             exit(1);
2842         }
2843
2844         len = fread( data, 1, space, stdin );
2845         if ( len == 0 )
2846             break;
2847
2848         /* Find the last newline by searching backwards. */
2849         p = buf;
2850         pe = data + len - 1;
2851         while ( *pe != '\n' && pe >= buf )
2852             pe--;
2853         pe += 1;
2854
2855         %% write exec;
2856
2857         /* How much is still in the buffer? */
2858         have = data + len - pe;
2859         if ( have > 0 )
2860             memmove( buf, pe, have );
2861
2862         if ( len < space )
2863             break;
2864     }
2865 \end{verbatim}
2866 \caption{An example of line-oriented processing.}
2867 \label{line-oriented}
2868 \end{figure}
2869
2870 In general, there are two approaches for guaranteeing the consistency of
2871 pointers to input data. The first approach is the one just described;
2872 lay down a marker from an action,
2873 then later ensure that the data the marker points to is preserved ahead of
2874 the buffer on the next execute invocation. This approach is good because it
2875 allows the parser to decide on the pointer-use boundaries, which can be
2876 arbitrarily complex parsing conditions. A downside is that it requires any
2877 pointers that are set to be corrected in between execute invocations.
2878
2879 The alternative is to find the pointer-use boundaries before invoking the execute
2880 routine, then pass in the data using these boundaries. For example, if the
2881 program must perform line-oriented processing, the user can scan backwards from
2882 the end of an input block that has just been read in and process only up to the
2883 first found newline. On the next input read, the new data is placed after the
2884 partially read line and processing continues from the beginning of the line.
2885 An example of line-oriented processing is given in Figure \ref{line-oriented}.
2886
2887
2888 \section{Running the Executables}
2889
2890 Ragel is broken down into two parts: a frontend that compiles machines
2891 and emits them in an XML format, and a backend that generates code or a
2892 Graphviz Dot file from the XML data. The purpose of the XML-based intermediate
2893 format is to allow users to inspect their compiled state machines and to
2894 interface Ragel to other tools such as custom visualizers, code generators or
2895 analysis tools. The split also serves to reduce the complexity of the Ragel
2896 program by strictly separating the data structures and algorithms that are used
2897 to compile machines from those that are used to generate code. 
2898
2899 \vspace{10pt}
2900
2901 \noindent The frontend program is called \verb|ragel|. It takes as an argument the host
2902 language. This can be:
2903
2904 \begin{itemize}
2905 \item \verb|-C  | for C/C++/Objective-C code (default)
2906 \item \verb|-D  | for D code.
2907 \item \verb|-J  | for Java code.
2908 \item \verb|-R  | for Ruby code.
2909 \end{itemize}
2910
2911 \noindent There are four code backend programs. These are:
2912
2913 \begin{itemize}
2914 \item \verb|rlgen-cd    | generate code for the C-based and D languages.
2915 \item \verb|rlgen-java  | generate code for the Java language.
2916 \item \verb|rlgen-ruby  | generate code for the Ruby language.
2917 \item \verb|rlgen-dot   | generate a Graphviz Dot file.
2918 \end{itemize}
2919
2920 \section{Choosing a Generated Code Style (C/D only)}
2921 \label{genout}
2922
2923 There are three styles of code output to choose from. Code style affects the
2924 size and speed of the compiled binary. Changing code style does not require any
2925 change to the Ragel program. There are two table-driven formats and a goto
2926 driven format.
2927
2928 In addition to choosing a style to emit, there are various levels of action
2929 code reuse to choose from.  The maximum reuse levels (\verb|-T0|, \verb|-F0|
2930 and \verb|-G0|) ensure that no FSM action code is ever duplicated by encoding
2931 each transition's action list as static data and iterating
2932 through the lists on every transition. This will normally result in a smaller
2933 binary. The less action reuse options (\verb|-T1|, \verb|-F1| and \verb|-G1|)
2934 will usually produce faster running code by expanding each transition's action
2935 list into a single block of code, eliminating the need to iterate through the
2936 lists. This duplicates action code instead of generating the logic necessary
2937 for reuse. Consequently the binary will be larger. However, this tradeoff applies to
2938 machines with moderate to dense action lists only. If a machine's transitions
2939 frequently have less than two actions then the less reuse options will actually
2940 produce both a smaller and a faster running binary due to less action sharing
2941 overhead. The best way to choose the appropriate code style for your
2942 application is to perform your own tests.
2943
2944 The table-driven FSM represents the state machine as constant static data. There are
2945 tables of states, transitions, indices and actions. The current state is
2946 stored in a variable. The execution is simply a loop that looks up the current
2947 state, looks up the transition to take, executes any actions and moves to the
2948 target state. In general, the table-driven FSM can handle any machine, produces
2949 a smaller binary and requires a less expensive host language compile, but
2950 results in slower running code.  Since the table-driven format is the most
2951 flexible it is the default code style.
2952
2953 The flat table-driven machine is a table-based machine that is optimized for
2954 small alphabets. Where the regular table machine uses the current character as
2955 the key in a binary search for the transition to take, the flat table machine
2956 uses the current character as an index into an array of transitions. This is
2957 faster in general, however is only suitable if the span of possible characters
2958 is small.
2959
2960 The goto-driven FSM represents the state machine using goto and switch
2961 statements. The execution is a flat code block where the transition to take is
2962 computed using switch statements and directly executable binary searches.  In
2963 general, the goto FSM produces faster code but results in a larger binary and a
2964 more expensive host language compile.
2965
2966 The goto-driven format has an additional action reuse level (\verb|-G2|) that
2967 writes actions directly into the state transitioning logic rather than putting
2968 all the actions together into a single switch. Generally this produces faster
2969 running code because it allows the machine to encode the current state using
2970 the processor's instruction pointer. Again, sparse machines may actually
2971 compile to smaller binaries when \verb|-G2| is used due to less state and
2972 action management overhead. For many parsing applications \verb|-G2| is the
2973 preferred output format.
2974
2975 \verbspace
2976 \begin{center}
2977 \begin{tabular}{|c|c|}
2978 \hline
2979 \multicolumn{2}{|c|}{\bf Code Output Style Options} \\
2980 \hline
2981 \verb|-T0|&binary search table-driven\\
2982 \hline
2983 \verb|-T1|&binary search, expanded actions\\
2984 \hline
2985 \verb|-F0|&flat table-driven\\
2986 \hline
2987 \verb|-F1|&flat table, expanded actions\\
2988 \hline
2989 \verb|-G0|&goto-driven\\
2990 \hline
2991 \verb|-G1|&goto, expanded actions\\
2992 \hline
2993 \verb|-G2|&goto, in-place actions\\
2994 \hline
2995 \end{tabular}
2996 \end{center}
2997
2998 \chapter{Beyond the Basic Model}
2999
3000 \section{Parser Modularization}
3001
3002 It is possible to use Ragel's machine construction and action embedding
3003 operators to specify an entire parser using a single regular expression. In
3004 many cases this is the desired way to specify a parser in Ragel. However, in
3005 some scenarios, the language to parse may be so large that it is difficult to
3006 think about it as a single regular expression. It may shift between distinct
3007 parsing strategies, in which case modularization into several coherent blocks
3008 of the language may be appropriate.
3009
3010 It may also be the case that patterns that compile to a large number of states
3011 must be used in a number of different contexts and referencing them in each
3012 context results in a very large state machine. In this case, an ability to reuse
3013 parsers would reduce code size.
3014
3015 To address this, distinct regular expressions may be instantiated and linked
3016 together by means of a jumping and calling mechanism. This mechanism is
3017 analogous to the jumping to and calling of processor instructions. A jump
3018 command, given in action code, causes control to be immediately passed to
3019 another portion of the machine by way of setting the current state variable. A
3020 call command causes the target state of the current transition to be pushed to
3021 a state stack before control is transferred.  Later on, the original location
3022 may be returned to with a return statement. In the following example, distinct
3023 state machines are used to handle the parsing of two types of headers.
3024
3025 % GENERATE: call
3026 % %%{
3027 %       machine call;
3028 \begin{inline_code}
3029 \begin{verbatim}
3030 action return { fret; }
3031 action call_date { fcall date; }
3032 action call_name { fcall name; }
3033
3034 # A parser for date strings.
3035 date := [0-9][0-9] '/' 
3036         [0-9][0-9] '/' 
3037         [0-9][0-9][0-9][0-9] '\n' @return;
3038
3039 # A parser for name strings.
3040 name := ( [a-zA-Z]+ | ' ' )** '\n' @return;
3041
3042 # The main parser.
3043 headers = 
3044     ( 'from' | 'to' ) ':' @call_name | 
3045     ( 'departed' | 'arrived' ) ':' @call_date;
3046
3047 main := headers*;
3048 \end{verbatim}
3049 \end{inline_code}
3050 % }%%
3051 % %% write data;
3052 % void f()
3053 % {
3054 %       %% write init;
3055 %       %% write exec;
3056 % }
3057 % END GENERATE
3058
3059 Calling and jumping should be used carefully as they are operations that take
3060 one out of the domain
3061 of regular languages. A machine that contains a call or jump statement in one
3062 of its actions should be used as an argument to a machine construction operator
3063 only with considerable care. Since DFA transitions may actually
3064 represent several NFA transitions, a call or jump embedded in one machine can
3065 inadvertently terminate another machine that it shares prefixes with. Despite
3066 this danger, theses statements have proven useful for tying together
3067 sub-parsers of a language into a parser for the full language, especially for
3068 the purpose of modularization and reducing the number of states when the
3069 machine contains frequently recurring patterns.
3070 \section{Referencing Names}
3071 \label{labels}
3072
3073 This section describes how to reference names in epsilon transitions and
3074 action-based control-flow statements such as \verb|fgoto|. There is a hierarchy
3075 of names implied in a Ragel specification.  At the top level are the machine
3076 instantiations. Beneath the instantiations are labels and references to machine
3077 definitions. Beneath those are more labels and references to definitions, and
3078 so on.
3079
3080 Any name reference may contain multiple components separated with the \verb|::|
3081 compound symbol.  The search for the first component of a name reference is
3082 rooted at the join expression that the epsilon transition or action embedding
3083 is contained in. If the name reference is not contained in a join,
3084 the search is rooted at the machine definition that the epsilon transition or
3085 action embedding is contained in. Each component after the first is searched
3086 for beginning at the location in the name tree that the previous reference
3087 component refers to.
3088
3089 In the case of action-based references, if the action is embedded more than
3090 once, the local search is performed for each embedding and the result is the
3091 union of all the searches. If no result is found for action-based references then
3092 the search is repeated at the root of the name tree.  Any action-based name
3093 search may be forced into a strictly global search by prefixing the name
3094 reference with \verb|::|.
3095
3096 The final component of the name reference must resolve to a unique entry point.
3097 If a name is unique in the entire name tree it can be referenced as is. If it
3098 is not unique it can be specified by qualifying it with names above it in the
3099 name tree. However, it can always be renamed.
3100
3101 % FIXME: Should fit this in somewhere.
3102 % Some kinds of name references are illegal. Cannot call into longest-match
3103 % machine, can only call its start state. Cannot make a call to anywhere from
3104 % any part of a longest-match machine except a rule's action. This would result
3105 % in an eventual return to some point inside a longest-match other than the
3106 % start state. This is banned for the same reason a call into the LM machine is
3107 % banned.
3108
3109
3110 \section{Scanners}
3111 \label{generating-scanners}
3112
3113 Scanners are very much intertwined with regular-languages and their
3114 corresponding processors. For this reason Ragel supports the definition of
3115 Scanners.  The generated code will repeatedly attempt to match patterns from a
3116 list, favouring longer patterns over shorter patterns.  In the case of
3117 equal-length matches, the generated code will favour patterns that appear ahead
3118 of others. When a scanner makes a match it executes the user code associated
3119 with the match, consumes the input then resumes scanning.
3120
3121 \verbspace
3122 \begin{verbatim}
3123 <machine_name> := |* 
3124         pattern1 => action1;
3125         pattern2 => action2;
3126         ...
3127     *|;
3128 \end{verbatim}
3129 \verbspace
3130
3131 On the surface, Ragel scanners are similar to those defined by Lex. Though
3132 there is a key distinguishing feature: patterns may be arbitrary Ragel
3133 expressions and can therefore contain embedded code. With a Ragel-based scanner
3134 the user need not wait until the end of a pattern before user code can be
3135 executed.
3136
3137 Scanners can be used to process sub-languages, as well as for tokenizing
3138 programming languages. In the following example a scanner is used to tokenize
3139 the contents of a header field.
3140
3141 \begin{inline_code}
3142 \begin{verbatim}
3143 word = [a-z]+;
3144 head_name = 'Header';
3145
3146 header := |*
3147     word;
3148     ' ';
3149     '\n' => { fret; };
3150 *|;
3151
3152 main := ( head_name ':' @{ fcall header; } )*;
3153 \end{verbatim}
3154 \end{inline_code}
3155 \verbspace
3156
3157 The scanner construction has a purpose similar to the longest-match kleene star
3158 operator \verb|**|. The key
3159 difference is that a scanner is able to backtrack to match a previously matched
3160 shorter string when the pursuit of a longer string fails.  For this reason the
3161 scanner construction operator is not a pure state machine construction
3162 operator. It relies on several variables which enable it to backtrack and make
3163 pointers to the matched input text available to the user.  For this reason
3164 scanners must be immediately instantiated. They cannot be defined inline or
3165 referenced by another expression. Scanners must be jumped to or called.
3166
3167 Scanners rely on the \verb|tokstart|, \verb|tokend| and \verb|act|
3168 variables to be present so that it can backtrack and make pointers to the
3169 matched text available to the user. If input is processed using multiple calls
3170 to the execute code then the user must ensure that when a token is only
3171 partially matched that the prefix is preserved on the subsequent invocation of
3172 the execute code.
3173
3174 The \verb|tokstart| variable must be defined as a pointer to the input data.
3175 It is used for recording where the current token match begins. This variable
3176 may be used in action code for retrieving the text of the current match.  Ragel
3177 ensures that in between tokens and outside of the longest-match machines that
3178 this pointer is set to null. In between calls to the execute code the user must
3179 check if \verb|tokstart| is set and if so, ensure that the data it points to is
3180 preserved ahead of the next buffer block. This is described in more detail
3181 below.
3182
3183 The \verb|tokend| variable must also be defined as a pointer to the input data.
3184 It is used for recording where a match ends and where scanning of the next
3185 token should begin. This can also be used in action code for retrieving the
3186 text of the current match.
3187
3188 The \verb|act| variable must be defined as an integer type. It is used for
3189 recording the identity of the last pattern matched when the scanner must go
3190 past a matched pattern in an attempt to make a longer match. If the longer
3191 match fails it may need to consult the \verb|act| variable. In some cases, use 
3192 of the \verb|act|
3193 variable can be avoided because the value of the current state is enough
3194 information to determine which token to accept, however in other cases this is
3195 not enough and so the \verb|act| variable is used. 
3196
3197 When the longest-match operator is in use, the user's driver code must take on
3198 some buffer management functions. The following algorithm gives an overview of
3199 the steps that should be taken to properly use the longest-match operator.
3200
3201 \begin{itemize}
3202 \setlength{\parskip}{0pt}
3203 \item Read a block of input data.
3204 \item Run the execute code.
3205 \item If \verb|tokstart| is set, the execute code will expect the incomplete
3206 token to be preserved ahead of the buffer on the next invocation of the execute
3207 code.  
3208 \begin{itemize}
3209 \item Shift the data beginning at \verb|tokstart| and ending at \verb|pe| to the
3210 beginning of the input buffer.
3211 \item Reset \verb|tokstart| to the beginning of the buffer. 
3212 \item Shift \verb|tokend| by the distance from the old value of \verb|tokstart|
3213 to the new value. The \verb|tokend| variable may or may not be valid.  There is
3214 no way to know if it holds a meaningful value because it is not kept at null
3215 when it is not in use. It can be shifted regardless.
3216 \end{itemize}
3217 \item Read another block of data into the buffer, immediately following any
3218 preserved data.
3219 \item Run the scanner on the new data.
3220 \end{itemize}
3221
3222 Figure \ref{preserve_example} shows the required handling of an input stream in
3223 which a token is broken by the input block boundaries. After processing up to
3224 and including the ``t'' of ``characters'', the prefix of the string token must be
3225 retained and processing should resume at the ``e'' on the next iteration of
3226 the execute code.
3227
3228 If one uses a large input buffer for collecting input then the number of times
3229 the shifting must be done will be small. Furthermore, if one takes care not to
3230 define tokens that are allowed to be very long and instead processes these
3231 items using pure state machines or sub-scanners, then only a small amount of
3232 data will ever need to be shifted.
3233
3234 \begin{figure}
3235 \begin{verbatim}
3236       a)           A stream "of characters" to be scanned.
3237                    |        |          |
3238                    p        tokstart   pe
3239
3240       b)           "of characters" to be scanned.
3241                    |          |        |
3242                    tokstart   p        pe
3243 \end{verbatim}
3244 \caption{Following an invocation of the execute code there may be a partially
3245 matched token (a). The data of the partially matched token 
3246 must be preserved ahead of the new data on the next invocation (b).}
3247 \label{preserve_example}
3248 \end{figure}
3249
3250 Since scanners attempt to make the longest possible match of input, in some
3251 cases they are not able to identify a token upon parsing its final character,
3252 they must wait for a lookahead character. For example if trying to match words,
3253 the token match must be triggered on following whitespace in case more
3254 characters of the word have yet to come. The user must therefore arrange for an
3255 EOF character to be sent to the scanner to flush out any token that has not yet
3256 been matched.  The user can exclude a single character from the entire scanner
3257 and use this character as the EOF character, possibly specifying an EOF action.
3258 For most scanners, zero is a suitable choice for the EOF character. 
3259
3260 Alternatively, if whitespace is not significant and ignored by the scanner, the
3261 final real token can be flushed out by simply sending an additional whitespace
3262 character on the end of the stream. If the real stream ends with whitespace
3263 then it will simply be extended and ignored. If it does not, then the last real token is
3264 guaranteed to be flushed and the dummy EOF whitespace ignored.
3265 An example scanner processing loop is given in Figure \ref{scanner-loop}.
3266
3267 \begin{figure}
3268 \small
3269 \begin{verbatim}
3270     int have = 0;
3271     bool done = false;
3272     while ( !done ) {
3273         /* How much space is in the buffer? */
3274         int space = BUFSIZE - have;
3275         if ( space == 0 ) {
3276             /* Buffer is full. */
3277             cerr << "TOKEN TOO BIG" << endl;
3278             exit(1);
3279         }
3280
3281         /* Read in a block after any data we already have. */
3282         char *p = inbuf + have;
3283         cin.read( p, space );
3284         int len = cin.gcount();
3285
3286         /* If no data was read, send the EOF character. */
3287         if ( len == 0 ) {
3288             p[0] = 0, len++;
3289             done = true;
3290         }
3291
3292         char *pe = p + len;
3293         %% write exec;
3294
3295         if ( cs == RagelScan_error ) {
3296             /* Machine failed before finding a token. */
3297             cerr << "PARSE ERROR" << endl;
3298             exit(1);
3299         }
3300
3301         if ( tokstart == 0 )
3302             have = 0;
3303         else {
3304             /* There is a prefix to preserve, shift it over. */
3305             have = pe - tokstart;
3306             memmove( inbuf, tokstart, have );
3307             tokend = inbuf + (tokend-tokstart);
3308             tokstart = inbuf;
3309         }
3310     }
3311 \end{verbatim}
3312 \caption{A processing loop for a scanner.}
3313 \label{scanner-loop}
3314 \end{figure}
3315
3316 \section{State Charts}
3317
3318 In addition to supporting the construction of state machines using regular
3319 languages, Ragel provides a way to manually specify state machines using
3320 state charts.  The comma operator combines machines together without any
3321 implied transitions. The user can then manually link machines by specifying
3322 epsilon transitions with the \verb|->| operator.  Epsilon transitions are drawn
3323 between the final states of a machine and entry points defined by labels.  This
3324 makes it possible to build machines using the explicit state-chart method while
3325 making minimal changes to the Ragel language. 
3326
3327 An interesting feature of Ragel's state chart construction method is that it
3328 can be mixed freely with regular expression constructions. A state chart may be
3329 referenced from within a regular expression, or a regular expression may be
3330 used in the definition of a state chart transition.
3331
3332 \subsection{Join}
3333
3334 \verb|expr , expr , ...|
3335 \verbspace
3336
3337 Join a list of machines together without
3338 drawing any transitions, without setting up a start state, and without
3339 designating any final states. Transitions between the machines may be specified
3340 using labels and epsilon transitions. The start state must be explicity
3341 specified with the ``start'' label. Final states may be specified with an
3342 epsilon transition to the implicitly created ``final'' state. The join
3343 operation allows one to build machines using a state chart model.
3344
3345 \subsection{Label}
3346
3347 \verb|label: expr| 
3348 \verbspace
3349
3350 Attaches a label to an expression. Labels can be
3351 used as the target of epsilon transitions and explicit control transfer
3352 statements such as \verb|fgoto| and \verb|fnext| in action
3353 code.
3354
3355 \subsection{Epsilon}
3356
3357 \verb|expr -> label| 
3358 \verbspace
3359
3360 Draws an epsilon transition to the state defined
3361 by \verb|label|.  Epsilon transitions are made deterministic when join
3362 operators are evaluated. Epsilon transitions that are not in a join operation
3363 are made deterministic when the machine definition that contains the epsilon is
3364 complete. See Section \ref{labels} for information on referencing labels.
3365
3366 \subsection{Simplifying State Charts}
3367
3368 There are two benefits to providing state charts in Ragel. The first is that it
3369 allows us to take a state chart with a full listing of states and transitions
3370 and simplifly it in selective places using regular expressions.
3371
3372 The state chart method of specifying parsers is very common.  It is an
3373 effective programming technique for producing robust code. The key disadvantage
3374 becomes clear when one attempts to comprehend a large parser specified in this
3375 way.  These programs usually require many lines, causing logic to be spread out
3376 over large distances in the source file. Remembering the function of a large
3377 number of states can be difficult and organizing the parser in a sensible way
3378 requires discipline because branches and repetition present many file layout
3379 options.  This kind of programming takes a specification with inherent
3380 structure such as looping, alternation and concatenation and expresses it in a
3381 flat form. 
3382
3383 If we could take an isolated component of a manually programmed state chart,
3384 that is, a subset of states that has only one entry point, and implement it
3385 using regular language operators then we could eliminate all the explicit
3386 naming of the states contained in it. By eliminating explicitly named states
3387 and replacing them with higher-level specifications we simplify a state machine
3388 specification.
3389
3390 For example, sometimes chains of states are needed, with only a small number of
3391 possible characters appearing along the chain. These can easily be replaced
3392 with a concatenation of characters. Sometimes a group of common states
3393 implement a loop back to another single portion of the machine. Rather than
3394 manually duplicate all the transitions that loop back, we may be able to
3395 express the loop using a kleene star operator.
3396
3397 Ragel allows one to take this state map simplification approach. We can build
3398 state machines using a state map model and implement portions of the state map
3399 using regular languages. In place of any transition in the state machine,
3400 entire sub-state machines can be given. These can encapsulate functionality
3401 defined elsewhere. An important aspect of the Ragel approach is that when we
3402 wrap up a collection of states using a regular expression we do not lose
3403 access to the states and transitions. We can still execute code on the
3404 transitions that we have encapsulated.
3405
3406 \subsection{Dropping Down One Level of Abstraction}
3407 \label{down}
3408
3409 The second benefit of incorporating state charts into Ragel is that it permits
3410 us to bypass the regular language abstraction if we need to. Ragel's action
3411 embedding operators are sometimes insufficient for expressing certain parsing
3412 tasks.  In the same way that is useful for C language programmers to drop down
3413 to assembly language programming using embedded assembler, it is sometimes
3414 useful for the Ragel programmer to drop down to programming with state charts.
3415
3416 In the following example, we wish to buffer the characters of an XML CDATA
3417 sequence. The sequence is terminated by the string \verb|]]>|. The challenge
3418 in our application is that we do not wish the terminating characters to be
3419 buffered. An expression of the form \verb|any* @buffer :>> ']]>'| will not work
3420 because the buffer will always contain the characters \verb|]]| on the end.
3421 Instead, what we need is to delay the buffering of \hspace{0.25mm} \verb|]|
3422 characters until a time when we
3423 abandon the terminating sequence and go back into the main loop. There is no
3424 easy way to express this using Ragel's regular expression and action embedding
3425 operators, and so an ability to drop down to the state chart method is useful.
3426
3427 % GENERATE: dropdown
3428 % OPT: -p
3429 % %%{
3430 % machine dropdown;
3431 \begin{inline_code}
3432 \begin{verbatim}
3433 action bchar { buff( fpc ); }    # Buffer the current character.
3434 action bbrack1 { buff( "]" ); }
3435 action bbrack2 { buff( "]]" ); }
3436
3437 CDATA_body =
3438 start: (
3439      ']' -> one |
3440      (any-']') @bchar ->start
3441 ),
3442 one: (
3443      ']' -> two |
3444      [^\]] @bbrack1 @bchar ->start
3445 ),
3446 two: (
3447      '>' -> final |
3448      ']' @bbrack1 -> two |
3449      [^>\]] @bbrack2 @bchar ->start
3450 );
3451 \end{verbatim}
3452 \end{inline_code}
3453 % main := CDATA_body;
3454 % }%%
3455 % END GENERATE
3456
3457 \graphspace
3458 \begin{center}
3459 \includegraphics[scale=0.55]{dropdown}
3460 \end{center}
3461
3462
3463 \section{Semantic Conditions}
3464 \label{semantic}
3465
3466 Many communication protocols contain variable-length fields, where the length
3467 of the field is given ahead of the field as a value. This
3468 problem cannot be expressed using regular languages because of its
3469 context-dependent nature. The prevalence of variable-length fields in
3470 communication protocols motivated us to introduce semantic conditions into
3471 the Ragel language.
3472
3473 A semantic condition is a block of user code that is executed immediately
3474 before a transition is taken. If the code returns a value of true, the
3475 transition may be taken.  We can now embed code that extracts the length of a
3476 field, then proceed to match $n$ data values.
3477
3478 % GENERATE: conds1
3479 % OPT: -p
3480 % %%{
3481 % machine conds1;
3482 % number = digit+;
3483 \begin{inline_code}
3484 \begin{verbatim}
3485 action rec_num { i = 0; n = getnumber(); }
3486 action test_len { i++ < n }
3487 data_fields = (
3488     'd' 
3489     [0-9]+ %rec_num 
3490     ':'
3491     ( [a-z] when test_len )*
3492 )**;
3493 \end{verbatim}
3494 \end{inline_code}
3495 % main := data_fields;
3496 % }%%
3497 % END GENERATE
3498
3499 \begin{center}
3500 \includegraphics[scale=0.55]{conds1}
3501 \end{center}
3502 \graphspace
3503
3504 The Ragel implementation of semantic conditions does not force us to give up the
3505 compositional property of Ragel definitions. For example, a machine that tests
3506 the length of a field using conditions can be unioned with another machine
3507 that accepts some of the same strings, without the two machines interfering with
3508 one another. The user need not be concerned about whether or not the result of the
3509 semantic condition will affect the matching of the second machine.
3510
3511 To see this, first consider that when a user associates a condition with an
3512 existing transition, the transition's label is translated from the base character
3513 to its corresponding value in the space that represents ``condition $c$ true''. Should
3514 the determinization process combine a state that has a conditional transition
3515 with another state that has a transition on the same input character but
3516 without a condition, then the condition-less transition first has its label
3517 translated into two values, one to its corresponding value in the space that
3518 represents ``condition $c$ true'' and another to its corresponding value in the
3519 space that represents ``condition $c$ false''. It
3520 is then safe to combine the two transitions. This is shown in the following
3521 example.  Two intersecting patterns are unioned, one with a condition and one
3522 without. The condition embedded in the first pattern does not affect the second
3523 pattern.
3524
3525 % GENERATE: conds2
3526 % OPT: -p
3527 % %%{
3528 % machine conds2;
3529 % number = digit+;
3530 \begin{inline_code}
3531 \begin{verbatim}
3532 action test_len { i++ < n }
3533 action one { /* accept pattern one */ }
3534 action two { /* accept pattern two */ }
3535 patterns = 
3536     ( [a-z] when test_len )+ %one |
3537     [a-z][a-z0-9]* %two;
3538 main := patterns '\n';
3539 \end{verbatim}
3540 \end{inline_code}
3541 % }%%
3542 % END GENERATE
3543
3544 \begin{center}
3545 \includegraphics[scale=0.55]{conds2}
3546 \end{center}
3547 \graphspace
3548
3549 There are many more potential uses for semantic conditions. The user is free to
3550 use arbitrary code and may therefore perform actions such as looking up names
3551 in dictionaries, validating input using external parsing mechanisms or
3552 performing checks on the semantic structure of input seen so far. In the
3553 next section we describe how Ragel accommodates several common parser
3554 engineering problems.
3555
3556 \section{Implementing Lookahead}
3557
3558 There are a few strategies for implementing lookahead in Ragel programs.
3559 Pending out actions, which are described in Section \ref{out-actions}, can be
3560 used as a form of lookahead.  Ragel also provides the \verb|fhold| directive
3561 which can be used in actions to prevent the machine from advancing over the
3562 current character. It is also possible to manually adjust the current character
3563 position by shifting it backwards using \verb|fexec|, however when this is
3564 done, care must be taken not to overstep the beginning of the current buffer
3565 block. In both the use of \verb|fhold| and \verb|fexec| the user must be
3566 cautious of combining the resulting machine with another in such a way that the
3567 transition on which the current position is adjusted is not combined with a
3568 transition from the other machine.
3569
3570 \section{Parsing Recursive Language Structures}
3571
3572 In general Ragel cannot handle recursive structures because the grammar is
3573 interpreted as a regular language. However, depending on what needs to be
3574 parsed it is sometimes practical to implement the recursive parts using manual
3575 coding techniques. This often works in cases where the recursive structures are
3576 simple and easy to recognize, such as in the balancing of parentheses
3577
3578 One approach to parsing recursive structures is to use actions that increment
3579 and decrement counters or otherwise recognise the entry to and exit from
3580 recursive structures and then jump to the appropriate machine defnition using
3581 \verb|fcall| and \verb|fret|. Alternatively, semantic conditions can be used to
3582 test counter variables.
3583
3584 A more traditional approach is to call a separate parsing function (expressed
3585 in the host language) when a recursive structure is entered, then later return
3586 when the end is recognized.
3587
3588 \end{document}