Initialize Tizen 2.3
[external/ragel.git] / examples / statechart.rl
1 /*
2  * Demonstrate the use of labels, the epsilon operator, and the join operator
3  * for creating machines using the named state and transition list paradigm.
4  * This implementes the same machine as the atoi example.
5  */
6
7 #include <iostream>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11
12 using namespace std;
13
14 struct StateChart
15 {
16         bool neg;
17         int val;
18         int cs;
19
20         int init( );
21         int execute( const char *data, int len );
22         int finish( );
23 };
24
25 %%{
26         machine StateChart;
27
28         action begin {
29                 neg = false;
30                 val = 0;
31         }
32
33         action see_neg {
34                 neg = true;
35         }
36
37         action add_digit { 
38                 val = val * 10 + (fc - '0');
39         }
40
41         action finish {
42                 if ( neg )
43                         val = -1 * val;
44         }
45
46         atoi = (
47                 start: (
48                         '-' @see_neg ->om_num | 
49                         '+' ->om_num |
50                         [0-9] @add_digit ->more_nums
51                 ),
52
53                 # One or more nums.
54                 om_num: (
55                         [0-9] @add_digit ->more_nums
56                 ),
57
58                 # Zero ore more nums.
59                 more_nums: (
60                         [0-9] @add_digit ->more_nums |
61                         '' -> final
62                 )
63         ) >begin %finish;
64
65         main := ( atoi '\n' @{ cout << val << endl; } )*;
66 }%%
67
68 %% write data;
69
70 int StateChart::init( )
71 {
72         neg = false;
73         val = false;
74         %% write init;
75         return 1;
76 }
77
78 int StateChart::execute( const char *data, int len )
79 {
80         const char *p = data;
81         const char *pe = data + len;
82
83         %% write exec;
84
85         if ( cs == StateChart_error )
86                 return -1;
87         if ( cs >= StateChart_first_final )
88                 return 1;
89         return 0;
90 }
91
92 int StateChart::finish( )
93 {
94         if ( cs == StateChart_error )
95                 return -1;
96         if ( cs >= StateChart_first_final )
97                 return 1;
98         return 0;
99 }
100
101
102 #define BUFSIZE 1024
103
104 int main()
105 {
106         char buf[BUFSIZE];
107
108         StateChart atoi;
109         atoi.init();
110         while ( fgets( buf, sizeof(buf), stdin ) != 0 ) {
111                 atoi.execute( buf, strlen(buf) );
112         }
113         if ( atoi.finish() <= 0 )
114                 cerr << "statechart: error: parsing input" << endl;
115         return 0;
116 }