summaryrefslogtreecommitdiff
path: root/examples/concurrent.rl
blob: 224f9601725e8e08be78625951f43211b27c7e54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/*
 * Show off concurrent abilities.
 */

#include <iostream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

#define BUFSIZE 2048

struct Concurrent
{
	int cur_char;
	int start_word;
	int start_comment;
	int start_literal;

	int cs;

	int init( );
	int execute( const char *data, int len, bool isEof );
	int finish( );
};

%%{
	machine Concurrent;

	action next_char {
		cur_char += 1;
	}

	action start_word {
		start_word = cur_char;
	}
	action end_word {
		cout << "word: " << start_word << 
				" " << cur_char-1 << endl;
	}

	action start_comment {
		start_comment = cur_char;
	}
	action end_comment {
		cout << "comment: " << start_comment <<
				" " << cur_char-1 << endl;
	}

	action start_literal {
		start_literal = cur_char;
	}
	action end_literal {
		cout << "literal: " << start_literal <<
				" " << cur_char-1 << endl;
	}

	# Count characters.
	chars = ( any @next_char )*;

	# Words are non-whitespace. 
	word = ( any-space )+ >start_word %end_word;
	words = ( ( word | space ) $1 %0 )*;

	# Finds C style comments. 
	comment = ( '/*' any* :>> '*/' ) >start_comment %end_comment;
	comments = ( comment | any )**;

	# Finds single quoted strings. 
	literalChar = ( any - ['\\] ) | ( '\\' . any );
	literal = ('\'' literalChar* '\'' ) >start_literal %end_literal;
	literals = ( ( literal | (any-'\'') ) $1 %0 )*;

	main := chars | words | comments | literals;
}%%

%% write data;

int Concurrent::init( )
{
	%% write init;
	cur_char = 0;
	return 1;
}

int Concurrent::execute( const char *data, int len, bool isEof )
{
	const char *p = data;
	const char *pe = data + len;
	const char *eof = isEof ? pe : 0;

	%% write exec;

	if ( cs == Concurrent_error )
		return -1;
	if ( cs >= Concurrent_first_final )
		return 1;
	return 0;
}

int Concurrent::finish( )
{
	if ( cs == Concurrent_error )
		return -1;
	if ( cs >= Concurrent_first_final )
		return 1;
	return 0;
}

Concurrent concurrent;
char buf[BUFSIZE];

int main()
{
	concurrent.init();
	while ( 1 ) {
		int len = fread( buf, 1, BUFSIZE, stdin );
		concurrent.execute( buf, len, len != BUFSIZE );
		if ( len != BUFSIZE )
			break;
	}

	if ( concurrent.finish() <= 0 )
		cerr << "concurrent: error parsing input" << endl;
	return 0;
}