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