Initialize Tizen 2.3
[external/ragel.git] / examples / gotocallret.rl
1 /*
2  * Demonstrate the use of goto, call and return. This machine expects either a
3  * lower case char or a digit as a command then a space followed by the command
4  * arg. If the command is a char, then the arg must be an a string of chars.
5  * If the command is a digit, then the arg must be a string of digits. This
6  * choice is determined by action code, rather than though transition
7  * desitinations.
8  */
9
10 #include <iostream>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <string.h>
14
15 using namespace std;
16
17 struct GotoCallRet 
18 {
19         char comm;
20         int cs, top, stack[32];
21
22         int init( );
23         int execute( const char *data, int len, bool isEof );
24         int finish( );
25 };
26
27 %%{
28         machine GotoCallRet;
29
30         # Error machine, consumes to end of 
31         # line, then starts the main line over.
32         garble_line := (
33                 (any-'\n')*'\n'
34         ) >{cout << "error: garbling line" << endl;} @{fgoto main;};
35
36         # Look for a string of alphas or of digits, 
37         # on anything else, hold the character and return.
38         alp_comm := alpha+ $!{fhold;fret;};
39         dig_comm := digit+ $!{fhold;fret;};
40
41         # Choose which to machine to call into based on the command.
42         action comm_arg {
43                 if ( comm >= 'a' )
44                         fcall alp_comm;
45                 else 
46                         fcall dig_comm;
47         }
48
49         # Specifies command string. Note that the arg is left out.
50         command = (
51                 [a-z0-9] @{comm = fc;} ' ' @comm_arg '\n'
52         ) @{cout << "correct command" << endl;};
53
54         # Any number of commands. If there is an 
55         # error anywhere, garble the line.
56         main := command* $!{fhold;fgoto garble_line;};
57 }%%
58
59 %% write data;
60
61 int GotoCallRet::init( )
62 {
63         %% write init;
64         return 1;
65 }
66
67 int GotoCallRet::execute( const char *data, int len, bool isEof )
68 {
69         const char *p = data;
70         const char *pe = data + len;
71         const char *eof = isEof ? pe : 0;
72
73         %% write exec;
74         if ( cs == GotoCallRet_error )
75                 return -1;
76         if ( cs >= GotoCallRet_first_final )
77                 return 1;
78         return 0;
79 }
80
81 #define BUFSIZE 1024
82
83 int main()
84 {
85         char buf[BUFSIZE];
86
87         GotoCallRet gcr;
88         gcr.init();
89         while ( fgets( buf, sizeof(buf), stdin ) != 0 )
90                 gcr.execute( buf, strlen(buf), false );
91
92         gcr.execute( 0, 0, true );
93         if ( gcr.cs < GotoCallRet_first_final )
94                 cerr << "gotocallret: error: parsing input" << endl;
95         return 0;
96 }