summaryrefslogtreecommitdiff
path: root/test/counting3.lm
blob: a45fc7798f0c7e4dbc8302a1ebc6231ee1f397db (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
127
128
129
context counting

	#
	# Regular Definitions
	#
	rl rl_ws /[ \t\n\r\v]+/
	rl rl_id /[a-zA-Z_][a-zA-Z0-9_]*/
	rl rl_num /[0-9]+/

	#
	# Tokens
	#

	lex
		# Ignore whitespace.
		ignore /rl_ws/

		literal `;

		# Tokens. 
		token id /rl_id/
		token number /rl_num/
	end

	#
	# Global Data
	#

	target: int
	count: int

	#
	# Productions
	#

	def get_target 
		[number]
		{
			count = 0
			target = r1.data.atoi()
			print( 'target: ', target, '\n' )
		}

	# Arbitrary item.
	def item 
		[number]
	|	[id]

	def count_items 
		[one_item count_items]
	|	[]

	def one_item 
		[item]
		{
			count = count + 1
			if count > target {
				reject
			} 
			print( 'ITEM\n' )
		}


	# Wrapper which prevents short lists from getting through if the parser
	# encounters an error and needs to backtrack over counted list.
	def counted_list 
		[get_target count_items]
		{
			print( 'trying: ', count, ' for: ', target, '\n' )
			if count < target {
				reject
			}
		}


	def start 
		[counted_list*]
		{

			for List: counted_list in lhs {
				match List [Count: number Items: count_items]
				print( 'num items: ', Count.data.atoi(), '\n' )

				i: int = 1
				for Item: item in Items {
					print( '  item ', i, ': ', ^Item, '\n' )
					i = i + 1
				}
			}
			print( '*** SUCCESS ***\n' )
		}

end # counting

Counting: counting = new counting()
parse counting::start( Counting )[ stdin ]
##### IN #####
3 1 b c 1 1 0 3 a b c
##### EXP #####
target: 3
ITEM
ITEM
ITEM
ITEM
trying: 3 for: 3
target: 1
ITEM
ITEM
trying: 1 for: 1
target: 0
ITEM
trying: 0 for: 0
target: 3
ITEM
ITEM
ITEM
trying: 3 for: 3
num items: 3
  item 1: 1
  item 2: b
  item 3: c
num items: 1
  item 1: 1
num items: 0
num items: 3
  item 1: a
  item 2: b
  item 3: c
*** SUCCESS ***