Check-in [c4f5a3bcd9]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:added gl, irregex, sdl2 - removed match.scm
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: c4f5a3bcd9e8b908d9fcb09b282e0e1176b6197e
User & Date: ovenpasta@pizzahack.eu 2016-07-09 21:57:07
Context
2016-07-21
11:19
added ffi utils check-in: ce8130716e user: ovenpasta@pizzahack.eu tags: trunk
2016-07-09
21:57
added gl, irregex, sdl2 - removed match.scm check-in: c4f5a3bcd9 user: ovenpasta@pizzahack.eu tags: trunk
2016-07-08
18:32
now load-shared-object is automatic check-in: abe3cf1742 user: ovenpasta@pizzahack.eu tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added gl.sls.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497

;;; Ypsilon Scheme System
;;; Copyright (c) 2004-2009 Y.FUJITA / LittleWing Company Limited.
;;; See license.txt for terms and conditions of use.

;;; Ported to Chez Scheme by Ed Cavazos (wayo.cavazos@gmail.com)

(library (gl)
  (export GL_FALSE
          GL_TRUE
          GL_BYTE
          GL_UNSIGNED_BYTE
          GL_SHORT
          GL_UNSIGNED_SHORT
          GL_INT
          GL_UNSIGNED_INT
          GL_FLOAT
          GL_2_BYTES
          GL_3_BYTES
          GL_4_BYTES
          GL_DOUBLE
          GL_POINTS
          GL_LINES
          GL_LINE_LOOP
          GL_LINE_STRIP
          GL_TRIANGLES
          GL_TRIANGLE_STRIP
          GL_TRIANGLE_FAN
          GL_QUADS
          GL_QUAD_STRIP
          GL_POLYGON
          GL_VERTEX_ARRAY
          GL_NORMAL_ARRAY
          GL_COLOR_ARRAY
          GL_INDEX_ARRAY
          GL_TEXTURE_COORD_ARRAY
          GL_EDGE_FLAG_ARRAY
          GL_VERTEX_ARRAY_SIZE
          GL_VERTEX_ARRAY_TYPE
          GL_VERTEX_ARRAY_STRIDE
          GL_NORMAL_ARRAY_TYPE
          GL_NORMAL_ARRAY_STRIDE
          GL_COLOR_ARRAY_SIZE
          GL_COLOR_ARRAY_TYPE
          GL_COLOR_ARRAY_STRIDE
          GL_INDEX_ARRAY_TYPE
          GL_INDEX_ARRAY_STRIDE
          GL_TEXTURE_COORD_ARRAY_SIZE
          GL_TEXTURE_COORD_ARRAY_TYPE
          GL_TEXTURE_COORD_ARRAY_STRIDE
          GL_EDGE_FLAG_ARRAY_STRIDE
          GL_VERTEX_ARRAY_POINTER
          GL_NORMAL_ARRAY_POINTER
          GL_COLOR_ARRAY_POINTER
          GL_INDEX_ARRAY_POINTER
          GL_TEXTURE_COORD_ARRAY_POINTER
          GL_EDGE_FLAG_ARRAY_POINTER
          GL_V2F
          GL_V3F
          GL_C4UB_V2F
          GL_C4UB_V3F
          GL_C3F_V3F
          GL_N3F_V3F
          GL_C4F_N3F_V3F
          GL_T2F_V3F
          GL_T4F_V4F
          GL_T2F_C4UB_V3F
          GL_T2F_C3F_V3F
          GL_T2F_N3F_V3F
          GL_T2F_C4F_N3F_V3F
          GL_T4F_C4F_N3F_V4F
          GL_MATRIX_MODE
          GL_MODELVIEW
          GL_PROJECTION
          GL_TEXTURE
          GL_POINT_SMOOTH
          GL_POINT_SIZE
          GL_POINT_SIZE_GRANULARITY
          GL_POINT_SIZE_RANGE
          GL_LINE_SMOOTH
          GL_LINE_STIPPLE
          GL_LINE_STIPPLE_PATTERN
          GL_LINE_STIPPLE_REPEAT
          GL_LINE_WIDTH
          GL_LINE_WIDTH_GRANULARITY
          GL_LINE_WIDTH_RANGE
          GL_POINT
          GL_LINE
          GL_FILL
          GL_CW
          GL_CCW
          GL_FRONT
          GL_BACK
          GL_POLYGON_MODE
          GL_POLYGON_SMOOTH
          GL_POLYGON_STIPPLE
          GL_EDGE_FLAG
          GL_CULL_FACE
          GL_CULL_FACE_MODE
          GL_FRONT_FACE
          GL_POLYGON_OFFSET_FACTOR
          GL_POLYGON_OFFSET_UNITS
          GL_POLYGON_OFFSET_POINT
          GL_POLYGON_OFFSET_LINE
          GL_POLYGON_OFFSET_FILL
          GL_COMPILE
          GL_COMPILE_AND_EXECUTE
          GL_LIST_BASE
          GL_LIST_INDEX
          GL_LIST_MODE
          GL_NEVER
          GL_LESS
          GL_EQUAL
          GL_LEQUAL
          GL_GREATER
          GL_NOTEQUAL
          GL_GEQUAL
          GL_ALWAYS
          GL_DEPTH_TEST
          GL_DEPTH_BITS
          GL_DEPTH_CLEAR_VALUE
          GL_DEPTH_FUNC
          GL_DEPTH_RANGE
          GL_DEPTH_WRITEMASK
          GL_DEPTH_COMPONENT
          GL_LIGHTING
          GL_LIGHT0
          GL_LIGHT1
          GL_LIGHT2
          GL_LIGHT3
          GL_LIGHT4
          GL_LIGHT5
          GL_LIGHT6
          GL_LIGHT7
          GL_SPOT_EXPONENT
          GL_SPOT_CUTOFF
          GL_CONSTANT_ATTENUATION
          GL_LINEAR_ATTENUATION
          GL_QUADRATIC_ATTENUATION
          GL_AMBIENT
          GL_DIFFUSE
          GL_SPECULAR
          GL_SHININESS
          GL_EMISSION
          GL_POSITION
          GL_SPOT_DIRECTION
          GL_AMBIENT_AND_DIFFUSE
          GL_COLOR_INDEXES
          GL_LIGHT_MODEL_TWO_SIDE
          GL_LIGHT_MODEL_LOCAL_VIEWER
          GL_LIGHT_MODEL_AMBIENT
          GL_FRONT_AND_BACK
          GL_SHADE_MODEL
          GL_FLAT
          GL_SMOOTH
          GL_COLOR_MATERIAL
          GL_COLOR_MATERIAL_FACE
          GL_COLOR_MATERIAL_PARAMETER
          GL_NORMALIZE
          GL_CLIP_PLANE0
          GL_CLIP_PLANE1
          GL_CLIP_PLANE2
          GL_CLIP_PLANE3
          GL_CLIP_PLANE4
          GL_CLIP_PLANE5
          GL_ACCUM_RED_BITS
          GL_ACCUM_GREEN_BITS
          GL_ACCUM_BLUE_BITS
          GL_ACCUM_ALPHA_BITS
          GL_ACCUM_CLEAR_VALUE
          GL_ACCUM
          GL_ADD
          GL_LOAD
          GL_MULT
          GL_RETURN
          GL_ALPHA_TEST
          GL_ALPHA_TEST_REF
          GL_ALPHA_TEST_FUNC
          GL_BLEND
          GL_BLEND_SRC
          GL_BLEND_DST
          GL_ZERO
          GL_ONE
          GL_SRC_COLOR
          GL_ONE_MINUS_SRC_COLOR
          GL_SRC_ALPHA
          GL_ONE_MINUS_SRC_ALPHA
          GL_DST_ALPHA
          GL_ONE_MINUS_DST_ALPHA
          GL_DST_COLOR
          GL_ONE_MINUS_DST_COLOR
          GL_SRC_ALPHA_SATURATE
          GL_FEEDBACK
          GL_RENDER
          GL_SELECT
          GL_2D
          GL_3D
          GL_3D_COLOR
          GL_3D_COLOR_TEXTURE
          GL_4D_COLOR_TEXTURE
          GL_POINT_TOKEN
          GL_LINE_TOKEN
          GL_LINE_RESET_TOKEN
          GL_POLYGON_TOKEN
          GL_BITMAP_TOKEN
          GL_DRAW_PIXEL_TOKEN
          GL_COPY_PIXEL_TOKEN
          GL_PASS_THROUGH_TOKEN
          GL_FEEDBACK_BUFFER_POINTER
          GL_FEEDBACK_BUFFER_SIZE
          GL_FEEDBACK_BUFFER_TYPE
          GL_SELECTION_BUFFER_POINTER
          GL_SELECTION_BUFFER_SIZE
          GL_FOG
          GL_FOG_MODE
          GL_FOG_DENSITY
          GL_FOG_COLOR
          GL_FOG_INDEX
          GL_FOG_START
          GL_FOG_END
          GL_LINEAR
          GL_EXP
          GL_EXP2
          GL_LOGIC_OP
          GL_INDEX_LOGIC_OP
          GL_COLOR_LOGIC_OP
          GL_LOGIC_OP_MODE
          GL_CLEAR
          GL_SET
          GL_COPY
          GL_COPY_INVERTED
          GL_NOOP
          GL_INVERT
          GL_AND
          GL_NAND
          GL_OR
          GL_NOR
          GL_XOR
          GL_EQUIV
          GL_AND_REVERSE
          GL_AND_INVERTED
          GL_OR_REVERSE
          GL_OR_INVERTED
          GL_STENCIL_BITS
          GL_STENCIL_TEST
          GL_STENCIL_CLEAR_VALUE
          GL_STENCIL_FUNC
          GL_STENCIL_VALUE_MASK
          GL_STENCIL_FAIL
          GL_STENCIL_PASS_DEPTH_FAIL
          GL_STENCIL_PASS_DEPTH_PASS
          GL_STENCIL_REF
          GL_STENCIL_WRITEMASK
          GL_STENCIL_INDEX
          GL_KEEP
          GL_REPLACE
          GL_INCR
          GL_DECR
          GL_NONE
          GL_LEFT
          GL_RIGHT
          GL_FRONT_LEFT
          GL_FRONT_RIGHT
          GL_BACK_LEFT
          GL_BACK_RIGHT
          GL_AUX0
          GL_AUX1
          GL_AUX2
          GL_AUX3
          GL_COLOR_INDEX
          GL_RED
          GL_GREEN
          GL_BLUE
          GL_ALPHA
          GL_LUMINANCE
          GL_LUMINANCE_ALPHA
          GL_ALPHA_BITS
          GL_RED_BITS
          GL_GREEN_BITS
          GL_BLUE_BITS
          GL_INDEX_BITS
          GL_SUBPIXEL_BITS
          GL_AUX_BUFFERS
          GL_READ_BUFFER
          GL_DRAW_BUFFER
          GL_DOUBLEBUFFER
          GL_STEREO
          GL_BITMAP
          GL_COLOR
          GL_DEPTH
          GL_STENCIL
          GL_DITHER
          GL_RGB
          GL_RGBA
          GL_MAX_LIST_NESTING
          GL_MAX_EVAL_ORDER
          GL_MAX_LIGHTS
          GL_MAX_CLIP_PLANES
          GL_MAX_TEXTURE_SIZE
          GL_MAX_PIXEL_MAP_TABLE
          GL_MAX_ATTRIB_STACK_DEPTH
          GL_MAX_MODELVIEW_STACK_DEPTH
          GL_MAX_NAME_STACK_DEPTH
          GL_MAX_PROJECTION_STACK_DEPTH
          GL_MAX_TEXTURE_STACK_DEPTH
          GL_MAX_VIEWPORT_DIMS
          GL_MAX_CLIENT_ATTRIB_STACK_DEPTH
          GL_ATTRIB_STACK_DEPTH
          GL_CLIENT_ATTRIB_STACK_DEPTH
          GL_COLOR_CLEAR_VALUE
          GL_COLOR_WRITEMASK
          GL_CURRENT_INDEX
          GL_CURRENT_COLOR
          GL_CURRENT_NORMAL
          GL_CURRENT_RASTER_COLOR
          GL_CURRENT_RASTER_DISTANCE
          GL_CURRENT_RASTER_INDEX
          GL_CURRENT_RASTER_POSITION
          GL_CURRENT_RASTER_TEXTURE_COORDS
          GL_CURRENT_RASTER_POSITION_VALID
          GL_CURRENT_TEXTURE_COORDS
          GL_INDEX_CLEAR_VALUE
          GL_INDEX_MODE
          GL_INDEX_WRITEMASK
          GL_MODELVIEW_MATRIX
          GL_MODELVIEW_STACK_DEPTH
          GL_NAME_STACK_DEPTH
          GL_PROJECTION_MATRIX
          GL_PROJECTION_STACK_DEPTH
          GL_RENDER_MODE
          GL_RGBA_MODE
          GL_TEXTURE_MATRIX
          GL_TEXTURE_STACK_DEPTH
          GL_VIEWPORT
          GL_AUTO_NORMAL
          GL_MAP1_COLOR_4
          GL_MAP1_INDEX
          GL_MAP1_NORMAL
          GL_MAP1_TEXTURE_COORD_1
          GL_MAP1_TEXTURE_COORD_2
          GL_MAP1_TEXTURE_COORD_3
          GL_MAP1_TEXTURE_COORD_4
          GL_MAP1_VERTEX_3
          GL_MAP1_VERTEX_4
          GL_MAP2_COLOR_4
          GL_MAP2_INDEX
          GL_MAP2_NORMAL
          GL_MAP2_TEXTURE_COORD_1
          GL_MAP2_TEXTURE_COORD_2
          GL_MAP2_TEXTURE_COORD_3
          GL_MAP2_TEXTURE_COORD_4
          GL_MAP2_VERTEX_3
          GL_MAP2_VERTEX_4
          GL_MAP1_GRID_DOMAIN
          GL_MAP1_GRID_SEGMENTS
          GL_MAP2_GRID_DOMAIN
          GL_MAP2_GRID_SEGMENTS
          GL_COEFF
          GL_ORDER
          GL_DOMAIN
          GL_PERSPECTIVE_CORRECTION_HINT
          GL_POINT_SMOOTH_HINT
          GL_LINE_SMOOTH_HINT
          GL_POLYGON_SMOOTH_HINT
          GL_FOG_HINT
          GL_DONT_CARE
          GL_FASTEST
          GL_NICEST
          GL_SCISSOR_BOX
          GL_SCISSOR_TEST
          GL_MAP_COLOR
          GL_MAP_STENCIL
          GL_INDEX_SHIFT
          GL_INDEX_OFFSET
          GL_RED_SCALE
          GL_RED_BIAS
          GL_GREEN_SCALE
          GL_GREEN_BIAS
          GL_BLUE_SCALE
          GL_BLUE_BIAS
          GL_ALPHA_SCALE
          GL_ALPHA_BIAS
          GL_DEPTH_SCALE
          GL_DEPTH_BIAS
          GL_PIXEL_MAP_S_TO_S_SIZE
          GL_PIXEL_MAP_I_TO_I_SIZE
          GL_PIXEL_MAP_I_TO_R_SIZE
          GL_PIXEL_MAP_I_TO_G_SIZE
          GL_PIXEL_MAP_I_TO_B_SIZE
          GL_PIXEL_MAP_I_TO_A_SIZE
          GL_PIXEL_MAP_R_TO_R_SIZE
          GL_PIXEL_MAP_G_TO_G_SIZE
          GL_PIXEL_MAP_B_TO_B_SIZE
          GL_PIXEL_MAP_A_TO_A_SIZE
          GL_PIXEL_MAP_S_TO_S
          GL_PIXEL_MAP_I_TO_I
          GL_PIXEL_MAP_I_TO_R
          GL_PIXEL_MAP_I_TO_G
          GL_PIXEL_MAP_I_TO_B
          GL_PIXEL_MAP_I_TO_A
          GL_PIXEL_MAP_R_TO_R
          GL_PIXEL_MAP_G_TO_G
          GL_PIXEL_MAP_B_TO_B
          GL_PIXEL_MAP_A_TO_A
          GL_PACK_ALIGNMENT
          GL_PACK_LSB_FIRST
          GL_PACK_ROW_LENGTH
          GL_PACK_SKIP_PIXELS
          GL_PACK_SKIP_ROWS
          GL_PACK_SWAP_BYTES
          GL_UNPACK_ALIGNMENT
          GL_UNPACK_LSB_FIRST
          GL_UNPACK_ROW_LENGTH
          GL_UNPACK_SKIP_PIXELS
          GL_UNPACK_SKIP_ROWS
          GL_UNPACK_SWAP_BYTES
          GL_ZOOM_X
          GL_ZOOM_Y
          GL_TEXTURE_ENV
          GL_TEXTURE_ENV_MODE
          GL_TEXTURE_1D
          GL_TEXTURE_2D
          GL_TEXTURE_WRAP_S
          GL_TEXTURE_WRAP_T
          GL_TEXTURE_MAG_FILTER
          GL_TEXTURE_MIN_FILTER
          GL_TEXTURE_ENV_COLOR
          GL_TEXTURE_GEN_S
          GL_TEXTURE_GEN_T
          GL_TEXTURE_GEN_MODE
          GL_TEXTURE_BORDER_COLOR
          GL_TEXTURE_WIDTH
          GL_TEXTURE_HEIGHT
          GL_TEXTURE_BORDER
          GL_TEXTURE_COMPONENTS
          GL_TEXTURE_RED_SIZE
          GL_TEXTURE_GREEN_SIZE
          GL_TEXTURE_BLUE_SIZE
          GL_TEXTURE_ALPHA_SIZE
          GL_TEXTURE_LUMINANCE_SIZE
          GL_TEXTURE_INTENSITY_SIZE
          GL_NEAREST_MIPMAP_NEAREST
          GL_NEAREST_MIPMAP_LINEAR
          GL_LINEAR_MIPMAP_NEAREST
          GL_LINEAR_MIPMAP_LINEAR
          GL_OBJECT_LINEAR
          GL_OBJECT_PLANE
          GL_EYE_LINEAR
          GL_EYE_PLANE
          GL_SPHERE_MAP
          GL_DECAL
          GL_MODULATE
          GL_NEAREST
          GL_REPEAT
          GL_CLAMP
          GL_S
          GL_T
          GL_R
          GL_Q
          GL_TEXTURE_GEN_R
          GL_TEXTURE_GEN_Q
          GL_VENDOR
          GL_RENDERER
          GL_VERSION
          GL_EXTENSIONS
          GL_NO_ERROR
          GL_INVALID_ENUM
          GL_INVALID_VALUE
          GL_INVALID_OPERATION
          GL_STACK_OVERFLOW
          GL_STACK_UNDERFLOW
          GL_OUT_OF_MEMORY
          GL_CURRENT_BIT
          GL_POINT_BIT
          GL_LINE_BIT
          GL_POLYGON_BIT
          GL_POLYGON_STIPPLE_BIT
          GL_PIXEL_MODE_BIT
          GL_LIGHTING_BIT
          GL_FOG_BIT
          GL_DEPTH_BUFFER_BIT
          GL_ACCUM_BUFFER_BIT
          GL_STENCIL_BUFFER_BIT
          GL_VIEWPORT_BIT
          GL_TRANSFORM_BIT
          GL_ENABLE_BIT
          GL_COLOR_BUFFER_BIT
          GL_HINT_BIT
          GL_EVAL_BIT
          GL_LIST_BIT
          GL_TEXTURE_BIT
          GL_SCISSOR_BIT
          GL_ALL_ATTRIB_BITS
          GL_PROXY_TEXTURE_1D
          GL_PROXY_TEXTURE_2D
          GL_TEXTURE_PRIORITY
          GL_TEXTURE_RESIDENT
          GL_TEXTURE_BINDING_1D
          GL_TEXTURE_BINDING_2D
          GL_TEXTURE_INTERNAL_FORMAT
          GL_ALPHA4
          GL_ALPHA8
          GL_ALPHA12
          GL_ALPHA16
          GL_LUMINANCE4
          GL_LUMINANCE8
          GL_LUMINANCE12
          GL_LUMINANCE16
          GL_LUMINANCE4_ALPHA4
          GL_LUMINANCE6_ALPHA2
          GL_LUMINANCE8_ALPHA8
          GL_LUMINANCE12_ALPHA4
          GL_LUMINANCE12_ALPHA12
          GL_LUMINANCE16_ALPHA16
          GL_INTENSITY
          GL_INTENSITY4
          GL_INTENSITY8
          GL_INTENSITY12
          GL_INTENSITY16
          GL_R3_G3_B2
          GL_RGB4
          GL_RGB5
          GL_RGB8
          GL_RGB10
          GL_RGB12
          GL_RGB16
          GL_RGBA2
          GL_RGBA4
          GL_RGB5_A1
          GL_RGBA8
          GL_RGB10_A2
          GL_RGBA12
          GL_RGBA16
          GL_CLIENT_PIXEL_STORE_BIT
          GL_CLIENT_VERTEX_ARRAY_BIT
          GL_ALL_CLIENT_ATTRIB_BITS
          GL_CLIENT_ALL_ATTRIB_BITS
          GL_RESCALE_NORMAL
          GL_CLAMP_TO_EDGE
          GL_MAX_ELEMENTS_VERTICES
          GL_MAX_ELEMENTS_INDICES
          GL_BGR
          GL_BGRA
          GL_UNSIGNED_BYTE_3_3_2
          GL_UNSIGNED_BYTE_2_3_3_REV
          GL_UNSIGNED_SHORT_5_6_5
          GL_UNSIGNED_SHORT_5_6_5_REV
          GL_UNSIGNED_SHORT_4_4_4_4
          GL_UNSIGNED_SHORT_4_4_4_4_REV
          GL_UNSIGNED_SHORT_5_5_5_1
          GL_UNSIGNED_SHORT_1_5_5_5_REV
          GL_UNSIGNED_INT_8_8_8_8
          GL_UNSIGNED_INT_8_8_8_8_REV
          GL_UNSIGNED_INT_10_10_10_2
          GL_UNSIGNED_INT_2_10_10_10_REV
          GL_LIGHT_MODEL_COLOR_CONTROL
          GL_SINGLE_COLOR
          GL_SEPARATE_SPECULAR_COLOR
          GL_TEXTURE_MIN_LOD
          GL_TEXTURE_MAX_LOD
          GL_TEXTURE_BASE_LEVEL
          GL_TEXTURE_MAX_LEVEL
          GL_SMOOTH_POINT_SIZE_RANGE
          GL_SMOOTH_POINT_SIZE_GRANULARITY
          GL_SMOOTH_LINE_WIDTH_RANGE
          GL_SMOOTH_LINE_WIDTH_GRANULARITY
          GL_ALIASED_POINT_SIZE_RANGE
          GL_ALIASED_LINE_WIDTH_RANGE
          GL_PACK_SKIP_IMAGES
          GL_PACK_IMAGE_HEIGHT
          GL_UNPACK_SKIP_IMAGES
          GL_UNPACK_IMAGE_HEIGHT
          GL_TEXTURE_3D
          GL_PROXY_TEXTURE_3D
          GL_TEXTURE_DEPTH
          GL_TEXTURE_WRAP_R
          GL_MAX_3D_TEXTURE_SIZE
          GL_TEXTURE_BINDING_3D
          GL_CONSTANT_COLOR
          GL_ONE_MINUS_CONSTANT_COLOR
          GL_CONSTANT_ALPHA
          GL_ONE_MINUS_CONSTANT_ALPHA
          GL_COLOR_TABLE
          GL_POST_CONVOLUTION_COLOR_TABLE
          GL_POST_COLOR_MATRIX_COLOR_TABLE
          GL_PROXY_COLOR_TABLE
          GL_PROXY_POST_CONVOLUTION_COLOR_TABLE
          GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE
          GL_COLOR_TABLE_SCALE
          GL_COLOR_TABLE_BIAS
          GL_COLOR_TABLE_FORMAT
          GL_COLOR_TABLE_WIDTH
          GL_COLOR_TABLE_RED_SIZE
          GL_COLOR_TABLE_GREEN_SIZE
          GL_COLOR_TABLE_BLUE_SIZE
          GL_COLOR_TABLE_ALPHA_SIZE
          GL_COLOR_TABLE_LUMINANCE_SIZE
          GL_COLOR_TABLE_INTENSITY_SIZE
          GL_CONVOLUTION_1D
          GL_CONVOLUTION_2D
          GL_SEPARABLE_2D
          GL_CONVOLUTION_BORDER_MODE
          GL_CONVOLUTION_FILTER_SCALE
          GL_CONVOLUTION_FILTER_BIAS
          GL_REDUCE
          GL_CONVOLUTION_FORMAT
          GL_CONVOLUTION_WIDTH
          GL_CONVOLUTION_HEIGHT
          GL_MAX_CONVOLUTION_WIDTH
          GL_MAX_CONVOLUTION_HEIGHT
          GL_POST_CONVOLUTION_RED_SCALE
          GL_POST_CONVOLUTION_GREEN_SCALE
          GL_POST_CONVOLUTION_BLUE_SCALE
          GL_POST_CONVOLUTION_ALPHA_SCALE
          GL_POST_CONVOLUTION_RED_BIAS
          GL_POST_CONVOLUTION_GREEN_BIAS
          GL_POST_CONVOLUTION_BLUE_BIAS
          GL_POST_CONVOLUTION_ALPHA_BIAS
          GL_CONSTANT_BORDER
          GL_REPLICATE_BORDER
          GL_CONVOLUTION_BORDER_COLOR
          GL_COLOR_MATRIX
          GL_COLOR_MATRIX_STACK_DEPTH
          GL_MAX_COLOR_MATRIX_STACK_DEPTH
          GL_POST_COLOR_MATRIX_RED_SCALE
          GL_POST_COLOR_MATRIX_GREEN_SCALE
          GL_POST_COLOR_MATRIX_BLUE_SCALE
          GL_POST_COLOR_MATRIX_ALPHA_SCALE
          GL_POST_COLOR_MATRIX_RED_BIAS
          GL_POST_COLOR_MATRIX_GREEN_BIAS
          GL_POST_COLOR_MATRIX_BLUE_BIAS
          GL_POST_COLOR_MATRIX_ALPHA_BIAS
          GL_HISTOGRAM
          GL_PROXY_HISTOGRAM
          GL_HISTOGRAM_WIDTH
          GL_HISTOGRAM_FORMAT
          GL_HISTOGRAM_RED_SIZE
          GL_HISTOGRAM_GREEN_SIZE
          GL_HISTOGRAM_BLUE_SIZE
          GL_HISTOGRAM_ALPHA_SIZE
          GL_HISTOGRAM_LUMINANCE_SIZE
          GL_HISTOGRAM_SINK
          GL_MINMAX
          GL_MINMAX_FORMAT
          GL_MINMAX_SINK
          GL_TABLE_TOO_LARGE
          GL_BLEND_EQUATION
          GL_MIN
          GL_MAX
          GL_FUNC_ADD
          GL_FUNC_SUBTRACT
          GL_FUNC_REVERSE_SUBTRACT
          GL_BLEND_COLOR
          GL_TEXTURE0
          GL_TEXTURE1
          GL_TEXTURE2
          GL_TEXTURE3
          GL_TEXTURE4
          GL_TEXTURE5
          GL_TEXTURE6
          GL_TEXTURE7
          GL_TEXTURE8
          GL_TEXTURE9
          GL_TEXTURE10
          GL_TEXTURE11
          GL_TEXTURE12
          GL_TEXTURE13
          GL_TEXTURE14
          GL_TEXTURE15
          GL_TEXTURE16
          GL_TEXTURE17
          GL_TEXTURE18
          GL_TEXTURE19
          GL_TEXTURE20
          GL_TEXTURE21
          GL_TEXTURE22
          GL_TEXTURE23
          GL_TEXTURE24
          GL_TEXTURE25
          GL_TEXTURE26
          GL_TEXTURE27
          GL_TEXTURE28
          GL_TEXTURE29
          GL_TEXTURE30
          GL_TEXTURE31
          GL_ACTIVE_TEXTURE
          GL_CLIENT_ACTIVE_TEXTURE
          GL_MAX_TEXTURE_UNITS
          GL_NORMAL_MAP
          GL_REFLECTION_MAP
          GL_TEXTURE_CUBE_MAP
          GL_TEXTURE_BINDING_CUBE_MAP
          GL_TEXTURE_CUBE_MAP_POSITIVE_X
          GL_TEXTURE_CUBE_MAP_NEGATIVE_X
          GL_TEXTURE_CUBE_MAP_POSITIVE_Y
          GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
          GL_TEXTURE_CUBE_MAP_POSITIVE_Z
          GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
          GL_PROXY_TEXTURE_CUBE_MAP
          GL_MAX_CUBE_MAP_TEXTURE_SIZE
          GL_COMPRESSED_ALPHA
          GL_COMPRESSED_LUMINANCE
          GL_COMPRESSED_LUMINANCE_ALPHA
          GL_COMPRESSED_INTENSITY
          GL_COMPRESSED_RGB
          GL_COMPRESSED_RGBA
          GL_TEXTURE_COMPRESSION_HINT
          GL_TEXTURE_COMPRESSED_IMAGE_SIZE
          GL_TEXTURE_COMPRESSED
          GL_NUM_COMPRESSED_TEXTURE_FORMATS
          GL_COMPRESSED_TEXTURE_FORMATS
          GL_MULTISAMPLE
          GL_SAMPLE_ALPHA_TO_COVERAGE
          GL_SAMPLE_ALPHA_TO_ONE
          GL_SAMPLE_COVERAGE
          GL_SAMPLE_BUFFERS
          GL_SAMPLES
          GL_SAMPLE_COVERAGE_VALUE
          GL_SAMPLE_COVERAGE_INVERT
          GL_MULTISAMPLE_BIT
          GL_TRANSPOSE_MODELVIEW_MATRIX
          GL_TRANSPOSE_PROJECTION_MATRIX
          GL_TRANSPOSE_TEXTURE_MATRIX
          GL_TRANSPOSE_COLOR_MATRIX
          GL_COMBINE
          GL_COMBINE_RGB
          GL_COMBINE_ALPHA
          GL_SOURCE0_RGB
          GL_SOURCE1_RGB
          GL_SOURCE2_RGB
          GL_SOURCE0_ALPHA
          GL_SOURCE1_ALPHA
          GL_SOURCE2_ALPHA
          GL_OPERAND0_RGB
          GL_OPERAND1_RGB
          GL_OPERAND2_RGB
          GL_OPERAND0_ALPHA
          GL_OPERAND1_ALPHA
          GL_OPERAND2_ALPHA
          GL_RGB_SCALE
          GL_ADD_SIGNED
          GL_INTERPOLATE
          GL_SUBTRACT
          GL_CONSTANT
          GL_PRIMARY_COLOR
          GL_PREVIOUS
          GL_DOT3_RGB
          GL_DOT3_RGBA
          GL_CLAMP_TO_BORDER
          GL_TEXTURE0_ARB
          GL_TEXTURE1_ARB
          GL_TEXTURE2_ARB
          GL_TEXTURE3_ARB
          GL_TEXTURE4_ARB
          GL_TEXTURE5_ARB
          GL_TEXTURE6_ARB
          GL_TEXTURE7_ARB
          GL_TEXTURE8_ARB
          GL_TEXTURE9_ARB
          GL_TEXTURE10_ARB
          GL_TEXTURE11_ARB
          GL_TEXTURE12_ARB
          GL_TEXTURE13_ARB
          GL_TEXTURE14_ARB
          GL_TEXTURE15_ARB
          GL_TEXTURE16_ARB
          GL_TEXTURE17_ARB
          GL_TEXTURE18_ARB
          GL_TEXTURE19_ARB
          GL_TEXTURE20_ARB
          GL_TEXTURE21_ARB
          GL_TEXTURE22_ARB
          GL_TEXTURE23_ARB
          GL_TEXTURE24_ARB
          GL_TEXTURE25_ARB
          GL_TEXTURE26_ARB
          GL_TEXTURE27_ARB
          GL_TEXTURE28_ARB
          GL_TEXTURE29_ARB
          GL_TEXTURE30_ARB
          GL_TEXTURE31_ARB
          GL_ACTIVE_TEXTURE_ARB
          GL_CLIENT_ACTIVE_TEXTURE_ARB
          GL_MAX_TEXTURE_UNITS_ARB
          glClearIndex
          glClearColor
          glClear
          glIndexMask
          glColorMask
          glAlphaFunc
          glBlendFunc
          glLogicOp
          glCullFace
          glFrontFace
          glPointSize
          glLineWidth
          glLineStipple
          glPolygonMode
          glPolygonOffset
          glPolygonStipple
          glGetPolygonStipple
          glEdgeFlag
          glEdgeFlagv
          glScissor
          glClipPlane
          glGetClipPlane
          glDrawBuffer
          glReadBuffer
          glEnable
          glDisable
          glIsEnabled
          glEnableClientState
          glDisableClientState
          glGetBooleanv
          glGetDoublev
          glGetFloatv
          glGetIntegerv
          glPushAttrib
          glPopAttrib
          glPushClientAttrib
          glPopClientAttrib
          glRenderMode
          glGetError
          glGetString
          glFinish
          glFlush
          glHint
          glClearDepth
          glDepthFunc
          glDepthMask
          glDepthRange
          glClearAccum
          glAccum
          glMatrixMode
          glOrtho
          glFrustum
          glViewport
          glPushMatrix
          glPopMatrix
          glLoadIdentity
          glLoadMatrixd
          glLoadMatrixf
          glMultMatrixd
          glMultMatrixf
          glRotated
          glRotatef
          glScaled
          glScalef
          glTranslated
          glTranslatef
          glIsList
          glDeleteLists
          glGenLists
          glNewList
          glEndList
          glCallList
          glCallLists
          glListBase
          glBegin
          glEnd
          glVertex2d
          glVertex2f
          glVertex2i
          glVertex2s
          glVertex3d
          glVertex3f
          glVertex3i
          glVertex3s
          glVertex4d
          glVertex4f
          glVertex4i
          glVertex4s
          glVertex2dv
          glVertex2fv
          glVertex2iv
          glVertex2sv
          glVertex3dv
          glVertex3fv
          glVertex3iv
          glVertex3sv
          glVertex4dv
          glVertex4fv
          glVertex4iv
          glVertex4sv
          glNormal3b
          glNormal3d
          glNormal3f
          glNormal3i
          glNormal3s
          glNormal3bv
          glNormal3dv
          glNormal3fv
          glNormal3iv
          glNormal3sv
          glIndexd
          glIndexf
          glIndexi
          glIndexs
          glIndexub
          glIndexdv
          glIndexfv
          glIndexiv
          glIndexsv
          glIndexubv
          glColor3b
          glColor3d
          glColor3f
          glColor3i
          glColor3s
          glColor3ub
          glColor3ui
          glColor3us
          glColor4b
          glColor4d
          glColor4f
          glColor4i
          glColor4s
          glColor4ub
          glColor4ui
          glColor4us
          glColor3bv
          glColor3dv
          glColor3fv
          glColor3iv
          glColor3sv
          glColor3ubv
          glColor3uiv
          glColor3usv
          glColor4bv
          glColor4dv
          glColor4fv
          glColor4iv
          glColor4sv
          glColor4ubv
          glColor4uiv
          glColor4usv
          glTexCoord1d
          glTexCoord1f
          glTexCoord1i
          glTexCoord1s
          glTexCoord2d
          glTexCoord2f
          glTexCoord2i
          glTexCoord2s
          glTexCoord3d
          glTexCoord3f
          glTexCoord3i
          glTexCoord3s
          glTexCoord4d
          glTexCoord4f
          glTexCoord4i
          glTexCoord4s
          glTexCoord1dv
          glTexCoord1fv
          glTexCoord1iv
          glTexCoord1sv
          glTexCoord2dv
          glTexCoord2fv
          glTexCoord2iv
          glTexCoord2sv
          glTexCoord3dv
          glTexCoord3fv
          glTexCoord3iv
          glTexCoord3sv
          glTexCoord4dv
          glTexCoord4fv
          glTexCoord4iv
          glTexCoord4sv
          glRasterPos2d
          glRasterPos2f
          glRasterPos2i
          glRasterPos2s
          glRasterPos3d
          glRasterPos3f
          glRasterPos3i
          glRasterPos3s
          glRasterPos4d
          glRasterPos4f
          glRasterPos4i
          glRasterPos4s
          glRasterPos2dv
          glRasterPos2fv
          glRasterPos2iv
          glRasterPos2sv
          glRasterPos3dv
          glRasterPos3fv
          glRasterPos3iv
          glRasterPos3sv
          glRasterPos4dv
          glRasterPos4fv
          glRasterPos4iv
          glRasterPos4sv
          glRectd
          glRectf
          glRecti
          glRects
          glRectdv
          glRectfv
          glRectiv
          glRectsv
          glVertexPointer
          glNormalPointer
          glColorPointer
          glIndexPointer
          glTexCoordPointer
          glEdgeFlagPointer
          glGetPointerv
          glArrayElement
          glDrawArrays
          glDrawElements
          glInterleavedArrays
          glShadeModel
          glLightf
          glLighti
          glLightfv
          glLightiv
          glGetLightfv
          glGetLightiv
          glLightModelf
          glLightModeli
          glLightModelfv
          glLightModeliv
          glMaterialf
          glMateriali
          glMaterialfv
          glMaterialiv
          glGetMaterialfv
          glGetMaterialiv
          glColorMaterial
          glPixelZoom
          glPixelStoref
          glPixelStorei
          glPixelTransferf
          glPixelTransferi
          glPixelMapfv
          glPixelMapuiv
          glPixelMapusv
          glGetPixelMapfv
          glGetPixelMapuiv
          glGetPixelMapusv
          glBitmap
          glReadPixels
          glDrawPixels
          glCopyPixels
          glStencilFunc
          glStencilMask
          glStencilOp
          glClearStencil
          glTexGend
          glTexGenf
          glTexGeni
          glTexGendv
          glTexGenfv
          glTexGeniv
          glGetTexGendv
          glGetTexGenfv
          glGetTexGeniv
          glTexEnvf
          glTexEnvi
          glTexEnvfv
          glTexEnviv
          glGetTexEnvfv
          glGetTexEnviv
          glTexParameterf
          glTexParameteri
          glTexParameterfv
          glTexParameteriv
          glGetTexParameterfv
          glGetTexParameteriv
          glGetTexLevelParameterfv
          glGetTexLevelParameteriv
          glTexImage1D
          glTexImage2D
          glGetTexImage
          glGenTextures
          glDeleteTextures
          glBindTexture
          glPrioritizeTextures
          glAreTexturesResident
          glIsTexture
          glTexSubImage1D
          glTexSubImage2D
          glCopyTexImage1D
          glCopyTexImage2D
          glCopyTexSubImage1D
          glCopyTexSubImage2D
          glMap1d
          glMap1f
          glMap2d
          glMap2f
          glGetMapdv
          glGetMapfv
          glGetMapiv
          glEvalCoord1d
          glEvalCoord1f
          glEvalCoord1dv
          glEvalCoord1fv
          glEvalCoord2d
          glEvalCoord2f
          glEvalCoord2dv
          glEvalCoord2fv
          glMapGrid1d
          glMapGrid1f
          glMapGrid2d
          glMapGrid2f
          glEvalPoint1
          glEvalPoint2
          glEvalMesh1
          glEvalMesh2
          glFogf
          glFogi
          glFogfv
          glFogiv
          glFeedbackBuffer
          glPassThrough
          glSelectBuffer
          glInitNames
          glLoadName
          glPushName
          glPopName
          glDrawRangeElements
          glTexImage3D
          glTexSubImage3D
          glCopyTexSubImage3D
          glColorTable
          glColorSubTable
          glColorTableParameteriv
          glColorTableParameterfv
          glCopyColorSubTable
          glCopyColorTable
          glGetColorTable
          glGetColorTableParameterfv
          glGetColorTableParameteriv
          glBlendEquation
          glBlendColor
          glHistogram
          glResetHistogram
          glGetHistogram
          glGetHistogramParameterfv
          glGetHistogramParameteriv
          glMinmax
          glResetMinmax
          glGetMinmax
          glGetMinmaxParameterfv
          glGetMinmaxParameteriv
          glConvolutionFilter1D
          glConvolutionFilter2D
          glConvolutionParameterf
          glConvolutionParameterfv
          glConvolutionParameteri
          glConvolutionParameteriv
          glCopyConvolutionFilter1D
          glCopyConvolutionFilter2D
          glGetConvolutionFilter
          glGetConvolutionParameterfv
          glGetConvolutionParameteriv
          glSeparableFilter2D
          glGetSeparableFilter
          glActiveTexture
          glClientActiveTexture
          glCompressedTexImage1D
          glCompressedTexImage2D
          glCompressedTexImage3D
          glCompressedTexSubImage1D
          glCompressedTexSubImage2D
          glCompressedTexSubImage3D
          glGetCompressedTexImage
          glMultiTexCoord1d
          glMultiTexCoord1dv
          glMultiTexCoord1f
          glMultiTexCoord1fv
          glMultiTexCoord1i
          glMultiTexCoord1iv
          glMultiTexCoord1s
          glMultiTexCoord1sv
          glMultiTexCoord2d
          glMultiTexCoord2dv
          glMultiTexCoord2f
          glMultiTexCoord2fv
          glMultiTexCoord2i
          glMultiTexCoord2iv
          glMultiTexCoord2s
          glMultiTexCoord2sv
          glMultiTexCoord3d
          glMultiTexCoord3dv
          glMultiTexCoord3f
          glMultiTexCoord3fv
          glMultiTexCoord3i
          glMultiTexCoord3iv
          glMultiTexCoord3s
          glMultiTexCoord3sv
          glMultiTexCoord4d
          glMultiTexCoord4dv
          glMultiTexCoord4f
          glMultiTexCoord4fv
          glMultiTexCoord4i
          glMultiTexCoord4iv
          glMultiTexCoord4s
          glMultiTexCoord4sv
          glLoadTransposeMatrixd
          glLoadTransposeMatrixf
          glMultTransposeMatrixd
          glMultTransposeMatrixf
          glSampleCoverage
          glActiveTextureARB
          glClientActiveTextureARB
          glMultiTexCoord1dARB
          glMultiTexCoord1dvARB
          glMultiTexCoord1fARB
          glMultiTexCoord1fvARB
          glMultiTexCoord1iARB
          glMultiTexCoord1ivARB
          glMultiTexCoord1sARB
          glMultiTexCoord1svARB
          glMultiTexCoord2dARB
          glMultiTexCoord2dvARB
          glMultiTexCoord2fARB
          glMultiTexCoord2fvARB
          glMultiTexCoord2iARB
          glMultiTexCoord2ivARB
          glMultiTexCoord2sARB
          glMultiTexCoord2svARB
          glMultiTexCoord3dARB
          glMultiTexCoord3dvARB
          glMultiTexCoord3fARB
          glMultiTexCoord3fvARB
          glMultiTexCoord3iARB
          glMultiTexCoord3ivARB
          glMultiTexCoord3sARB
          glMultiTexCoord3svARB
          glMultiTexCoord4dARB
          glMultiTexCoord4dvARB
          glMultiTexCoord4fARB
          glMultiTexCoord4fvARB
          glMultiTexCoord4iARB
          glMultiTexCoord4ivARB
          glMultiTexCoord4sARB
          glMultiTexCoord4svARB)
  
  (import (chezscheme))

  ;; (define lib-name
  ;;   (cond (on-darwin  "OpenGL.framework/OpenGL")
  ;;         (on-windows "opengl32.dll")
  ;;         (on-linux   "libGL.so.1")
  ;;         (on-freebsd "libGL.so")
  ;;         (on-openbsd "libGL.so.7.3")
  ;;         (on-sunos   "libGL.so.1")
  ;;         (else
  ;;          (assertion-violation #f "can not locate OpenGL library, unknown operating system"))))

  ;; (define lib (load-shared-object lib-name))

  (define no-op (load-shared-object "libGL.so.1"))

  ;;;; Boolean values
  (define GL_FALSE #x0)
  (define GL_TRUE #x1)
  ;;;; Data types
  (define GL_BYTE #x1400)
  (define GL_UNSIGNED_BYTE #x1401)
  (define GL_SHORT #x1402)
  (define GL_UNSIGNED_SHORT #x1403)
  (define GL_INT #x1404)
  (define GL_UNSIGNED_INT #x1405)
  (define GL_FLOAT #x1406)
  (define GL_2_BYTES #x1407)
  (define GL_3_BYTES #x1408)
  (define GL_4_BYTES #x1409)
  (define GL_DOUBLE #x140A)
  ;;;; Primitives
  (define GL_POINTS #x0000)
  (define GL_LINES #x0001)
  (define GL_LINE_LOOP #x0002)
  (define GL_LINE_STRIP #x0003)
  (define GL_TRIANGLES #x0004)
  (define GL_TRIANGLE_STRIP #x0005)
  (define GL_TRIANGLE_FAN #x0006)
  (define GL_QUADS #x0007)
  (define GL_QUAD_STRIP #x0008)
  (define GL_POLYGON #x0009)
  ;;;; Vertex Arrays
  (define GL_VERTEX_ARRAY #x8074)
  (define GL_NORMAL_ARRAY #x8075)
  (define GL_COLOR_ARRAY #x8076)
  (define GL_INDEX_ARRAY #x8077)
  (define GL_TEXTURE_COORD_ARRAY #x8078)
  (define GL_EDGE_FLAG_ARRAY #x8079)
  (define GL_VERTEX_ARRAY_SIZE #x807A)
  (define GL_VERTEX_ARRAY_TYPE #x807B)
  (define GL_VERTEX_ARRAY_STRIDE #x807C)
  (define GL_NORMAL_ARRAY_TYPE #x807E)
  (define GL_NORMAL_ARRAY_STRIDE #x807F)
  (define GL_COLOR_ARRAY_SIZE #x8081)
  (define GL_COLOR_ARRAY_TYPE #x8082)
  (define GL_COLOR_ARRAY_STRIDE #x8083)
  (define GL_INDEX_ARRAY_TYPE #x8085)
  (define GL_INDEX_ARRAY_STRIDE #x8086)
  (define GL_TEXTURE_COORD_ARRAY_SIZE #x8088)
  (define GL_TEXTURE_COORD_ARRAY_TYPE #x8089)
  (define GL_TEXTURE_COORD_ARRAY_STRIDE #x808A)
  (define GL_EDGE_FLAG_ARRAY_STRIDE #x808C)
  (define GL_VERTEX_ARRAY_POINTER #x808E)
  (define GL_NORMAL_ARRAY_POINTER #x808F)
  (define GL_COLOR_ARRAY_POINTER #x8090)
  (define GL_INDEX_ARRAY_POINTER #x8091)
  (define GL_TEXTURE_COORD_ARRAY_POINTER #x8092)
  (define GL_EDGE_FLAG_ARRAY_POINTER #x8093)
  (define GL_V2F #x2A20)
  (define GL_V3F #x2A21)
  (define GL_C4UB_V2F #x2A22)
  (define GL_C4UB_V3F #x2A23)
  (define GL_C3F_V3F #x2A24)
  (define GL_N3F_V3F #x2A25)
  (define GL_C4F_N3F_V3F #x2A26)
  (define GL_T2F_V3F #x2A27)
  (define GL_T4F_V4F #x2A28)
  (define GL_T2F_C4UB_V3F #x2A29)
  (define GL_T2F_C3F_V3F #x2A2A)
  (define GL_T2F_N3F_V3F #x2A2B)
  (define GL_T2F_C4F_N3F_V3F #x2A2C)
  (define GL_T4F_C4F_N3F_V4F #x2A2D)
  ;;;; Matrix Mode
  (define GL_MATRIX_MODE #x0BA0)
  (define GL_MODELVIEW #x1700)
  (define GL_PROJECTION #x1701)
  (define GL_TEXTURE #x1702)
  ;;;; Points
  (define GL_POINT_SMOOTH #x0B10)
  (define GL_POINT_SIZE #x0B11)
  (define GL_POINT_SIZE_GRANULARITY #x0B13)
  (define GL_POINT_SIZE_RANGE #x0B12)
  ;;;; Lines
  (define GL_LINE_SMOOTH #x0B20)
  (define GL_LINE_STIPPLE #x0B24)
  (define GL_LINE_STIPPLE_PATTERN #x0B25)
  (define GL_LINE_STIPPLE_REPEAT #x0B26)
  (define GL_LINE_WIDTH #x0B21)
  (define GL_LINE_WIDTH_GRANULARITY #x0B23)
  (define GL_LINE_WIDTH_RANGE #x0B22)
  ;;;; Polygons
  (define GL_POINT #x1B00)
  (define GL_LINE #x1B01)
  (define GL_FILL #x1B02)
  (define GL_CW #x0900)
  (define GL_CCW #x0901)
  (define GL_FRONT #x0404)
  (define GL_BACK #x0405)
  (define GL_POLYGON_MODE #x0B40)
  (define GL_POLYGON_SMOOTH #x0B41)
  (define GL_POLYGON_STIPPLE #x0B42)
  (define GL_EDGE_FLAG #x0B43)
  (define GL_CULL_FACE #x0B44)
  (define GL_CULL_FACE_MODE #x0B45)
  (define GL_FRONT_FACE #x0B46)
  (define GL_POLYGON_OFFSET_FACTOR #x8038)
  (define GL_POLYGON_OFFSET_UNITS #x2A00)
  (define GL_POLYGON_OFFSET_POINT #x2A01)
  (define GL_POLYGON_OFFSET_LINE #x2A02)
  (define GL_POLYGON_OFFSET_FILL #x8037)
  ;;;; Display Lists
  (define GL_COMPILE #x1300)
  (define GL_COMPILE_AND_EXECUTE #x1301)
  (define GL_LIST_BASE #x0B32)
  (define GL_LIST_INDEX #x0B33)
  (define GL_LIST_MODE #x0B30)
  ;;;; Depth buffer
  (define GL_NEVER #x0200)
  (define GL_LESS #x0201)
  (define GL_EQUAL #x0202)
  (define GL_LEQUAL #x0203)
  (define GL_GREATER #x0204)
  (define GL_NOTEQUAL #x0205)
  (define GL_GEQUAL #x0206)
  (define GL_ALWAYS #x0207)
  (define GL_DEPTH_TEST #x0B71)
  (define GL_DEPTH_BITS #x0D56)
  (define GL_DEPTH_CLEAR_VALUE #x0B73)
  (define GL_DEPTH_FUNC #x0B74)
  (define GL_DEPTH_RANGE #x0B70)
  (define GL_DEPTH_WRITEMASK #x0B72)
  (define GL_DEPTH_COMPONENT #x1902)
  ;;;; Lighting
  (define GL_LIGHTING #x0B50)
  (define GL_LIGHT0 #x4000)
  (define GL_LIGHT1 #x4001)
  (define GL_LIGHT2 #x4002)
  (define GL_LIGHT3 #x4003)
  (define GL_LIGHT4 #x4004)
  (define GL_LIGHT5 #x4005)
  (define GL_LIGHT6 #x4006)
  (define GL_LIGHT7 #x4007)
  (define GL_SPOT_EXPONENT #x1205)
  (define GL_SPOT_CUTOFF #x1206)
  (define GL_CONSTANT_ATTENUATION #x1207)
  (define GL_LINEAR_ATTENUATION #x1208)
  (define GL_QUADRATIC_ATTENUATION #x1209)
  (define GL_AMBIENT #x1200)
  (define GL_DIFFUSE #x1201)
  (define GL_SPECULAR #x1202)
  (define GL_SHININESS #x1601)
  (define GL_EMISSION #x1600)
  (define GL_POSITION #x1203)
  (define GL_SPOT_DIRECTION #x1204)
  (define GL_AMBIENT_AND_DIFFUSE #x1602)
  (define GL_COLOR_INDEXES #x1603)
  (define GL_LIGHT_MODEL_TWO_SIDE #x0B52)
  (define GL_LIGHT_MODEL_LOCAL_VIEWER #x0B51)
  (define GL_LIGHT_MODEL_AMBIENT #x0B53)
  (define GL_FRONT_AND_BACK #x0408)
  (define GL_SHADE_MODEL #x0B54)
  (define GL_FLAT #x1D00)
  (define GL_SMOOTH #x1D01)
  (define GL_COLOR_MATERIAL #x0B57)
  (define GL_COLOR_MATERIAL_FACE #x0B55)
  (define GL_COLOR_MATERIAL_PARAMETER #x0B56)
  (define GL_NORMALIZE #x0BA1)
  ;;;; User clipping planes
  (define GL_CLIP_PLANE0 #x3000)
  (define GL_CLIP_PLANE1 #x3001)
  (define GL_CLIP_PLANE2 #x3002)
  (define GL_CLIP_PLANE3 #x3003)
  (define GL_CLIP_PLANE4 #x3004)
  (define GL_CLIP_PLANE5 #x3005)
  ;;;; Accumulation buffer
  (define GL_ACCUM_RED_BITS #x0D58)
  (define GL_ACCUM_GREEN_BITS #x0D59)
  (define GL_ACCUM_BLUE_BITS #x0D5A)
  (define GL_ACCUM_ALPHA_BITS #x0D5B)
  (define GL_ACCUM_CLEAR_VALUE #x0B80)
  (define GL_ACCUM #x0100)
  (define GL_ADD #x0104)
  (define GL_LOAD #x0101)
  (define GL_MULT #x0103)
  (define GL_RETURN #x0102)
  ;;;; Alpha testing
  (define GL_ALPHA_TEST #x0BC0)
  (define GL_ALPHA_TEST_REF #x0BC2)
  (define GL_ALPHA_TEST_FUNC #x0BC1)
  ;;;; Blending
  (define GL_BLEND #x0BE2)
  (define GL_BLEND_SRC #x0BE1)
  (define GL_BLEND_DST #x0BE0)
  (define GL_ZERO #x0)
  (define GL_ONE #x1)
  (define GL_SRC_COLOR #x0300)
  (define GL_ONE_MINUS_SRC_COLOR #x0301)
  (define GL_SRC_ALPHA #x0302)
  (define GL_ONE_MINUS_SRC_ALPHA #x0303)
  (define GL_DST_ALPHA #x0304)
  (define GL_ONE_MINUS_DST_ALPHA #x0305)
  (define GL_DST_COLOR #x0306)
  (define GL_ONE_MINUS_DST_COLOR #x0307)
  (define GL_SRC_ALPHA_SATURATE #x0308)
  ;;;; Render Mode
  (define GL_FEEDBACK #x1C01)
  (define GL_RENDER #x1C00)
  (define GL_SELECT #x1C02)
  ;;;; Feedback
  (define GL_2D #x0600)
  (define GL_3D #x0601)
  (define GL_3D_COLOR #x0602)
  (define GL_3D_COLOR_TEXTURE #x0603)
  (define GL_4D_COLOR_TEXTURE #x0604)
  (define GL_POINT_TOKEN #x0701)
  (define GL_LINE_TOKEN #x0702)
  (define GL_LINE_RESET_TOKEN #x0707)
  (define GL_POLYGON_TOKEN #x0703)
  (define GL_BITMAP_TOKEN #x0704)
  (define GL_DRAW_PIXEL_TOKEN #x0705)
  (define GL_COPY_PIXEL_TOKEN #x0706)
  (define GL_PASS_THROUGH_TOKEN #x0700)
  (define GL_FEEDBACK_BUFFER_POINTER #x0DF0)
  (define GL_FEEDBACK_BUFFER_SIZE #x0DF1)
  (define GL_FEEDBACK_BUFFER_TYPE #x0DF2)
  ;;;; Selection
  (define GL_SELECTION_BUFFER_POINTER #x0DF3)
  (define GL_SELECTION_BUFFER_SIZE #x0DF4)
  ;;;; Fog
  (define GL_FOG #x0B60)
  (define GL_FOG_MODE #x0B65)
  (define GL_FOG_DENSITY #x0B62)
  (define GL_FOG_COLOR #x0B66)
  (define GL_FOG_INDEX #x0B61)
  (define GL_FOG_START #x0B63)
  (define GL_FOG_END #x0B64)
  (define GL_LINEAR #x2601)
  (define GL_EXP #x0800)
  (define GL_EXP2 #x0801)
  ;;;; Logic Ops
  (define GL_LOGIC_OP #x0BF1)
  (define GL_INDEX_LOGIC_OP #x0BF1)
  (define GL_COLOR_LOGIC_OP #x0BF2)
  (define GL_LOGIC_OP_MODE #x0BF0)
  (define GL_CLEAR #x1500)
  (define GL_SET #x150F)
  (define GL_COPY #x1503)
  (define GL_COPY_INVERTED #x150C)
  (define GL_NOOP #x1505)
  (define GL_INVERT #x150A)
  (define GL_AND #x1501)
  (define GL_NAND #x150E)
  (define GL_OR #x1507)
  (define GL_NOR #x1508)
  (define GL_XOR #x1506)
  (define GL_EQUIV #x1509)
  (define GL_AND_REVERSE #x1502)
  (define GL_AND_INVERTED #x1504)
  (define GL_OR_REVERSE #x150B)
  (define GL_OR_INVERTED #x150D)
  ;;;; Stencil
  (define GL_STENCIL_BITS #x0D57)
  (define GL_STENCIL_TEST #x0B90)
  (define GL_STENCIL_CLEAR_VALUE #x0B91)
  (define GL_STENCIL_FUNC #x0B92)
  (define GL_STENCIL_VALUE_MASK #x0B93)
  (define GL_STENCIL_FAIL #x0B94)
  (define GL_STENCIL_PASS_DEPTH_FAIL #x0B95)
  (define GL_STENCIL_PASS_DEPTH_PASS #x0B96)
  (define GL_STENCIL_REF #x0B97)
  (define GL_STENCIL_WRITEMASK #x0B98)
  (define GL_STENCIL_INDEX #x1901)
  (define GL_KEEP #x1E00)
  (define GL_REPLACE #x1E01)
  (define GL_INCR #x1E02)
  (define GL_DECR #x1E03)
  ;;;; Buffers, Pixel Drawing/Reading
  (define GL_NONE #x0)
  (define GL_LEFT #x0406)
  (define GL_RIGHT #x0407)
  ;;;;GL_FRONT                  0x0404
  ;;;;GL_BACK                   0x0405
  ;;;;GL_FRONT_AND_BACK         0x0408
  (define GL_FRONT_LEFT #x0400)
  (define GL_FRONT_RIGHT #x0401)
  (define GL_BACK_LEFT #x0402)
  (define GL_BACK_RIGHT #x0403)
  (define GL_AUX0 #x0409)
  (define GL_AUX1 #x040A)
  (define GL_AUX2 #x040B)
  (define GL_AUX3 #x040C)
  (define GL_COLOR_INDEX #x1900)
  (define GL_RED #x1903)
  (define GL_GREEN #x1904)
  (define GL_BLUE #x1905)
  (define GL_ALPHA #x1906)
  (define GL_LUMINANCE #x1909)
  (define GL_LUMINANCE_ALPHA #x190A)
  (define GL_ALPHA_BITS #x0D55)
  (define GL_RED_BITS #x0D52)
  (define GL_GREEN_BITS #x0D53)
  (define GL_BLUE_BITS #x0D54)
  (define GL_INDEX_BITS #x0D51)
  (define GL_SUBPIXEL_BITS #x0D50)
  (define GL_AUX_BUFFERS #x0C00)
  (define GL_READ_BUFFER #x0C02)
  (define GL_DRAW_BUFFER #x0C01)
  (define GL_DOUBLEBUFFER #x0C32)
  (define GL_STEREO #x0C33)
  (define GL_BITMAP #x1A00)
  (define GL_COLOR #x1800)
  (define GL_DEPTH #x1801)
  (define GL_STENCIL #x1802)
  (define GL_DITHER #x0BD0)
  (define GL_RGB #x1907)
  (define GL_RGBA #x1908)
  ;;;; Implementation limits
  (define GL_MAX_LIST_NESTING #x0B31)
  (define GL_MAX_EVAL_ORDER #x0D30)
  (define GL_MAX_LIGHTS #x0D31)
  (define GL_MAX_CLIP_PLANES #x0D32)
  (define GL_MAX_TEXTURE_SIZE #x0D33)
  (define GL_MAX_PIXEL_MAP_TABLE #x0D34)
  (define GL_MAX_ATTRIB_STACK_DEPTH #x0D35)
  (define GL_MAX_MODELVIEW_STACK_DEPTH #x0D36)
  (define GL_MAX_NAME_STACK_DEPTH #x0D37)
  (define GL_MAX_PROJECTION_STACK_DEPTH #x0D38)
  (define GL_MAX_TEXTURE_STACK_DEPTH #x0D39)
  (define GL_MAX_VIEWPORT_DIMS #x0D3A)
  (define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH #x0D3B)
  ;;;; Gets
  (define GL_ATTRIB_STACK_DEPTH #x0BB0)
  (define GL_CLIENT_ATTRIB_STACK_DEPTH #x0BB1)
  (define GL_COLOR_CLEAR_VALUE #x0C22)
  (define GL_COLOR_WRITEMASK #x0C23)
  (define GL_CURRENT_INDEX #x0B01)
  (define GL_CURRENT_COLOR #x0B00)
  (define GL_CURRENT_NORMAL #x0B02)
  (define GL_CURRENT_RASTER_COLOR #x0B04)
  (define GL_CURRENT_RASTER_DISTANCE #x0B09)
  (define GL_CURRENT_RASTER_INDEX #x0B05)
  (define GL_CURRENT_RASTER_POSITION #x0B07)
  (define GL_CURRENT_RASTER_TEXTURE_COORDS #x0B06)
  (define GL_CURRENT_RASTER_POSITION_VALID #x0B08)
  (define GL_CURRENT_TEXTURE_COORDS #x0B03)
  (define GL_INDEX_CLEAR_VALUE #x0C20)
  (define GL_INDEX_MODE #x0C30)
  (define GL_INDEX_WRITEMASK #x0C21)
  (define GL_MODELVIEW_MATRIX #x0BA6)
  (define GL_MODELVIEW_STACK_DEPTH #x0BA3)
  (define GL_NAME_STACK_DEPTH #x0D70)
  (define GL_PROJECTION_MATRIX #x0BA7)
  (define GL_PROJECTION_STACK_DEPTH #x0BA4)
  (define GL_RENDER_MODE #x0C40)
  (define GL_RGBA_MODE #x0C31)
  (define GL_TEXTURE_MATRIX #x0BA8)
  (define GL_TEXTURE_STACK_DEPTH #x0BA5)
  (define GL_VIEWPORT #x0BA2)
  ;;;; Evaluators
  (define GL_AUTO_NORMAL #x0D80)
  (define GL_MAP1_COLOR_4 #x0D90)
  (define GL_MAP1_INDEX #x0D91)
  (define GL_MAP1_NORMAL #x0D92)
  (define GL_MAP1_TEXTURE_COORD_1 #x0D93)
  (define GL_MAP1_TEXTURE_COORD_2 #x0D94)
  (define GL_MAP1_TEXTURE_COORD_3 #x0D95)
  (define GL_MAP1_TEXTURE_COORD_4 #x0D96)
  (define GL_MAP1_VERTEX_3 #x0D97)
  (define GL_MAP1_VERTEX_4 #x0D98)
  (define GL_MAP2_COLOR_4 #x0DB0)
  (define GL_MAP2_INDEX #x0DB1)
  (define GL_MAP2_NORMAL #x0DB2)
  (define GL_MAP2_TEXTURE_COORD_1 #x0DB3)
  (define GL_MAP2_TEXTURE_COORD_2 #x0DB4)
  (define GL_MAP2_TEXTURE_COORD_3 #x0DB5)
  (define GL_MAP2_TEXTURE_COORD_4 #x0DB6)
  (define GL_MAP2_VERTEX_3 #x0DB7)
  (define GL_MAP2_VERTEX_4 #x0DB8)
  (define GL_MAP1_GRID_DOMAIN #x0DD0)
  (define GL_MAP1_GRID_SEGMENTS #x0DD1)
  (define GL_MAP2_GRID_DOMAIN #x0DD2)
  (define GL_MAP2_GRID_SEGMENTS #x0DD3)
  (define GL_COEFF #x0A00)
  (define GL_ORDER #x0A01)
  (define GL_DOMAIN #x0A02)
  ;;;; Hints
  (define GL_PERSPECTIVE_CORRECTION_HINT #x0C50)
  (define GL_POINT_SMOOTH_HINT #x0C51)
  (define GL_LINE_SMOOTH_HINT #x0C52)
  (define GL_POLYGON_SMOOTH_HINT #x0C53)
  (define GL_FOG_HINT #x0C54)
  (define GL_DONT_CARE #x1100)
  (define GL_FASTEST #x1101)
  (define GL_NICEST #x1102)
  ;;;; Scissor box
  (define GL_SCISSOR_BOX #x0C10)
  (define GL_SCISSOR_TEST #x0C11)
  ;;;; Pixel Mode / Transfer
  (define GL_MAP_COLOR #x0D10)
  (define GL_MAP_STENCIL #x0D11)
  (define GL_INDEX_SHIFT #x0D12)
  (define GL_INDEX_OFFSET #x0D13)
  (define GL_RED_SCALE #x0D14)
  (define GL_RED_BIAS #x0D15)
  (define GL_GREEN_SCALE #x0D18)
  (define GL_GREEN_BIAS #x0D19)
  (define GL_BLUE_SCALE #x0D1A)
  (define GL_BLUE_BIAS #x0D1B)
  (define GL_ALPHA_SCALE #x0D1C)
  (define GL_ALPHA_BIAS #x0D1D)
  (define GL_DEPTH_SCALE #x0D1E)
  (define GL_DEPTH_BIAS #x0D1F)
  (define GL_PIXEL_MAP_S_TO_S_SIZE #x0CB1)
  (define GL_PIXEL_MAP_I_TO_I_SIZE #x0CB0)
  (define GL_PIXEL_MAP_I_TO_R_SIZE #x0CB2)
  (define GL_PIXEL_MAP_I_TO_G_SIZE #x0CB3)
  (define GL_PIXEL_MAP_I_TO_B_SIZE #x0CB4)
  (define GL_PIXEL_MAP_I_TO_A_SIZE #x0CB5)
  (define GL_PIXEL_MAP_R_TO_R_SIZE #x0CB6)
  (define GL_PIXEL_MAP_G_TO_G_SIZE #x0CB7)
  (define GL_PIXEL_MAP_B_TO_B_SIZE #x0CB8)
  (define GL_PIXEL_MAP_A_TO_A_SIZE #x0CB9)
  (define GL_PIXEL_MAP_S_TO_S #x0C71)
  (define GL_PIXEL_MAP_I_TO_I #x0C70)
  (define GL_PIXEL_MAP_I_TO_R #x0C72)
  (define GL_PIXEL_MAP_I_TO_G #x0C73)
  (define GL_PIXEL_MAP_I_TO_B #x0C74)
  (define GL_PIXEL_MAP_I_TO_A #x0C75)
  (define GL_PIXEL_MAP_R_TO_R #x0C76)
  (define GL_PIXEL_MAP_G_TO_G #x0C77)
  (define GL_PIXEL_MAP_B_TO_B #x0C78)
  (define GL_PIXEL_MAP_A_TO_A #x0C79)
  (define GL_PACK_ALIGNMENT #x0D05)
  (define GL_PACK_LSB_FIRST #x0D01)
  (define GL_PACK_ROW_LENGTH #x0D02)
  (define GL_PACK_SKIP_PIXELS #x0D04)
  (define GL_PACK_SKIP_ROWS #x0D03)
  (define GL_PACK_SWAP_BYTES #x0D00)
  (define GL_UNPACK_ALIGNMENT #x0CF5)
  (define GL_UNPACK_LSB_FIRST #x0CF1)
  (define GL_UNPACK_ROW_LENGTH #x0CF2)
  (define GL_UNPACK_SKIP_PIXELS #x0CF4)
  (define GL_UNPACK_SKIP_ROWS #x0CF3)
  (define GL_UNPACK_SWAP_BYTES #x0CF0)
  (define GL_ZOOM_X #x0D16)
  (define GL_ZOOM_Y #x0D17)
  ;;;; Texture mapping
  (define GL_TEXTURE_ENV #x2300)
  (define GL_TEXTURE_ENV_MODE #x2200)
  (define GL_TEXTURE_1D #x0DE0)
  (define GL_TEXTURE_2D #x0DE1)
  (define GL_TEXTURE_WRAP_S #x2802)
  (define GL_TEXTURE_WRAP_T #x2803)
  (define GL_TEXTURE_MAG_FILTER #x2800)
  (define GL_TEXTURE_MIN_FILTER #x2801)
  (define GL_TEXTURE_ENV_COLOR #x2201)
  (define GL_TEXTURE_GEN_S #x0C60)
  (define GL_TEXTURE_GEN_T #x0C61)
  (define GL_TEXTURE_GEN_MODE #x2500)
  (define GL_TEXTURE_BORDER_COLOR #x1004)
  (define GL_TEXTURE_WIDTH #x1000)
  (define GL_TEXTURE_HEIGHT #x1001)
  (define GL_TEXTURE_BORDER #x1005)
  (define GL_TEXTURE_COMPONENTS #x1003)
  (define GL_TEXTURE_RED_SIZE #x805C)
  (define GL_TEXTURE_GREEN_SIZE #x805D)
  (define GL_TEXTURE_BLUE_SIZE #x805E)
  (define GL_TEXTURE_ALPHA_SIZE #x805F)
  (define GL_TEXTURE_LUMINANCE_SIZE #x8060)
  (define GL_TEXTURE_INTENSITY_SIZE #x8061)
  (define GL_NEAREST_MIPMAP_NEAREST #x2700)
  (define GL_NEAREST_MIPMAP_LINEAR #x2702)
  (define GL_LINEAR_MIPMAP_NEAREST #x2701)
  (define GL_LINEAR_MIPMAP_LINEAR #x2703)
  (define GL_OBJECT_LINEAR #x2401)
  (define GL_OBJECT_PLANE #x2501)
  (define GL_EYE_LINEAR #x2400)
  (define GL_EYE_PLANE #x2502)
  (define GL_SPHERE_MAP #x2402)
  (define GL_DECAL #x2101)
  (define GL_MODULATE #x2100)
  (define GL_NEAREST #x2600)
  (define GL_REPEAT #x2901)
  (define GL_CLAMP #x2900)
  (define GL_S #x2000)
  (define GL_T #x2001)
  (define GL_R #x2002)
  (define GL_Q #x2003)
  (define GL_TEXTURE_GEN_R #x0C62)
  (define GL_TEXTURE_GEN_Q #x0C63)
  ;;;; Utility
  (define GL_VENDOR #x1F00)
  (define GL_RENDERER #x1F01)
  (define GL_VERSION #x1F02)
  (define GL_EXTENSIONS #x1F03)
  ;;;; Errors
  (define GL_NO_ERROR #x0)
  (define GL_INVALID_ENUM #x0500)
  (define GL_INVALID_VALUE #x0501)
  (define GL_INVALID_OPERATION #x0502)
  (define GL_STACK_OVERFLOW #x0503)
  (define GL_STACK_UNDERFLOW #x0504)
  (define GL_OUT_OF_MEMORY #x0505)
  ;;;; glPush/PopAttrib bits
  (define GL_CURRENT_BIT #x00000001)
  (define GL_POINT_BIT #x00000002)
  (define GL_LINE_BIT #x00000004)
  (define GL_POLYGON_BIT #x00000008)
  (define GL_POLYGON_STIPPLE_BIT #x00000010)
  (define GL_PIXEL_MODE_BIT #x00000020)
  (define GL_LIGHTING_BIT #x00000040)
  (define GL_FOG_BIT #x00000080)
  (define GL_DEPTH_BUFFER_BIT #x00000100)
  (define GL_ACCUM_BUFFER_BIT #x00000200)
  (define GL_STENCIL_BUFFER_BIT #x00000400)
  (define GL_VIEWPORT_BIT #x00000800)
  (define GL_TRANSFORM_BIT #x00001000)
  (define GL_ENABLE_BIT #x00002000)
  (define GL_COLOR_BUFFER_BIT #x00004000)
  (define GL_HINT_BIT #x00008000)
  (define GL_EVAL_BIT #x00010000)
  (define GL_LIST_BIT #x00020000)
  (define GL_TEXTURE_BIT #x00040000)
  (define GL_SCISSOR_BIT #x00080000)
  (define GL_ALL_ATTRIB_BITS #x000FFFFF)
  ;;;; OpenGL 1.1
  (define GL_PROXY_TEXTURE_1D #x8063)
  (define GL_PROXY_TEXTURE_2D #x8064)
  (define GL_TEXTURE_PRIORITY #x8066)
  (define GL_TEXTURE_RESIDENT #x8067)
  (define GL_TEXTURE_BINDING_1D #x8068)
  (define GL_TEXTURE_BINDING_2D #x8069)
  (define GL_TEXTURE_INTERNAL_FORMAT #x1003)
  (define GL_ALPHA4 #x803B)
  (define GL_ALPHA8 #x803C)
  (define GL_ALPHA12 #x803D)
  (define GL_ALPHA16 #x803E)
  (define GL_LUMINANCE4 #x803F)
  (define GL_LUMINANCE8 #x8040)
  (define GL_LUMINANCE12 #x8041)
  (define GL_LUMINANCE16 #x8042)
  (define GL_LUMINANCE4_ALPHA4 #x8043)
  (define GL_LUMINANCE6_ALPHA2 #x8044)
  (define GL_LUMINANCE8_ALPHA8 #x8045)
  (define GL_LUMINANCE12_ALPHA4 #x8046)
  (define GL_LUMINANCE12_ALPHA12 #x8047)
  (define GL_LUMINANCE16_ALPHA16 #x8048)
  (define GL_INTENSITY #x8049)
  (define GL_INTENSITY4 #x804A)
  (define GL_INTENSITY8 #x804B)
  (define GL_INTENSITY12 #x804C)
  (define GL_INTENSITY16 #x804D)
  (define GL_R3_G3_B2 #x2A10)
  (define GL_RGB4 #x804F)
  (define GL_RGB5 #x8050)
  (define GL_RGB8 #x8051)
  (define GL_RGB10 #x8052)
  (define GL_RGB12 #x8053)
  (define GL_RGB16 #x8054)
  (define GL_RGBA2 #x8055)
  (define GL_RGBA4 #x8056)
  (define GL_RGB5_A1 #x8057)
  (define GL_RGBA8 #x8058)
  (define GL_RGB10_A2 #x8059)
  (define GL_RGBA12 #x805A)
  (define GL_RGBA16 #x805B)
  (define GL_CLIENT_PIXEL_STORE_BIT #x00000001)
  (define GL_CLIENT_VERTEX_ARRAY_BIT #x00000002)
  (define GL_ALL_CLIENT_ATTRIB_BITS #xFFFFFFFF)
  (define GL_CLIENT_ALL_ATTRIB_BITS #xFFFFFFFF)
  ;;;; OpenGL 1.2
  (define GL_RESCALE_NORMAL #x803A)
  (define GL_CLAMP_TO_EDGE #x812F)
  (define GL_MAX_ELEMENTS_VERTICES #x80E8)
  (define GL_MAX_ELEMENTS_INDICES #x80E9)
  (define GL_BGR #x80E0)
  (define GL_BGRA #x80E1)
  (define GL_UNSIGNED_BYTE_3_3_2 #x8032)
  (define GL_UNSIGNED_BYTE_2_3_3_REV #x8362)
  (define GL_UNSIGNED_SHORT_5_6_5 #x8363)
  (define GL_UNSIGNED_SHORT_5_6_5_REV #x8364)
  (define GL_UNSIGNED_SHORT_4_4_4_4 #x8033)
  (define GL_UNSIGNED_SHORT_4_4_4_4_REV #x8365)
  (define GL_UNSIGNED_SHORT_5_5_5_1 #x8034)
  (define GL_UNSIGNED_SHORT_1_5_5_5_REV #x8366)
  (define GL_UNSIGNED_INT_8_8_8_8 #x8035)
  (define GL_UNSIGNED_INT_8_8_8_8_REV #x8367)
  (define GL_UNSIGNED_INT_10_10_10_2 #x8036)
  (define GL_UNSIGNED_INT_2_10_10_10_REV #x8368)
  (define GL_LIGHT_MODEL_COLOR_CONTROL #x81F8)
  (define GL_SINGLE_COLOR #x81F9)
  (define GL_SEPARATE_SPECULAR_COLOR #x81FA)
  (define GL_TEXTURE_MIN_LOD #x813A)
  (define GL_TEXTURE_MAX_LOD #x813B)
  (define GL_TEXTURE_BASE_LEVEL #x813C)
  (define GL_TEXTURE_MAX_LEVEL #x813D)
  (define GL_SMOOTH_POINT_SIZE_RANGE #x0B12)
  (define GL_SMOOTH_POINT_SIZE_GRANULARITY #x0B13)
  (define GL_SMOOTH_LINE_WIDTH_RANGE #x0B22)
  (define GL_SMOOTH_LINE_WIDTH_GRANULARITY #x0B23)
  (define GL_ALIASED_POINT_SIZE_RANGE #x846D)
  (define GL_ALIASED_LINE_WIDTH_RANGE #x846E)
  (define GL_PACK_SKIP_IMAGES #x806B)
  (define GL_PACK_IMAGE_HEIGHT #x806C)
  (define GL_UNPACK_SKIP_IMAGES #x806D)
  (define GL_UNPACK_IMAGE_HEIGHT #x806E)
  (define GL_TEXTURE_3D #x806F)
  (define GL_PROXY_TEXTURE_3D #x8070)
  (define GL_TEXTURE_DEPTH #x8071)
  (define GL_TEXTURE_WRAP_R #x8072)
  (define GL_MAX_3D_TEXTURE_SIZE #x8073)
  (define GL_TEXTURE_BINDING_3D #x806A)
  ;;;; GL_ARB_imaging
  (define GL_CONSTANT_COLOR #x8001)
  (define GL_ONE_MINUS_CONSTANT_COLOR #x8002)
  (define GL_CONSTANT_ALPHA #x8003)
  (define GL_ONE_MINUS_CONSTANT_ALPHA #x8004)
  (define GL_COLOR_TABLE #x80D0)
  (define GL_POST_CONVOLUTION_COLOR_TABLE #x80D1)
  (define GL_POST_COLOR_MATRIX_COLOR_TABLE #x80D2)
  (define GL_PROXY_COLOR_TABLE #x80D3)
  (define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE #x80D4)
  (define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE #x80D5)
  (define GL_COLOR_TABLE_SCALE #x80D6)
  (define GL_COLOR_TABLE_BIAS #x80D7)
  (define GL_COLOR_TABLE_FORMAT #x80D8)
  (define GL_COLOR_TABLE_WIDTH #x80D9)
  (define GL_COLOR_TABLE_RED_SIZE #x80DA)
  (define GL_COLOR_TABLE_GREEN_SIZE #x80DB)
  (define GL_COLOR_TABLE_BLUE_SIZE #x80DC)
  (define GL_COLOR_TABLE_ALPHA_SIZE #x80DD)
  (define GL_COLOR_TABLE_LUMINANCE_SIZE #x80DE)
  (define GL_COLOR_TABLE_INTENSITY_SIZE #x80DF)
  (define GL_CONVOLUTION_1D #x8010)
  (define GL_CONVOLUTION_2D #x8011)
  (define GL_SEPARABLE_2D #x8012)
  (define GL_CONVOLUTION_BORDER_MODE #x8013)
  (define GL_CONVOLUTION_FILTER_SCALE #x8014)
  (define GL_CONVOLUTION_FILTER_BIAS #x8015)
  (define GL_REDUCE #x8016)
  (define GL_CONVOLUTION_FORMAT #x8017)
  (define GL_CONVOLUTION_WIDTH #x8018)
  (define GL_CONVOLUTION_HEIGHT #x8019)
  (define GL_MAX_CONVOLUTION_WIDTH #x801A)
  (define GL_MAX_CONVOLUTION_HEIGHT #x801B)
  (define GL_POST_CONVOLUTION_RED_SCALE #x801C)
  (define GL_POST_CONVOLUTION_GREEN_SCALE #x801D)
  (define GL_POST_CONVOLUTION_BLUE_SCALE #x801E)
  (define GL_POST_CONVOLUTION_ALPHA_SCALE #x801F)
  (define GL_POST_CONVOLUTION_RED_BIAS #x8020)
  (define GL_POST_CONVOLUTION_GREEN_BIAS #x8021)
  (define GL_POST_CONVOLUTION_BLUE_BIAS #x8022)
  (define GL_POST_CONVOLUTION_ALPHA_BIAS #x8023)
  (define GL_CONSTANT_BORDER #x8151)
  (define GL_REPLICATE_BORDER #x8153)
  (define GL_CONVOLUTION_BORDER_COLOR #x8154)
  (define GL_COLOR_MATRIX #x80B1)
  (define GL_COLOR_MATRIX_STACK_DEPTH #x80B2)
  (define GL_MAX_COLOR_MATRIX_STACK_DEPTH #x80B3)
  (define GL_POST_COLOR_MATRIX_RED_SCALE #x80B4)
  (define GL_POST_COLOR_MATRIX_GREEN_SCALE #x80B5)
  (define GL_POST_COLOR_MATRIX_BLUE_SCALE #x80B6)
  (define GL_POST_COLOR_MATRIX_ALPHA_SCALE #x80B7)
  (define GL_POST_COLOR_MATRIX_RED_BIAS #x80B8)
  (define GL_POST_COLOR_MATRIX_GREEN_BIAS #x80B9)
  (define GL_POST_COLOR_MATRIX_BLUE_BIAS #x80BA)
  (define GL_POST_COLOR_MATRIX_ALPHA_BIAS #x80BB)
  (define GL_HISTOGRAM #x8024)
  (define GL_PROXY_HISTOGRAM #x8025)
  (define GL_HISTOGRAM_WIDTH #x8026)
  (define GL_HISTOGRAM_FORMAT #x8027)
  (define GL_HISTOGRAM_RED_SIZE #x8028)
  (define GL_HISTOGRAM_GREEN_SIZE #x8029)
  (define GL_HISTOGRAM_BLUE_SIZE #x802A)
  (define GL_HISTOGRAM_ALPHA_SIZE #x802B)
  (define GL_HISTOGRAM_LUMINANCE_SIZE #x802C)
  (define GL_HISTOGRAM_SINK #x802D)
  (define GL_MINMAX #x802E)
  (define GL_MINMAX_FORMAT #x802F)
  (define GL_MINMAX_SINK #x8030)
  (define GL_TABLE_TOO_LARGE #x8031)
  (define GL_BLEND_EQUATION #x8009)
  (define GL_MIN #x8007)
  (define GL_MAX #x8008)
  (define GL_FUNC_ADD #x8006)
  (define GL_FUNC_SUBTRACT #x800A)
  (define GL_FUNC_REVERSE_SUBTRACT #x800B)
  (define GL_BLEND_COLOR #x8005)
  ;;;; OpenGL 1.3
  ;;;; multitexture
  (define GL_TEXTURE0 #x84C0)
  (define GL_TEXTURE1 #x84C1)
  (define GL_TEXTURE2 #x84C2)
  (define GL_TEXTURE3 #x84C3)
  (define GL_TEXTURE4 #x84C4)
  (define GL_TEXTURE5 #x84C5)
  (define GL_TEXTURE6 #x84C6)
  (define GL_TEXTURE7 #x84C7)
  (define GL_TEXTURE8 #x84C8)
  (define GL_TEXTURE9 #x84C9)
  (define GL_TEXTURE10 #x84CA)
  (define GL_TEXTURE11 #x84CB)
  (define GL_TEXTURE12 #x84CC)
  (define GL_TEXTURE13 #x84CD)
  (define GL_TEXTURE14 #x84CE)
  (define GL_TEXTURE15 #x84CF)
  (define GL_TEXTURE16 #x84D0)
  (define GL_TEXTURE17 #x84D1)
  (define GL_TEXTURE18 #x84D2)
  (define GL_TEXTURE19 #x84D3)
  (define GL_TEXTURE20 #x84D4)
  (define GL_TEXTURE21 #x84D5)
  (define GL_TEXTURE22 #x84D6)
  (define GL_TEXTURE23 #x84D7)
  (define GL_TEXTURE24 #x84D8)
  (define GL_TEXTURE25 #x84D9)
  (define GL_TEXTURE26 #x84DA)
  (define GL_TEXTURE27 #x84DB)
  (define GL_TEXTURE28 #x84DC)
  (define GL_TEXTURE29 #x84DD)
  (define GL_TEXTURE30 #x84DE)
  (define GL_TEXTURE31 #x84DF)
  (define GL_ACTIVE_TEXTURE #x84E0)
  (define GL_CLIENT_ACTIVE_TEXTURE #x84E1)
  (define GL_MAX_TEXTURE_UNITS #x84E2)
  ;;;; texture_cube_map
  (define GL_NORMAL_MAP #x8511)
  (define GL_REFLECTION_MAP #x8512)
  (define GL_TEXTURE_CUBE_MAP #x8513)
  (define GL_TEXTURE_BINDING_CUBE_MAP #x8514)
  (define GL_TEXTURE_CUBE_MAP_POSITIVE_X #x8515)
  (define GL_TEXTURE_CUBE_MAP_NEGATIVE_X #x8516)
  (define GL_TEXTURE_CUBE_MAP_POSITIVE_Y #x8517)
  (define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y #x8518)
  (define GL_TEXTURE_CUBE_MAP_POSITIVE_Z #x8519)
  (define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z #x851A)
  (define GL_PROXY_TEXTURE_CUBE_MAP #x851B)
  (define GL_MAX_CUBE_MAP_TEXTURE_SIZE #x851C)
  ;;;; texture_compression
  (define GL_COMPRESSED_ALPHA #x84E9)
  (define GL_COMPRESSED_LUMINANCE #x84EA)
  (define GL_COMPRESSED_LUMINANCE_ALPHA #x84EB)
  (define GL_COMPRESSED_INTENSITY #x84EC)
  (define GL_COMPRESSED_RGB #x84ED)
  (define GL_COMPRESSED_RGBA #x84EE)
  (define GL_TEXTURE_COMPRESSION_HINT #x84EF)
  (define GL_TEXTURE_COMPRESSED_IMAGE_SIZE #x86A0)
  (define GL_TEXTURE_COMPRESSED #x86A1)
  (define GL_NUM_COMPRESSED_TEXTURE_FORMATS #x86A2)
  (define GL_COMPRESSED_TEXTURE_FORMATS #x86A3)
  ;;;; multisample
  (define GL_MULTISAMPLE #x809D)
  (define GL_SAMPLE_ALPHA_TO_COVERAGE #x809E)
  (define GL_SAMPLE_ALPHA_TO_ONE #x809F)
  (define GL_SAMPLE_COVERAGE #x80A0)
  (define GL_SAMPLE_BUFFERS #x80A8)
  (define GL_SAMPLES #x80A9)
  (define GL_SAMPLE_COVERAGE_VALUE #x80AA)
  (define GL_SAMPLE_COVERAGE_INVERT #x80AB)
  (define GL_MULTISAMPLE_BIT #x20000000)
  ;;;; transpose_matrix
  (define GL_TRANSPOSE_MODELVIEW_MATRIX #x84E3)
  (define GL_TRANSPOSE_PROJECTION_MATRIX #x84E4)
  (define GL_TRANSPOSE_TEXTURE_MATRIX #x84E5)
  (define GL_TRANSPOSE_COLOR_MATRIX #x84E6)
  ;;;; texture_env_combine
  (define GL_COMBINE #x8570)
  (define GL_COMBINE_RGB #x8571)
  (define GL_COMBINE_ALPHA #x8572)
  (define GL_SOURCE0_RGB #x8580)
  (define GL_SOURCE1_RGB #x8581)
  (define GL_SOURCE2_RGB #x8582)
  (define GL_SOURCE0_ALPHA #x8588)
  (define GL_SOURCE1_ALPHA #x8589)
  (define GL_SOURCE2_ALPHA #x858A)
  (define GL_OPERAND0_RGB #x8590)
  (define GL_OPERAND1_RGB #x8591)
  (define GL_OPERAND2_RGB #x8592)
  (define GL_OPERAND0_ALPHA #x8598)
  (define GL_OPERAND1_ALPHA #x8599)
  (define GL_OPERAND2_ALPHA #x859A)
  (define GL_RGB_SCALE #x8573)
  (define GL_ADD_SIGNED #x8574)
  (define GL_INTERPOLATE #x8575)
  (define GL_SUBTRACT #x84E7)
  (define GL_CONSTANT #x8576)
  (define GL_PRIMARY_COLOR #x8577)
  (define GL_PREVIOUS #x8578)
  ;;;; texture_env_dot3
  (define GL_DOT3_RGB #x86AE)
  (define GL_DOT3_RGBA #x86AF)
  ;;;; texture_border_clamp
  (define GL_CLAMP_TO_BORDER #x812D)
  ;;;; GL_ARB_multitexture: ARB extension 1 and OpenGL 1.2.1
  (define GL_TEXTURE0_ARB #x84C0)
  (define GL_TEXTURE1_ARB #x84C1)
  (define GL_TEXTURE2_ARB #x84C2)
  (define GL_TEXTURE3_ARB #x84C3)
  (define GL_TEXTURE4_ARB #x84C4)
  (define GL_TEXTURE5_ARB #x84C5)
  (define GL_TEXTURE6_ARB #x84C6)
  (define GL_TEXTURE7_ARB #x84C7)
  (define GL_TEXTURE8_ARB #x84C8)
  (define GL_TEXTURE9_ARB #x84C9)
  (define GL_TEXTURE10_ARB #x84CA)
  (define GL_TEXTURE11_ARB #x84CB)
  (define GL_TEXTURE12_ARB #x84CC)
  (define GL_TEXTURE13_ARB #x84CD)
  (define GL_TEXTURE14_ARB #x84CE)
  (define GL_TEXTURE15_ARB #x84CF)
  (define GL_TEXTURE16_ARB #x84D0)
  (define GL_TEXTURE17_ARB #x84D1)
  (define GL_TEXTURE18_ARB #x84D2)
  (define GL_TEXTURE19_ARB #x84D3)
  (define GL_TEXTURE20_ARB #x84D4)
  (define GL_TEXTURE21_ARB #x84D5)
  (define GL_TEXTURE22_ARB #x84D6)
  (define GL_TEXTURE23_ARB #x84D7)
  (define GL_TEXTURE24_ARB #x84D8)
  (define GL_TEXTURE25_ARB #x84D9)
  (define GL_TEXTURE26_ARB #x84DA)
  (define GL_TEXTURE27_ARB #x84DB)
  (define GL_TEXTURE28_ARB #x84DC)
  (define GL_TEXTURE29_ARB #x84DD)
  (define GL_TEXTURE30_ARB #x84DE)
  (define GL_TEXTURE31_ARB #x84DF)
  (define GL_ACTIVE_TEXTURE_ARB #x84E0)
  (define GL_CLIENT_ACTIVE_TEXTURE_ARB #x84E1)
  (define GL_MAX_TEXTURE_UNITS_ARB #x84E2)

  ;; (define-syntax define-function
  ;;   (syntax-rules ()
  ;;     ((_ ret name args)
  ;;      (define name (c-function lib lib-name ret __stdcall name args)))))

  (define-syntax define-function
    (syntax-rules ()
      ((_ ret name args)
       (define name
         (foreign-procedure (symbol->string 'name) args ret)))))

  ;; void glClearIndex( GLfloat c )
  (define-function void glClearIndex (float))

  ;; void glClearColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha )
  (define-function void glClearColor (float float float float))

  ;; void glClear( GLbitfield mask )
  (define-function void glClear (int))

  ;; void glIndexMask( GLuint mask )
  (define-function void glIndexMask (int))

  ;; void glColorMask( GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha )
  (define-function void glColorMask (int int int int))

  ;; void glAlphaFunc( GLenum func, GLclampf ref )
  (define-function void glAlphaFunc (int float))

  ;; void glBlendFunc( GLenum sfactor, GLenum dfactor )
  (define-function void glBlendFunc (int int))

  ;; void glLogicOp( GLenum opcode )
  (define-function void glLogicOp (int))

  ;; void glCullFace( GLenum mode )
  (define-function void glCullFace (int))

  ;; void glFrontFace( GLenum mode )
  (define-function void glFrontFace (int))

  ;; void glPointSize( GLfloat size )
  (define-function void glPointSize (float))

  ;; void glLineWidth( GLfloat width )
  (define-function void glLineWidth (float))

  ;; void glLineStipple( GLint factor, GLushort pattern )
  (define-function void glLineStipple (int int))

  ;; void glPolygonMode( GLenum face, GLenum mode )
  (define-function void glPolygonMode (int int))

  ;; void glPolygonOffset( GLfloat factor, GLfloat units )
  (define-function void glPolygonOffset (float float))

  ;; void glPolygonStipple( const GLubyte *mask )
  (define-function void glPolygonStipple (void*))

  ;; void glGetPolygonStipple( GLubyte *mask )
  (define-function void glGetPolygonStipple (void*))

  ;; void glEdgeFlag( GLboolean flag )
  (define-function void glEdgeFlag (int))

  ;; void glEdgeFlagv( const GLboolean *flag )
  (define-function void glEdgeFlagv (void*))

  ;; void glScissor( GLint x, GLint y, GLsizei width, GLsizei height)
  (define-function void glScissor (int int int int))

  ;; void glClipPlane( GLenum plane, const GLdouble *equation )
  (define-function void glClipPlane (int void*))

  ;; void glGetClipPlane( GLenum plane, GLdouble *equation )
  (define-function void glGetClipPlane (int void*))

  ;; void glDrawBuffer( GLenum mode )
  (define-function void glDrawBuffer (int))

  ;; void glReadBuffer( GLenum mode )
  (define-function void glReadBuffer (int))

  ;; void glEnable( GLenum cap )
  (define-function void glEnable (int))

  ;; void glDisable( GLenum cap )
  (define-function void glDisable (int))

  ;; GLboolean glIsEnabled( GLenum cap )
  (define-function int glIsEnabled (int))

  ;; void glEnableClientState( GLenum cap )  /* 1.1 */
  (define-function void glEnableClientState (int))

  ;; void glDisableClientState( GLenum cap )  /* 1.1 */
  (define-function void glDisableClientState (int))

  ;; void glGetBooleanv( GLenum pname, GLboolean *params )
  (define-function void glGetBooleanv (int void*))

  ;; void glGetDoublev( GLenum pname, GLdouble *params )

  ;; (define-function void glGetDoublev (int void*))

  (define-function void glGetDoublev (int u8*))

  ;; void glGetFloatv( GLenum pname, GLfloat *params )
  (define-function void glGetFloatv (int void*))

  ;; void glGetIntegerv( GLenum pname, GLint *params )
  (define-function void glGetIntegerv (int void*))

  ;; void glPushAttrib( GLbitfield mask )
  (define-function void glPushAttrib (int))

  ;; void glPopAttrib( void )
  (define-function void glPopAttrib ())

  ;; void glPushClientAttrib( GLbitfield mask )  /* 1.1 */
  (define-function void glPushClientAttrib (int))

  ;; void glPopClientAttrib( void )  /* 1.1 */
  (define-function void glPopClientAttrib ())

  ;; GLint glRenderMode( GLenum mode )
  (define-function int glRenderMode (int))

  ;; GLenum glGetError( void )
  (define-function int glGetError ())

  ;; const GLubyte * glGetString( GLenum name )
  (define-function string glGetString (int))

  ;; void glFinish( void )
  (define-function void glFinish ())

  ;; void glFlush( void )
  (define-function void glFlush ())

  ;; void glHint( GLenum target, GLenum mode )
  (define-function void glHint (int int))

  ;;;; Depth Buffer

  ;; void glClearDepth( GLclampd depth )
  (define-function void glClearDepth (double))

  ;; void glDepthFunc( GLenum func )
  (define-function void glDepthFunc (int))

  ;; void glDepthMask( GLboolean flag )
  (define-function void glDepthMask (int))

  ;; void glDepthRange( GLclampd near_val, GLclampd far_val )
  (define-function void glDepthRange (double double))

  ;;;; Accumulation Buffer

  ;; void glClearAccum( GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha )
  (define-function void glClearAccum (float float float float))

  ;; void glAccum( GLenum op, GLfloat value )
  (define-function void glAccum (int float))

  ;;;; Transformation

  ;; void glMatrixMode( GLenum mode )
  (define-function void glMatrixMode (int))

  ;; void glOrtho( GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val )
  (define-function void glOrtho (double double double double double double))

  ;; void glFrustum( GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val )
  (define-function void glFrustum (double double double double double double))

  ;; void glViewport( GLint x, GLint y, GLsizei width, GLsizei height )
  (define-function void glViewport (int int int int))

  ;; void glPushMatrix( void )
  (define-function void glPushMatrix ())

  ;; void glPopMatrix( void )
  (define-function void glPopMatrix ())

  ;; void glLoadIdentity( void )
  (define-function void glLoadIdentity ())

  ;; void glLoadMatrixd( const GLdouble *m )
  (define-function void glLoadMatrixd (u8*))

  ;; void glLoadMatrixf( const GLfloat *m )
  (define-function void glLoadMatrixf (u8*))

  ;; void glMultMatrixd( const GLdouble *m )
  (define-function void glMultMatrixd (u8*))

  ;; void glMultMatrixf( const GLfloat *m )
  (define-function void glMultMatrixf (u8*))

  ;; void glRotated( GLdouble angle, GLdouble x, GLdouble y, GLdouble z )
  (define-function void glRotated (double double double double))

  ;; void glRotatef( GLfloat angle, GLfloat x, GLfloat y, GLfloat z )
  (define-function void glRotatef (float float float float))

  ;; void glScaled( GLdouble x, GLdouble y, GLdouble z )
  (define-function void glScaled (double double double))

  ;; void glScalef( GLfloat x, GLfloat y, GLfloat z )
  (define-function void glScalef (float float float))

  ;; void glTranslated( GLdouble x, GLdouble y, GLdouble z )
  (define-function void glTranslated (double double double))

  ;; void glTranslatef( GLfloat x, GLfloat y, GLfloat z )
  (define-function void glTranslatef (float float float))

  ;;;; Display Lists

  ;; GLboolean glIsList( GLuint list )
  (define-function int glIsList (int))

  ;; void glDeleteLists( GLuint list, GLsizei range )
  (define-function void glDeleteLists (int int))

  ;; GLuint glGenLists( GLsizei range )
  (define-function int glGenLists (int))

  ;; void glNewList( GLuint list, GLenum mode )
  (define-function void glNewList (int int))

  ;; void glEndList( void )
  (define-function void glEndList ())

  ;; void glCallList( GLuint list )
  (define-function void glCallList (int))

  ;; void glCallLists( GLsizei n, GLenum type, const GLvoid *lists )
  (define-function void glCallLists (int int void*))

  ;; void glListBase( GLuint base )
  (define-function void glListBase (int))

  ;;;; Drawing Functions

  ;; void glBegin( GLenum mode )
  (define-function void glBegin (int))

  ;; void glEnd( void )
  (define-function void glEnd ())

  ;; void glVertex2d( GLdouble x, GLdouble y )
  (define-function void glVertex2d (double double))

  ;; void glVertex2f( GLfloat x, GLfloat y )
  (define-function void glVertex2f (float float))

  ;; void glVertex2i( GLint x, GLint y )
  (define-function void glVertex2i (int int))

  ;; void glVertex2s( GLshort x, GLshort y )
  (define-function void glVertex2s (int int))

  ;; void glVertex3d( GLdouble x, GLdouble y, GLdouble z )
  (define-function void glVertex3d (double double double))

  ;; void glVertex3f( GLfloat x, GLfloat y, GLfloat z )
  (define-function void glVertex3f (float float float))

  ;; void glVertex3i( GLint x, GLint y, GLint z )
  (define-function void glVertex3i (int int int))

  ;; void glVertex3s( GLshort x, GLshort y, GLshort z )
  (define-function void glVertex3s (int int int))

  ;; void glVertex4d( GLdouble x, GLdouble y, GLdouble z, GLdouble w )
  (define-function void glVertex4d (double double double double))

  ;; void glVertex4f( GLfloat x, GLfloat y, GLfloat z, GLfloat w )
  (define-function void glVertex4f (float float float float))

  ;; void glVertex4i( GLint x, GLint y, GLint z, GLint w )
  (define-function void glVertex4i (int int int int))

  ;; void glVertex4s( GLshort x, GLshort y, GLshort z, GLshort w )
  (define-function void glVertex4s (int int int int))

  ;; void glVertex2dv( const GLdouble *v )
  (define-function void glVertex2dv (void*))

  ;; void glVertex2fv( const GLfloat *v )
  (define-function void glVertex2fv (void*))

  ;; void glVertex2iv( const GLint *v )
  (define-function void glVertex2iv (void*))

  ;; void glVertex2sv( const GLshort *v )
  (define-function void glVertex2sv (void*))

  ;; void glVertex3dv( const GLdouble *v )
  (define-function void glVertex3dv (void*))

  ;; void glVertex3fv( const GLfloat *v )
  (define-function void glVertex3fv (void*))

  ;; void glVertex3iv( const GLint *v )
  (define-function void glVertex3iv (void*))

  ;; void glVertex3sv( const GLshort *v )
  (define-function void glVertex3sv (void*))

  ;; void glVertex4dv( const GLdouble *v )
  (define-function void glVertex4dv (void*))

  ;; void glVertex4fv( const GLfloat *v )
  (define-function void glVertex4fv (void*))

  ;; void glVertex4iv( const GLint *v )
  (define-function void glVertex4iv (void*))

  ;; void glVertex4sv( const GLshort *v )
  (define-function void glVertex4sv (void*))

  ;; void glNormal3b( GLbyte nx, GLbyte ny, GLbyte nz )
  (define-function void glNormal3b (int int int))

  ;; void glNormal3d( GLdouble nx, GLdouble ny, GLdouble nz )
  (define-function void glNormal3d (double double double))

  ;; void glNormal3f( GLfloat nx, GLfloat ny, GLfloat nz )
  (define-function void glNormal3f (float float float))

  ;; void glNormal3i( GLint nx, GLint ny, GLint nz )
  (define-function void glNormal3i (int int int))

  ;; void glNormal3s( GLshort nx, GLshort ny, GLshort nz )
  (define-function void glNormal3s (int int int))

  ;; void glNormal3bv( const GLbyte *v )
  (define-function void glNormal3bv (void*))

  ;; void glNormal3dv( const GLdouble *v )
  (define-function void glNormal3dv (void*))

  ;; void glNormal3fv( const GLfloat *v )
  (define-function void glNormal3fv (void*))

  ;; void glNormal3iv( const GLint *v )
  (define-function void glNormal3iv (void*))

  ;; void glNormal3sv( const GLshort *v )
  (define-function void glNormal3sv (void*))

  ;; void glIndexd( GLdouble c )
  (define-function void glIndexd (double))

  ;; void glIndexf( GLfloat c )
  (define-function void glIndexf (float))

  ;; void glIndexi( GLint c )
  (define-function void glIndexi (int))

  ;; void glIndexs( GLshort c )
  (define-function void glIndexs (int))

  ;; void glIndexub( GLubyte c )  /* 1.1 */
  (define-function void glIndexub (int))

  ;; void glIndexdv( const GLdouble *c )
  (define-function void glIndexdv (void*))

  ;; void glIndexfv( const GLfloat *c )
  (define-function void glIndexfv (void*))

  ;; void glIndexiv( const GLint *c )
  (define-function void glIndexiv (void*))

  ;; void glIndexsv( const GLshort *c )
  (define-function void glIndexsv (void*))

  ;; void glIndexubv( const GLubyte *c )  /* 1.1 */
  (define-function void glIndexubv (void*))

  ;; void glColor3b( GLbyte red, GLbyte green, GLbyte blue )
  (define-function void glColor3b (int int int))

  ;; void glColor3d( GLdouble red, GLdouble green, GLdouble blue )
  (define-function void glColor3d (double double double))

  ;; void glColor3f( GLfloat red, GLfloat green, GLfloat blue )
  (define-function void glColor3f (float float float))

  ;; void glColor3i( GLint red, GLint green, GLint blue )
  (define-function void glColor3i (int int int))

  ;; void glColor3s( GLshort red, GLshort green, GLshort blue )
  (define-function void glColor3s (int int int))

  ;; void glColor3ub( GLubyte red, GLubyte green, GLubyte blue )
  (define-function void glColor3ub (int int int))

  ;; void glColor3ui( GLuint red, GLuint green, GLuint blue )
  (define-function void glColor3ui (int int int))

  ;; void glColor3us( GLushort red, GLushort green, GLushort blue )
  (define-function void glColor3us (int int int))

  ;; void glColor4b( GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha )
  (define-function void glColor4b (int int int int))

  ;; void glColor4d( GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha )
  (define-function void glColor4d (double double double double))

  ;; void glColor4f( GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha )
  (define-function void glColor4f (float float float float))

  ;; void glColor4i( GLint red, GLint green, GLint blue, GLint alpha )
  (define-function void glColor4i (int int int int))

  ;; void glColor4s( GLshort red, GLshort green, GLshort blue, GLshort alpha )
  (define-function void glColor4s (int int int int))

  ;; void glColor4ub( GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha )
  (define-function void glColor4ub (int int int int))

  ;; void glColor4ui( GLuint red, GLuint green, GLuint blue, GLuint alpha )
  (define-function void glColor4ui (int int int int))

  ;; void glColor4us( GLushort red, GLushort green, GLushort blue, GLushort alpha )
  (define-function void glColor4us (int int int int))

  ;; void glColor3bv( const GLbyte *v )
  (define-function void glColor3bv (void*))

  ;; void glColor3dv( const GLdouble *v )
  (define-function void glColor3dv (void*))

  ;; void glColor3fv( const GLfloat *v )
  (define-function void glColor3fv (void*))

  ;; void glColor3iv( const GLint *v )
  (define-function void glColor3iv (void*))

  ;; void glColor3sv( const GLshort *v )
  (define-function void glColor3sv (void*))

  ;; void glColor3ubv( const GLubyte *v )
  (define-function void glColor3ubv (void*))

  ;; void glColor3uiv( const GLuint *v )
  (define-function void glColor3uiv (void*))

  ;; void glColor3usv( const GLushort *v )
  (define-function void glColor3usv (void*))

  ;; void glColor4bv( const GLbyte *v )
  (define-function void glColor4bv (void*))

  ;; void glColor4dv( const GLdouble *v )
  (define-function void glColor4dv (void*))

  ;; void glColor4fv( const GLfloat *v )
  (define-function void glColor4fv (void*))

  ;; void glColor4iv( const GLint *v )
  (define-function void glColor4iv (void*))

  ;; void glColor4sv( const GLshort *v )
  (define-function void glColor4sv (void*))

  ;; void glColor4ubv( const GLubyte *v )
  (define-function void glColor4ubv (void*))

  ;; void glColor4uiv( const GLuint *v )
  (define-function void glColor4uiv (void*))

  ;; void glColor4usv( const GLushort *v )
  (define-function void glColor4usv (void*))

  ;; void glTexCoord1d( GLdouble s )
  (define-function void glTexCoord1d (double))

  ;; void glTexCoord1f( GLfloat s )
  (define-function void glTexCoord1f (float))

  ;; void glTexCoord1i( GLint s )
  (define-function void glTexCoord1i (int))

  ;; void glTexCoord1s( GLshort s )
  (define-function void glTexCoord1s (int))

  ;; void glTexCoord2d( GLdouble s, GLdouble t )
  (define-function void glTexCoord2d (double double))

  ;; void glTexCoord2f( GLfloat s, GLfloat t )
  (define-function void glTexCoord2f (float float))

  ;; void glTexCoord2i( GLint s, GLint t )
  (define-function void glTexCoord2i (int int))

  ;; void glTexCoord2s( GLshort s, GLshort t )
  (define-function void glTexCoord2s (int int))

  ;; void glTexCoord3d( GLdouble s, GLdouble t, GLdouble r )
  (define-function void glTexCoord3d (double double double))

  ;; void glTexCoord3f( GLfloat s, GLfloat t, GLfloat r )
  (define-function void glTexCoord3f (float float float))

  ;; void glTexCoord3i( GLint s, GLint t, GLint r )
  (define-function void glTexCoord3i (int int int))

  ;; void glTexCoord3s( GLshort s, GLshort t, GLshort r )
  (define-function void glTexCoord3s (int int int))

  ;; void glTexCoord4d( GLdouble s, GLdouble t, GLdouble r, GLdouble q )
  (define-function void glTexCoord4d (double double double double))

  ;; void glTexCoord4f( GLfloat s, GLfloat t, GLfloat r, GLfloat q )
  (define-function void glTexCoord4f (float float float float))

  ;; void glTexCoord4i( GLint s, GLint t, GLint r, GLint q )
  (define-function void glTexCoord4i (int int int int))

  ;; void glTexCoord4s( GLshort s, GLshort t, GLshort r, GLshort q )
  (define-function void glTexCoord4s (int int int int))

  ;; void glTexCoord1dv( const GLdouble *v )
  (define-function void glTexCoord1dv (void*))

  ;; void glTexCoord1fv( const GLfloat *v )
  (define-function void glTexCoord1fv (void*))

  ;; void glTexCoord1iv( const GLint *v )
  (define-function void glTexCoord1iv (void*))

  ;; void glTexCoord1sv( const GLshort *v )
  (define-function void glTexCoord1sv (void*))

  ;; void glTexCoord2dv( const GLdouble *v )
  (define-function void glTexCoord2dv (void*))

  ;; void glTexCoord2fv( const GLfloat *v )
  (define-function void glTexCoord2fv (void*))

  ;; void glTexCoord2iv( const GLint *v )
  (define-function void glTexCoord2iv (void*))

  ;; void glTexCoord2sv( const GLshort *v )
  (define-function void glTexCoord2sv (void*))

  ;; void glTexCoord3dv( const GLdouble *v )
  (define-function void glTexCoord3dv (void*))

  ;; void glTexCoord3fv( const GLfloat *v )
  (define-function void glTexCoord3fv (void*))

  ;; void glTexCoord3iv( const GLint *v )
  (define-function void glTexCoord3iv (void*))

  ;; void glTexCoord3sv( const GLshort *v )
  (define-function void glTexCoord3sv (void*))

  ;; void glTexCoord4dv( const GLdouble *v )
  (define-function void glTexCoord4dv (void*))

  ;; void glTexCoord4fv( const GLfloat *v )
  (define-function void glTexCoord4fv (void*))

  ;; void glTexCoord4iv( const GLint *v )
  (define-function void glTexCoord4iv (void*))

  ;; void glTexCoord4sv( const GLshort *v )
  (define-function void glTexCoord4sv (void*))

  ;; void glRasterPos2d( GLdouble x, GLdouble y )
  (define-function void glRasterPos2d (double double))

  ;; void glRasterPos2f( GLfloat x, GLfloat y )
  (define-function void glRasterPos2f (float float))

  ;; void glRasterPos2i( GLint x, GLint y )
  (define-function void glRasterPos2i (int int))

  ;; void glRasterPos2s( GLshort x, GLshort y )
  (define-function void glRasterPos2s (int int))

  ;; void glRasterPos3d( GLdouble x, GLdouble y, GLdouble z )
  (define-function void glRasterPos3d (double double double))

  ;; void glRasterPos3f( GLfloat x, GLfloat y, GLfloat z )
  (define-function void glRasterPos3f (float float float))

  ;; void glRasterPos3i( GLint x, GLint y, GLint z )
  (define-function void glRasterPos3i (int int int))

  ;; void glRasterPos3s( GLshort x, GLshort y, GLshort z )
  (define-function void glRasterPos3s (int int int))

  ;; void glRasterPos4d( GLdouble x, GLdouble y, GLdouble z, GLdouble w )
  (define-function void glRasterPos4d (double double double double))

  ;; void glRasterPos4f( GLfloat x, GLfloat y, GLfloat z, GLfloat w )
  (define-function void glRasterPos4f (float float float float))

  ;; void glRasterPos4i( GLint x, GLint y, GLint z, GLint w )
  (define-function void glRasterPos4i (int int int int))

  ;; void glRasterPos4s( GLshort x, GLshort y, GLshort z, GLshort w )
  (define-function void glRasterPos4s (int int int int))

  ;; void glRasterPos2dv( const GLdouble *v )
  (define-function void glRasterPos2dv (void*))

  ;; void glRasterPos2fv( const GLfloat *v )
  (define-function void glRasterPos2fv (void*))

  ;; void glRasterPos2iv( const GLint *v )
  (define-function void glRasterPos2iv (void*))

  ;; void glRasterPos2sv( const GLshort *v )
  (define-function void glRasterPos2sv (void*))

  ;; void glRasterPos3dv( const GLdouble *v )
  (define-function void glRasterPos3dv (void*))

  ;; void glRasterPos3fv( const GLfloat *v )
  (define-function void glRasterPos3fv (void*))

  ;; void glRasterPos3iv( const GLint *v )
  (define-function void glRasterPos3iv (void*))

  ;; void glRasterPos3sv( const GLshort *v )
  (define-function void glRasterPos3sv (void*))

  ;; void glRasterPos4dv( const GLdouble *v )
  (define-function void glRasterPos4dv (void*))

  ;; void glRasterPos4fv( const GLfloat *v )
  (define-function void glRasterPos4fv (void*))

  ;; void glRasterPos4iv( const GLint *v )
  (define-function void glRasterPos4iv (void*))

  ;; void glRasterPos4sv( const GLshort *v )
  (define-function void glRasterPos4sv (void*))

  ;; void glRectd( GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2 )
  (define-function void glRectd (double double double double))

  ;; void glRectf( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2 )
  (define-function void glRectf (float float float float))

  ;; void glRecti( GLint x1, GLint y1, GLint x2, GLint y2 )
  (define-function void glRecti (int int int int))

  ;; void glRects( GLshort x1, GLshort y1, GLshort x2, GLshort y2 )
  (define-function void glRects (int int int int))

  ;; void glRectdv( const GLdouble *v1, const GLdouble *v2 )
  (define-function void glRectdv (void* void*))

  ;; void glRectfv( const GLfloat *v1, const GLfloat *v2 )
  (define-function void glRectfv (void* void*))

  ;; void glRectiv( const GLint *v1, const GLint *v2 )
  (define-function void glRectiv (void* void*))

  ;; void glRectsv( const GLshort *v1, const GLshort *v2 )
  (define-function void glRectsv (void* void*))

  ;;;; Vertex Arrays 1.1

  ;; void glVertexPointer( GLint size, GLenum type, GLsizei stride, const GLvoid *ptr )
  (define-function void glVertexPointer (int int int void*))

  ;; void glNormalPointer( GLenum type, GLsizei stride, const GLvoid *ptr )
  (define-function void glNormalPointer (int int void*))

  ;; void glColorPointer( GLint size, GLenum type, GLsizei stride, const GLvoid *ptr )
  (define-function void glColorPointer (int int int void*))

  ;; void glIndexPointer( GLenum type, GLsizei stride, const GLvoid *ptr )
  (define-function void glIndexPointer (int int void*))

  ;; void glTexCoordPointer( GLint size, GLenum type, GLsizei stride, const GLvoid *ptr )
  (define-function void glTexCoordPointer (int int int void*))

  ;; void glEdgeFlagPointer( GLsizei stride, const GLvoid *ptr )
  (define-function void glEdgeFlagPointer (int void*))

  ;; void glGetPointerv( GLenum pname, GLvoid **params )
  (define-function void glGetPointerv (int void*))

  ;; void glArrayElement( GLint i )
  (define-function void glArrayElement (int))

  ;; void glDrawArrays( GLenum mode, GLint first, GLsizei count )
  (define-function void glDrawArrays (int int int))

  ;; void glDrawElements( GLenum mode, GLsizei count, GLenum type, const GLvoid *indices )
  (define-function void glDrawElements (int int int void*))

  ;; void glInterleavedArrays( GLenum format, GLsizei stride, const GLvoid *pointer )
  (define-function void glInterleavedArrays (int int void*))

  ;;;; Lighting

  ;; void glShadeModel( GLenum mode )
  (define-function void glShadeModel (int))

  ;; void glLightf( GLenum light, GLenum pname, GLfloat param )
  (define-function void glLightf (int int float))

  ;; void glLighti( GLenum light, GLenum pname, GLint param )
  (define-function void glLighti (int int int))

  ;; void glLightfv( GLenum light, GLenum pname, const GLfloat *params )
  ;; (define-function void glLightfv (int int void*))
  (define-function void glLightfv (int int u8*))

  ;; void glLightiv( GLenum light, GLenum pname, const GLint *params )
  (define-function void glLightiv (int int void*))

  ;; void glGetLightfv( GLenum light, GLenum pname, GLfloat *params )
  (define-function void glGetLightfv (int int void*))

  ;; void glGetLightiv( GLenum light, GLenum pname, GLint *params )
  (define-function void glGetLightiv (int int void*))

  ;; void glLightModelf( GLenum pname, GLfloat param )
  (define-function void glLightModelf (int float))

  ;; void glLightModeli( GLenum pname, GLint param )
  (define-function void glLightModeli (int int))

  ;; void glLightModelfv( GLenum pname, const GLfloat *params )
  (define-function void glLightModelfv (int void*))

  ;; void glLightModeliv( GLenum pname, const GLint *params )
  (define-function void glLightModeliv (int void*))

  ;; void glMaterialf( GLenum face, GLenum pname, GLfloat param )
  (define-function void glMaterialf (int int float))

  ;; void glMateriali( GLenum face, GLenum pname, GLint param )
  (define-function void glMateriali (int int int))

  ;; void glMaterialfv( GLenum face, GLenum pname, const GLfloat *params )
  ;; (define-function void glMaterialfv (int int void*))
  (define-function void glMaterialfv (int int u8*))

  ;; void glMaterialiv( GLenum face, GLenum pname, const GLint *params )
  (define-function void glMaterialiv (int int void*))

  ;; void glGetMaterialfv( GLenum face, GLenum pname, GLfloat *params )
  (define-function void glGetMaterialfv (int int void*))

  ;; void glGetMaterialiv( GLenum face, GLenum pname, GLint *params )
  (define-function void glGetMaterialiv (int int void*))

  ;; void glColorMaterial( GLenum face, GLenum mode )
  (define-function void glColorMaterial (int int))

  ;;;; Raster functions

  ;; void glPixelZoom( GLfloat xfactor, GLfloat yfactor )
  (define-function void glPixelZoom (float float))

  ;; void glPixelStoref( GLenum pname, GLfloat param )
  (define-function void glPixelStoref (int float))

  ;; void glPixelStorei( GLenum pname, GLint param )
  (define-function void glPixelStorei (int int))

  ;; void glPixelTransferf( GLenum pname, GLfloat param )
  (define-function void glPixelTransferf (int float))

  ;; void glPixelTransferi( GLenum pname, GLint param )
  (define-function void glPixelTransferi (int int))

  ;; void glPixelMapfv( GLenum map, GLsizei mapsize, const GLfloat *values )
  (define-function void glPixelMapfv (int int void*))

  ;; void glPixelMapuiv( GLenum map, GLsizei mapsize, const GLuint *values )
  (define-function void glPixelMapuiv (int int void*))

  ;; void glPixelMapusv( GLenum map, GLsizei mapsize, const GLushort *values )
  (define-function void glPixelMapusv (int int void*))

  ;; void glGetPixelMapfv( GLenum map, GLfloat *values )
  (define-function void glGetPixelMapfv (int void*))

  ;; void glGetPixelMapuiv( GLenum map, GLuint *values )
  (define-function void glGetPixelMapuiv (int void*))

  ;; void glGetPixelMapusv( GLenum map, GLushort *values )
  (define-function void glGetPixelMapusv (int void*))

  ;; void glBitmap( GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap )
  ;; (define-function void glBitmap (int int float float float float void*))
  (define-function void glBitmap (int int float float float float u8*))

  ;; void glReadPixels( GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels )
  (define-function void glReadPixels (int int int int int int void*))

  ;; void glDrawPixels( GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels )
  ;; (define-function void glDrawPixels (int int int int void*))
  (define-function void glDrawPixels (int int int int u8*))

  ;; void glCopyPixels( GLint x, GLint y, GLsizei width, GLsizei height, GLenum type )
  (define-function void glCopyPixels (int int int int int))

  ;;;; Stenciling

  ;; void glStencilFunc( GLenum func, GLint ref, GLuint mask )
  (define-function void glStencilFunc (int int int))

  ;; void glStencilMask( GLuint mask )
  (define-function void glStencilMask (int))

  ;; void glStencilOp( GLenum fail, GLenum zfail, GLenum zpass )
  (define-function void glStencilOp (int int int))

  ;; void glClearStencil( GLint s )
  (define-function void glClearStencil (int))

  ;;;; Texture mapping

  ;; void glTexGend( GLenum coord, GLenum pname, GLdouble param )
  (define-function void glTexGend (int int double))

  ;; void glTexGenf( GLenum coord, GLenum pname, GLfloat param )
  (define-function void glTexGenf (int int float))

  ;; void glTexGeni( GLenum coord, GLenum pname, GLint param )
  (define-function void glTexGeni (int int int))

  ;; void glTexGendv( GLenum coord, GLenum pname, const GLdouble *params )
  (define-function void glTexGendv (int int void*))

  ;; void glTexGenfv( GLenum coord, GLenum pname, const GLfloat *params )
  (define-function void glTexGenfv (int int void*))

  ;; void glTexGeniv( GLenum coord, GLenum pname, const GLint *params )
  (define-function void glTexGeniv (int int void*))

  ;; void glGetTexGendv( GLenum coord, GLenum pname, GLdouble *params )
  (define-function void glGetTexGendv (int int void*))

  ;; void glGetTexGenfv( GLenum coord, GLenum pname, GLfloat *params )
  (define-function void glGetTexGenfv (int int void*))

  ;; void glGetTexGeniv( GLenum coord, GLenum pname, GLint *params )
  (define-function void glGetTexGeniv (int int void*))

  ;; void glTexEnvf( GLenum target, GLenum pname, GLfloat param )
  (define-function void glTexEnvf (int int float))

  ;; void glTexEnvi( GLenum target, GLenum pname, GLint param )
  (define-function void glTexEnvi (int int int))

  ;; void glTexEnvfv( GLenum target, GLenum pname, const GLfloat *params )
  (define-function void glTexEnvfv (int int void*))

  ;; void glTexEnviv( GLenum target, GLenum pname, const GLint *params )
  (define-function void glTexEnviv (int int void*))

  ;; void glGetTexEnvfv( GLenum target, GLenum pname, GLfloat *params )
  (define-function void glGetTexEnvfv (int int void*))

  ;; void glGetTexEnviv( GLenum target, GLenum pname, GLint *params )
  (define-function void glGetTexEnviv (int int void*))

  ;; void glTexParameterf( GLenum target, GLenum pname, GLfloat param )
  (define-function void glTexParameterf (int int float))

  ;; void glTexParameteri( GLenum target, GLenum pname, GLint param )
  (define-function void glTexParameteri (int int int))

  ;; void glTexParameterfv( GLenum target, GLenum pname, const GLfloat *params )
  (define-function void glTexParameterfv (int int void*))

  ;; void glTexParameteriv( GLenum target, GLenum pname, const GLint *params )
  (define-function void glTexParameteriv (int int void*))

  ;; void glGetTexParameterfv( GLenum target, GLenum pname, GLfloat *params)
  (define-function void glGetTexParameterfv (int int void*))

  ;; void glGetTexParameteriv( GLenum target, GLenum pname, GLint *params )
  (define-function void glGetTexParameteriv (int int void*))

  ;; void glGetTexLevelParameterfv( GLenum target, GLint level, GLenum pname, GLfloat *params )
  (define-function void glGetTexLevelParameterfv (int int int void*))

  ;; void glGetTexLevelParameteriv( GLenum target, GLint level, GLenum pname, GLint *params )
  (define-function void glGetTexLevelParameteriv (int int int void*))

  ;; void glTexImage1D( GLenum target, GLint level, GLint internalFormat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels )
  (define-function void glTexImage1D (int int int int int int int void*))

  ;; void glTexImage2D( GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels )
  ;; (define-function void glTexImage2D (int int int int int int int int void*))
  (define-function void glTexImage2D (int int int int int int int int u8*))

  ;; void glGetTexImage( GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels )
  (define-function void glGetTexImage (int int int int void*))

  ;;;; 1.1 functions

  ;; void glGenTextures( GLsizei n, GLuint *textures )
  ;; (define-function void glGenTextures (int void*))
  (define-function void glGenTextures (int u32*))

  ;; void glDeleteTextures( GLsizei n, const GLuint *textures)
  (define-function void glDeleteTextures (int void*))

  ;; void glBindTexture( GLenum target, GLuint texture )
  (define-function void glBindTexture (int int))

  ;; void glPrioritizeTextures( GLsizei n, const GLuint *textures, const GLclampf *priorities )
  (define-function void glPrioritizeTextures (int void* void*))

  ;; GLboolean glAreTexturesResident( GLsizei n, const GLuint *textures, GLboolean *residences )
  (define-function int glAreTexturesResident (int void* void*))

  ;; GLboolean glIsTexture( GLuint texture )
  (define-function int glIsTexture (int))

  ;; void glTexSubImage1D( GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels )
  (define-function void glTexSubImage1D (int int int int int int void*))

  ;; void glTexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels )
  (define-function void glTexSubImage2D (int int int int int int int int void*))

  ;; void glCopyTexImage1D( GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border )
  (define-function void glCopyTexImage1D (int int int int int int int))

  ;; void glCopyTexImage2D( GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border )
  (define-function void glCopyTexImage2D (int int int int int int int int))

  ;; void glCopyTexSubImage1D( GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width )
  (define-function void glCopyTexSubImage1D (int int int int int int))

  ;; void glCopyTexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height )
  (define-function void glCopyTexSubImage2D (int int int int int int int int))

  ;;;; Evaluators

  ;; void glMap1d( GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points )
  (define-function void glMap1d (int double double int int void*))

  ;; void glMap1f( GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points )
  (define-function void glMap1f (int float float int int void*))

  ;; void glMap2d( GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points )
  (define-function void glMap2d (int double double int int double double int int void*))

  ;; void glMap2f( GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points )
  (define-function void glMap2f (int float float int int float float int int void*))

  ;; void glGetMapdv( GLenum target, GLenum query, GLdouble *v )
  (define-function void glGetMapdv (int int void*))

  ;; void glGetMapfv( GLenum target, GLenum query, GLfloat *v )
  (define-function void glGetMapfv (int int void*))

  ;; void glGetMapiv( GLenum target, GLenum query, GLint *v )
  (define-function void glGetMapiv (int int void*))

  ;; void glEvalCoord1d( GLdouble u )
  (define-function void glEvalCoord1d (double))

  ;; void glEvalCoord1f( GLfloat u )
  (define-function void glEvalCoord1f (float))

  ;; void glEvalCoord1dv( const GLdouble *u )
  (define-function void glEvalCoord1dv (void*))

  ;; void glEvalCoord1fv( const GLfloat *u )
  (define-function void glEvalCoord1fv (void*))

  ;; void glEvalCoord2d( GLdouble u, GLdouble v )
  (define-function void glEvalCoord2d (double double))

  ;; void glEvalCoord2f( GLfloat u, GLfloat v )
  (define-function void glEvalCoord2f (float float))

  ;; void glEvalCoord2dv( const GLdouble *u )
  (define-function void glEvalCoord2dv (void*))

  ;; void glEvalCoord2fv( const GLfloat *u )
  (define-function void glEvalCoord2fv (void*))

  ;; void glMapGrid1d( GLint un, GLdouble u1, GLdouble u2 )
  (define-function void glMapGrid1d (int double double))

  ;; void glMapGrid1f( GLint un, GLfloat u1, GLfloat u2 )
  (define-function void glMapGrid1f (int float float))

  ;; void glMapGrid2d( GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2 )
  (define-function void glMapGrid2d (int double double int double double))

  ;; void glMapGrid2f( GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2 )
  (define-function void glMapGrid2f (int float float int float float))

  ;; void glEvalPoint1( GLint i )
  (define-function void glEvalPoint1 (int))

  ;; void glEvalPoint2( GLint i, GLint j )
  (define-function void glEvalPoint2 (int int))

  ;; void glEvalMesh1( GLenum mode, GLint i1, GLint i2 )
  (define-function void glEvalMesh1 (int int int))

  ;; void glEvalMesh2( GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2 )
  (define-function void glEvalMesh2 (int int int int int))

  ;;;; Fog

  ;; void glFogf( GLenum pname, GLfloat param )
  (define-function void glFogf (int float))

  ;; void glFogi( GLenum pname, GLint param )
  (define-function void glFogi (int int))

  ;; void glFogfv( GLenum pname, const GLfloat *params )
  (define-function void glFogfv (int void*))

  ;; void glFogiv( GLenum pname, const GLint *params )
  (define-function void glFogiv (int void*))

  ;;;; Selection and Feedback

  ;; void glFeedbackBuffer( GLsizei size, GLenum type, GLfloat *buffer )
  (define-function void glFeedbackBuffer (int int void*))

  ;; void glPassThrough( GLfloat token )
  (define-function void glPassThrough (float))

  ;; void glSelectBuffer( GLsizei size, GLuint *buffer )
  (define-function void glSelectBuffer (int void*))

  ;; void glInitNames( void )
  (define-function void glInitNames ())

  ;; void glLoadName( GLuint name )
  (define-function void glLoadName (int))

  ;; void glPushName( GLuint name )
  (define-function void glPushName (int))

  ;; void glPopName( void )
  (define-function void glPopName ())

  ;;;; OpenGL 1.2

  ;; void glDrawRangeElements( GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices )
  (define-function void glDrawRangeElements (int int int int int void*))

  ;; void glTexImage3D( GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels )
  (define-function void glTexImage3D (int int int int int int int int int void*))

  ;; void glTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels)
  (define-function void glTexSubImage3D (int int int int int int int int int int void*))

  ;; void glCopyTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height )
  (define-function void glCopyTexSubImage3D (int int int int int int int int int))

  ;;;; GL_ARB_imaging

  ;; void glColorTable( GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table )
  (define-function void glColorTable (int int int int int void*))

  ;; void glColorSubTable( GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data )
  (define-function void glColorSubTable (int int int int int void*))

  ;; void glColorTableParameteriv(GLenum target, GLenum pname, const GLint *params)
  (define-function void glColorTableParameteriv (int int void*))

  ;; void glColorTableParameterfv(GLenum target, GLenum pname, const GLfloat *params)
  (define-function void glColorTableParameterfv (int int void*))

  ;; void glCopyColorSubTable( GLenum target, GLsizei start, GLint x, GLint y, GLsizei width )
  (define-function void glCopyColorSubTable (int int int int int))

  ;; void glCopyColorTable( GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width )
  (define-function void glCopyColorTable (int int int int int))

  ;; void glGetColorTable( GLenum target, GLenum format, GLenum type, GLvoid *table )
  (define-function void glGetColorTable (int int int void*))

  ;; void glGetColorTableParameterfv( GLenum target, GLenum pname, GLfloat *params )
  (define-function void glGetColorTableParameterfv (int int void*))

  ;; void glGetColorTableParameteriv( GLenum target, GLenum pname, GLint *params )
  (define-function void glGetColorTableParameteriv (int int void*))

  ;; void glBlendEquation( GLenum mode )
  (define-function void glBlendEquation (int))

  ;; void glBlendColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha )
  (define-function void glBlendColor (float float float float))

  ;; void glHistogram( GLenum target, GLsizei width, GLenum internalformat, GLboolean sink )
  (define-function void glHistogram (int int int int))

  ;; void glResetHistogram( GLenum target )
  (define-function void glResetHistogram (int))

  ;; void glGetHistogram( GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values )
  (define-function void glGetHistogram (int int int int void*))

  ;; void glGetHistogramParameterfv( GLenum target, GLenum pname, GLfloat *params )
  (define-function void glGetHistogramParameterfv (int int void*))

  ;; void glGetHistogramParameteriv( GLenum target, GLenum pname, GLint *params )
  (define-function void glGetHistogramParameteriv (int int void*))

  ;; void glMinmax( GLenum target, GLenum internalformat, GLboolean sink )
  (define-function void glMinmax (int int int))

  ;; void glResetMinmax( GLenum target )
  (define-function void glResetMinmax (int))

  ;; void glGetMinmax( GLenum target, GLboolean reset, GLenum format, GLenum types, GLvoid *values )
  (define-function void glGetMinmax (int int int int void*))

  ;; void glGetMinmaxParameterfv( GLenum target, GLenum pname, GLfloat *params )
  (define-function void glGetMinmaxParameterfv (int int void*))

  ;; void glGetMinmaxParameteriv( GLenum target, GLenum pname, GLint *params )
  (define-function void glGetMinmaxParameteriv (int int void*))

  ;; void glConvolutionFilter1D( GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image )
  (define-function void glConvolutionFilter1D (int int int int int void*))

  ;; void glConvolutionFilter2D( GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image )
  (define-function void glConvolutionFilter2D (int int int int int int void*))

  ;; void glConvolutionParameterf( GLenum target, GLenum pname, GLfloat params )
  (define-function void glConvolutionParameterf (int int float))

  ;; void glConvolutionParameterfv( GLenum target, GLenum pname, const GLfloat *params )
  (define-function void glConvolutionParameterfv (int int void*))

  ;; void glConvolutionParameteri( GLenum target, GLenum pname, GLint params )
  (define-function void glConvolutionParameteri (int int int))

  ;; void glConvolutionParameteriv( GLenum target, GLenum pname, const GLint *params )
  (define-function void glConvolutionParameteriv (int int void*))

  ;; void glCopyConvolutionFilter1D( GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width )
  (define-function void glCopyConvolutionFilter1D (int int int int int))

  ;; void glCopyConvolutionFilter2D( GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height)
  (define-function void glCopyConvolutionFilter2D (int int int int int int))

  ;; void glGetConvolutionFilter( GLenum target, GLenum format, GLenum type, GLvoid *image )
  (define-function void glGetConvolutionFilter (int int int void*))

  ;; void glGetConvolutionParameterfv( GLenum target, GLenum pname, GLfloat *params )
  (define-function void glGetConvolutionParameterfv (int int void*))

  ;; void glGetConvolutionParameteriv( GLenum target, GLenum pname, GLint *params )
  (define-function void glGetConvolutionParameteriv (int int void*))

  ;; void glSeparableFilter2D( GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column )
  (define-function void glSeparableFilter2D (int int int int int int void* void*))

  ;; void glGetSeparableFilter( GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span )
  (define-function void glGetSeparableFilter (int int int void* void* void*))

  ;; void glActiveTexture( GLenum texture )
  (define-function void glActiveTexture (int))

  ;; void glClientActiveTexture( GLenum texture )
  (define-function void glClientActiveTexture (int))

  ;; void glCompressedTexImage1D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data )
  (define-function void glCompressedTexImage1D (int int int int int int void*))

  ;; void glCompressedTexImage2D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data )
  (define-function void glCompressedTexImage2D (int int int int int int int void*))

  ;; void glCompressedTexImage3D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data )
  (define-function void glCompressedTexImage3D (int int int int int int int int void*))

  ;; void glCompressedTexSubImage1D( GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data )
  (define-function void glCompressedTexSubImage1D (int int int int int int void*))

  ;; void glCompressedTexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data )
  (define-function void glCompressedTexSubImage2D (int int int int int int int int void*))

  ;; void glCompressedTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data )
  (define-function void glCompressedTexSubImage3D (int int int int int int int int int int void*))

  ;; void glGetCompressedTexImage( GLenum target, GLint lod, GLvoid *img )
  (define-function void glGetCompressedTexImage (int int void*))

  ;; void glMultiTexCoord1d( GLenum target, GLdouble s )
  (define-function void glMultiTexCoord1d (int double))

  ;; void glMultiTexCoord1dv( GLenum target, const GLdouble *v )
  (define-function void glMultiTexCoord1dv (int void*))

  ;; void glMultiTexCoord1f( GLenum target, GLfloat s )
  (define-function void glMultiTexCoord1f (int float))

  ;; void glMultiTexCoord1fv( GLenum target, const GLfloat *v )
  (define-function void glMultiTexCoord1fv (int void*))

  ;; void glMultiTexCoord1i( GLenum target, GLint s )
  (define-function void glMultiTexCoord1i (int int))

  ;; void glMultiTexCoord1iv( GLenum target, const GLint *v )
  (define-function void glMultiTexCoord1iv (int void*))

  ;; void glMultiTexCoord1s( GLenum target, GLshort s )
  (define-function void glMultiTexCoord1s (int int))

  ;; void glMultiTexCoord1sv( GLenum target, const GLshort *v )
  (define-function void glMultiTexCoord1sv (int void*))

  ;; void glMultiTexCoord2d( GLenum target, GLdouble s, GLdouble t )
  (define-function void glMultiTexCoord2d (int double double))

  ;; void glMultiTexCoord2dv( GLenum target, const GLdouble *v )
  (define-function void glMultiTexCoord2dv (int void*))

  ;; void glMultiTexCoord2f( GLenum target, GLfloat s, GLfloat t )
  (define-function void glMultiTexCoord2f (int float float))

  ;; void glMultiTexCoord2fv( GLenum target, const GLfloat *v )
  (define-function void glMultiTexCoord2fv (int void*))

  ;; void glMultiTexCoord2i( GLenum target, GLint s, GLint t )
  (define-function void glMultiTexCoord2i (int int int))

  ;; void glMultiTexCoord2iv( GLenum target, const GLint *v )
  (define-function void glMultiTexCoord2iv (int void*))

  ;; void glMultiTexCoord2s( GLenum target, GLshort s, GLshort t )
  (define-function void glMultiTexCoord2s (int int int))

  ;; void glMultiTexCoord2sv( GLenum target, const GLshort *v )
  (define-function void glMultiTexCoord2sv (int void*))

  ;; void glMultiTexCoord3d( GLenum target, GLdouble s, GLdouble t, GLdouble r )
  (define-function void glMultiTexCoord3d (int double double double))

  ;; void glMultiTexCoord3dv( GLenum target, const GLdouble *v )
  (define-function void glMultiTexCoord3dv (int void*))

  ;; void glMultiTexCoord3f( GLenum target, GLfloat s, GLfloat t, GLfloat r )
  (define-function void glMultiTexCoord3f (int float float float))

  ;; void glMultiTexCoord3fv( GLenum target, const GLfloat *v )
  (define-function void glMultiTexCoord3fv (int void*))

  ;; void glMultiTexCoord3i( GLenum target, GLint s, GLint t, GLint r )
  (define-function void glMultiTexCoord3i (int int int int))

  ;; void glMultiTexCoord3iv( GLenum target, const GLint *v )
  (define-function void glMultiTexCoord3iv (int void*))

  ;; void glMultiTexCoord3s( GLenum target, GLshort s, GLshort t, GLshort r )
  (define-function void glMultiTexCoord3s (int int int int))

  ;; void glMultiTexCoord3sv( GLenum target, const GLshort *v )
  (define-function void glMultiTexCoord3sv (int void*))

  ;; void glMultiTexCoord4d( GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q )
  (define-function void glMultiTexCoord4d (int double double double double))

  ;; void glMultiTexCoord4dv( GLenum target, const GLdouble *v )
  (define-function void glMultiTexCoord4dv (int void*))

  ;; void glMultiTexCoord4f( GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q )
  (define-function void glMultiTexCoord4f (int float float float float))

  ;; void glMultiTexCoord4fv( GLenum target, const GLfloat *v )
  (define-function void glMultiTexCoord4fv (int void*))

  ;; void glMultiTexCoord4i( GLenum target, GLint s, GLint t, GLint r, GLint q )
  (define-function void glMultiTexCoord4i (int int int int int))

  ;; void glMultiTexCoord4iv( GLenum target, const GLint *v )
  (define-function void glMultiTexCoord4iv (int void*))

  ;; void glMultiTexCoord4s( GLenum target, GLshort s, GLshort t, GLshort r, GLshort q )
  (define-function void glMultiTexCoord4s (int int int int int))

  ;; void glMultiTexCoord4sv( GLenum target, const GLshort *v )
  (define-function void glMultiTexCoord4sv (int void*))

  ;; void glLoadTransposeMatrixd( const GLdouble *m ) /* void glLoadTransposeMatrixd( const GLdouble m[16] ) */
  (define-function void glLoadTransposeMatrixd (void*))

  ;; void glLoadTransposeMatrixf( const GLfloat *m ) /* void glLoadTransposeMatrixf( const GLfloat m[16] ) */
  (define-function void glLoadTransposeMatrixf (void*))

  ;; void glMultTransposeMatrixd( const GLdouble *m ) /* void glMultTransposeMatrixd( const GLdouble m[16] ) */
  (define-function void glMultTransposeMatrixd (void*))

  ;; void glMultTransposeMatrixf( const GLfloat *m ) /* void glMultTransposeMatrixf( const GLfloat m[16] ) */
  (define-function void glMultTransposeMatrixf (void*))

  ;; void glSampleCoverage( GLclampf value, GLboolean invert )
  (define-function void glSampleCoverage (float int))

  ;;;; OpenGL 1.3

  ;; void glActiveTextureARB(GLenum texture)
  (define-function void glActiveTextureARB (int))

  ;; void glClientActiveTextureARB(GLenum texture)
  (define-function void glClientActiveTextureARB (int))

  ;; void glMultiTexCoord1dARB(GLenum target, GLdouble s)
  (define-function void glMultiTexCoord1dARB (int double))

  ;; void glMultiTexCoord1dvARB(GLenum target, const GLdouble *v)
  (define-function void glMultiTexCoord1dvARB (int void*))

  ;; void glMultiTexCoord1fARB(GLenum target, GLfloat s)
  (define-function void glMultiTexCoord1fARB (int float))

  ;; void glMultiTexCoord1fvARB(GLenum target, const GLfloat *v)
  (define-function void glMultiTexCoord1fvARB (int void*))

  ;; void glMultiTexCoord1iARB(GLenum target, GLint s)
  (define-function void glMultiTexCoord1iARB (int int))

  ;; void glMultiTexCoord1ivARB(GLenum target, const GLint *v)
  (define-function void glMultiTexCoord1ivARB (int void*))

  ;; void glMultiTexCoord1sARB(GLenum target, GLshort s)
  (define-function void glMultiTexCoord1sARB (int int))

  ;; void glMultiTexCoord1svARB(GLenum target, const GLshort *v)
  (define-function void glMultiTexCoord1svARB (int void*))

  ;; void glMultiTexCoord2dARB(GLenum target, GLdouble s, GLdouble t)
  (define-function void glMultiTexCoord2dARB (int double double))

  ;; void glMultiTexCoord2dvARB(GLenum target, const GLdouble *v)
  (define-function void glMultiTexCoord2dvARB (int void*))

  ;; void glMultiTexCoord2fARB(GLenum target, GLfloat s, GLfloat t)
  (define-function void glMultiTexCoord2fARB (int float float))

  ;; void glMultiTexCoord2fvARB(GLenum target, const GLfloat *v)
  (define-function void glMultiTexCoord2fvARB (int void*))

  ;; void glMultiTexCoord2iARB(GLenum target, GLint s, GLint t)
  (define-function void glMultiTexCoord2iARB (int int int))

  ;; void glMultiTexCoord2ivARB(GLenum target, const GLint *v)
  (define-function void glMultiTexCoord2ivARB (int void*))

  ;; void glMultiTexCoord2sARB(GLenum target, GLshort s, GLshort t)
  (define-function void glMultiTexCoord2sARB (int int int))

  ;; void glMultiTexCoord2svARB(GLenum target, const GLshort *v)
  (define-function void glMultiTexCoord2svARB (int void*))

  ;; void glMultiTexCoord3dARB(GLenum target, GLdouble s, GLdouble t, GLdouble r)
  (define-function void glMultiTexCoord3dARB (int double double double))

  ;; void glMultiTexCoord3dvARB(GLenum target, const GLdouble *v)
  (define-function void glMultiTexCoord3dvARB (int void*))

  ;; void glMultiTexCoord3fARB(GLenum target, GLfloat s, GLfloat t, GLfloat r)
  (define-function void glMultiTexCoord3fARB (int float float float))

  ;; void glMultiTexCoord3fvARB(GLenum target, const GLfloat *v)
  (define-function void glMultiTexCoord3fvARB (int void*))

  ;; void glMultiTexCoord3iARB(GLenum target, GLint s, GLint t, GLint r)
  (define-function void glMultiTexCoord3iARB (int int int int))

  ;; void glMultiTexCoord3ivARB(GLenum target, const GLint *v)
  (define-function void glMultiTexCoord3ivARB (int void*))

  ;; void glMultiTexCoord3sARB(GLenum target, GLshort s, GLshort t, GLshort r)
  (define-function void glMultiTexCoord3sARB (int int int int))

  ;; void glMultiTexCoord3svARB(GLenum target, const GLshort *v)
  (define-function void glMultiTexCoord3svARB (int void*))

  ;; void glMultiTexCoord4dARB(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q)
  (define-function void glMultiTexCoord4dARB (int double double double double))

  ;; void glMultiTexCoord4dvARB(GLenum target, const GLdouble *v)
  (define-function void glMultiTexCoord4dvARB (int void*))

  ;; void glMultiTexCoord4fARB(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q)
  (define-function void glMultiTexCoord4fARB (int float float float float))

  ;; void glMultiTexCoord4fvARB(GLenum target, const GLfloat *v)
  (define-function void glMultiTexCoord4fvARB (int void*))

  ;; void glMultiTexCoord4iARB(GLenum target, GLint s, GLint t, GLint r, GLint q)
  (define-function void glMultiTexCoord4iARB (int int int int int))

  ;; void glMultiTexCoord4ivARB(GLenum target, const GLint *v)
  (define-function void glMultiTexCoord4ivARB (int void*))

  ;; void glMultiTexCoord4sARB(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q)
  (define-function void glMultiTexCoord4sARB (int int int int int))

  ;; void glMultiTexCoord4svARB(GLenum target, const GLshort *v)
  (define-function void glMultiTexCoord4svARB (int void*))

  )

Added glu.sls.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664

;;; Ypsilon Scheme System
;;; Copyright (c) 2004-2009 Y.FUJITA / LittleWing Company Limited.
;;; See license.txt for terms and conditions of use.

;;; Ported to Chez Scheme by Ed Cavazos (wayo.cavazos@gmail.com)

(library (glu)

  (export GLU_EXT_object_space_tess
          GLU_EXT_nurbs_tessellator
          GLU_FALSE
          GLU_TRUE
          GLU_VERSION_1_1
          GLU_VERSION_1_2
          GLU_VERSION_1_3
          GLU_VERSION
          GLU_EXTENSIONS
          GLU_INVALID_ENUM
          GLU_INVALID_VALUE
          GLU_OUT_OF_MEMORY
          GLU_INCOMPATIBLE_GL_VERSION
          GLU_INVALID_OPERATION
          GLU_OUTLINE_POLYGON
          GLU_OUTLINE_PATCH
          GLU_NURBS_ERROR
          GLU_ERROR
          GLU_NURBS_BEGIN
          GLU_NURBS_BEGIN_EXT
          GLU_NURBS_VERTEX
          GLU_NURBS_VERTEX_EXT
          GLU_NURBS_NORMAL
          GLU_NURBS_NORMAL_EXT
          GLU_NURBS_COLOR
          GLU_NURBS_COLOR_EXT
          GLU_NURBS_TEXTURE_COORD
          GLU_NURBS_TEX_COORD_EXT
          GLU_NURBS_END
          GLU_NURBS_END_EXT
          GLU_NURBS_BEGIN_DATA
          GLU_NURBS_BEGIN_DATA_EXT
          GLU_NURBS_VERTEX_DATA
          GLU_NURBS_VERTEX_DATA_EXT
          GLU_NURBS_NORMAL_DATA
          GLU_NURBS_NORMAL_DATA_EXT
          GLU_NURBS_COLOR_DATA
          GLU_NURBS_COLOR_DATA_EXT
          GLU_NURBS_TEXTURE_COORD_DATA
          GLU_NURBS_TEX_COORD_DATA_EXT
          GLU_NURBS_END_DATA
          GLU_NURBS_END_DATA_EXT
          GLU_NURBS_ERROR1
          GLU_NURBS_ERROR2
          GLU_NURBS_ERROR3
          GLU_NURBS_ERROR4
          GLU_NURBS_ERROR5
          GLU_NURBS_ERROR6
          GLU_NURBS_ERROR7
          GLU_NURBS_ERROR8
          GLU_NURBS_ERROR9
          GLU_NURBS_ERROR10
          GLU_NURBS_ERROR11
          GLU_NURBS_ERROR12
          GLU_NURBS_ERROR13
          GLU_NURBS_ERROR14
          GLU_NURBS_ERROR15
          GLU_NURBS_ERROR16
          GLU_NURBS_ERROR17
          GLU_NURBS_ERROR18
          GLU_NURBS_ERROR19
          GLU_NURBS_ERROR20
          GLU_NURBS_ERROR21
          GLU_NURBS_ERROR22
          GLU_NURBS_ERROR23
          GLU_NURBS_ERROR24
          GLU_NURBS_ERROR25
          GLU_NURBS_ERROR26
          GLU_NURBS_ERROR27
          GLU_NURBS_ERROR28
          GLU_NURBS_ERROR29
          GLU_NURBS_ERROR30
          GLU_NURBS_ERROR31
          GLU_NURBS_ERROR32
          GLU_NURBS_ERROR33
          GLU_NURBS_ERROR34
          GLU_NURBS_ERROR35
          GLU_NURBS_ERROR36
          GLU_NURBS_ERROR37
          GLU_AUTO_LOAD_MATRIX
          GLU_CULLING
          GLU_SAMPLING_TOLERANCE
          GLU_DISPLAY_MODE
          GLU_PARAMETRIC_TOLERANCE
          GLU_SAMPLING_METHOD
          GLU_U_STEP
          GLU_V_STEP
          GLU_NURBS_MODE
          GLU_NURBS_MODE_EXT
          GLU_NURBS_TESSELLATOR
          GLU_NURBS_TESSELLATOR_EXT
          GLU_NURBS_RENDERER
          GLU_NURBS_RENDERER_EXT
          GLU_OBJECT_PARAMETRIC_ERROR
          GLU_OBJECT_PARAMETRIC_ERROR_EXT
          GLU_OBJECT_PATH_LENGTH
          GLU_OBJECT_PATH_LENGTH_EXT
          GLU_PATH_LENGTH
          GLU_PARAMETRIC_ERROR
          GLU_DOMAIN_DISTANCE
          GLU_MAP1_TRIM_2
          GLU_MAP1_TRIM_3
          GLU_POINT
          GLU_LINE
          GLU_FILL
          GLU_SILHOUETTE
          GLU_SMOOTH
          GLU_FLAT
          GLU_NONE
          GLU_OUTSIDE
          GLU_INSIDE
          GLU_TESS_BEGIN
          GLU_BEGIN
          GLU_TESS_VERTEX
          GLU_VERTEX
          GLU_TESS_END
          GLU_END
          GLU_TESS_ERROR
          GLU_TESS_EDGE_FLAG
          GLU_EDGE_FLAG
          GLU_TESS_COMBINE
          GLU_TESS_BEGIN_DATA
          GLU_TESS_VERTEX_DATA
          GLU_TESS_END_DATA
          GLU_TESS_ERROR_DATA
          GLU_TESS_EDGE_FLAG_DATA
          GLU_TESS_COMBINE_DATA
          GLU_CW
          GLU_CCW
          GLU_INTERIOR
          GLU_EXTERIOR
          GLU_UNKNOWN
          GLU_TESS_WINDING_RULE
          GLU_TESS_BOUNDARY_ONLY
          GLU_TESS_TOLERANCE
          GLU_TESS_ERROR1
          GLU_TESS_ERROR2
          GLU_TESS_ERROR3
          GLU_TESS_ERROR4
          GLU_TESS_ERROR5
          GLU_TESS_ERROR6
          GLU_TESS_ERROR7
          GLU_TESS_ERROR8
          GLU_TESS_MISSING_BEGIN_POLYGON
          GLU_TESS_MISSING_BEGIN_CONTOUR
          GLU_TESS_MISSING_END_POLYGON
          GLU_TESS_MISSING_END_CONTOUR
          GLU_TESS_COORD_TOO_LARGE
          GLU_TESS_NEED_COMBINE_CALLBACK
          GLU_TESS_WINDING_ODD
          GLU_TESS_WINDING_NONZERO
          GLU_TESS_WINDING_POSITIVE
          GLU_TESS_WINDING_NEGATIVE
          GLU_TESS_WINDING_ABS_GEQ_TWO
          GLU_TESS_MAX_COORD
          gluBeginCurve
          gluBeginPolygon
          gluBeginSurface
          gluBeginTrim
          gluBuild1DMipmapLevels
          gluBuild1DMipmaps
          gluBuild2DMipmapLevels
          gluBuild2DMipmaps
          gluBuild3DMipmapLevels
          gluBuild3DMipmaps
          gluCheckExtension
          gluCylinder
          gluDeleteNurbsRenderer
          gluDeleteQuadric
          gluDeleteTess
          gluDisk
          gluEndCurve
          gluEndPolygon
          gluEndSurface
          gluEndTrim
          gluErrorString
          gluGetNurbsProperty
          gluGetString
          gluGetTessProperty
          gluLoadSamplingMatrices
          gluLookAt
          gluNewNurbsRenderer
          gluNewQuadric
          gluNewTess
          gluNextContour

          ;; gluNurbsCallback

          gluNurbsCallbackData
          gluNurbsCallbackDataEXT
          gluNurbsCurve
          gluNurbsProperty
          gluNurbsSurface
          gluOrtho2D
          gluPartialDisk
          gluPerspective
          gluPickMatrix
          gluProject
          gluPwlCurve

          ;; gluQuadricCallback

          gluQuadricDrawStyle
          gluQuadricNormals
          gluQuadricOrientation
          gluQuadricTexture
          gluScaleImage
          gluSphere
          gluTessBeginContour
          gluTessBeginPolygon

          ;; gluTessCallback
          
          gluTessEndContour
          gluTessEndPolygon
          gluTessNormal
          gluTessProperty
          gluTessVertex
          gluUnProject
          gluUnProject4)
  
  (import (chezscheme))

  ;; (define lib-name
  ;;   (cond (on-linux   "libGLU.so.1")
  ;;         (on-sunos   "libGLU.so.1")
  ;;         (on-freebsd "libGLU.so")
  ;;         (on-openbsd "libGLU.so.7.0")
  ;;         (on-darwin  "OpenGL.framework/OpenGL")
  ;;         (on-windows "glu32.dll")
  ;;         (else
  ;;          (assertion-violation
  ;;           #f
  ;;           "can not locate GLU library, unknown operating system"))))

  ;; (define lib (load-shared-object lib-name))

  (define no-op (load-shared-object "libGLU.so.1"))

  ;; (define-syntax define-function
  ;;   (syntax-rules ()
  ;;     ((_ ret name args)
  ;;      (define name (c-function lib lib-name ret __stdcall name args)))))

  (define-syntax define-function
    (syntax-rules ()
      ((_ ret name args)
       (define name
         (foreign-procedure (symbol->string 'name) args ret)))))

  ;;;; Extensions
  (define GLU_EXT_object_space_tess          1)
  (define GLU_EXT_nurbs_tessellator          1)
  ;;;; Boolean
  (define GLU_FALSE                          0)
  (define GLU_TRUE                           1)
  ;;;; Version
  (define GLU_VERSION_1_1                    1)
  (define GLU_VERSION_1_2                    1)
  (define GLU_VERSION_1_3                    1)
  ;;;; StringName
  (define GLU_VERSION                        100800)
  (define GLU_EXTENSIONS                     100801)
  ;;;; ErrorCode
  (define GLU_INVALID_ENUM                   100900)
  (define GLU_INVALID_VALUE                  100901)
  (define GLU_OUT_OF_MEMORY                  100902)
  (define GLU_INCOMPATIBLE_GL_VERSION        100903)
  (define GLU_INVALID_OPERATION              100904)
  ;;;; NurbsDisplay
  ;;;;    GLU_FILL
  (define GLU_OUTLINE_POLYGON                100240)
  (define GLU_OUTLINE_PATCH                  100241)
  ;;;; NurbsCallback
  (define GLU_NURBS_ERROR                    100103)
  (define GLU_ERROR                          100103)
  (define GLU_NURBS_BEGIN                    100164)
  (define GLU_NURBS_BEGIN_EXT                100164)
  (define GLU_NURBS_VERTEX                   100165)
  (define GLU_NURBS_VERTEX_EXT               100165)
  (define GLU_NURBS_NORMAL                   100166)
  (define GLU_NURBS_NORMAL_EXT               100166)
  (define GLU_NURBS_COLOR                    100167)
  (define GLU_NURBS_COLOR_EXT                100167)
  (define GLU_NURBS_TEXTURE_COORD            100168)
  (define GLU_NURBS_TEX_COORD_EXT            100168)
  (define GLU_NURBS_END                      100169)
  (define GLU_NURBS_END_EXT                  100169)
  (define GLU_NURBS_BEGIN_DATA               100170)
  (define GLU_NURBS_BEGIN_DATA_EXT           100170)
  (define GLU_NURBS_VERTEX_DATA              100171)
  (define GLU_NURBS_VERTEX_DATA_EXT          100171)
  (define GLU_NURBS_NORMAL_DATA              100172)
  (define GLU_NURBS_NORMAL_DATA_EXT          100172)
  (define GLU_NURBS_COLOR_DATA               100173)
  (define GLU_NURBS_COLOR_DATA_EXT           100173)
  (define GLU_NURBS_TEXTURE_COORD_DATA       100174)
  (define GLU_NURBS_TEX_COORD_DATA_EXT       100174)
  (define GLU_NURBS_END_DATA                 100175)
  (define GLU_NURBS_END_DATA_EXT             100175)
  ;;;; NurbsError
  (define GLU_NURBS_ERROR1                   100251)
  (define GLU_NURBS_ERROR2                   100252)
  (define GLU_NURBS_ERROR3                   100253)
  (define GLU_NURBS_ERROR4                   100254)
  (define GLU_NURBS_ERROR5                   100255)
  (define GLU_NURBS_ERROR6                   100256)
  (define GLU_NURBS_ERROR7                   100257)
  (define GLU_NURBS_ERROR8                   100258)
  (define GLU_NURBS_ERROR9                   100259)
  (define GLU_NURBS_ERROR10                  100260)
  (define GLU_NURBS_ERROR11                  100261)
  (define GLU_NURBS_ERROR12                  100262)
  (define GLU_NURBS_ERROR13                  100263)
  (define GLU_NURBS_ERROR14                  100264)
  (define GLU_NURBS_ERROR15                  100265)
  (define GLU_NURBS_ERROR16                  100266)
  (define GLU_NURBS_ERROR17                  100267)
  (define GLU_NURBS_ERROR18                  100268)
  (define GLU_NURBS_ERROR19                  100269)
  (define GLU_NURBS_ERROR20                  100270)
  (define GLU_NURBS_ERROR21                  100271)
  (define GLU_NURBS_ERROR22                  100272)
  (define GLU_NURBS_ERROR23                  100273)
  (define GLU_NURBS_ERROR24                  100274)
  (define GLU_NURBS_ERROR25                  100275)
  (define GLU_NURBS_ERROR26                  100276)
  (define GLU_NURBS_ERROR27                  100277)
  (define GLU_NURBS_ERROR28                  100278)
  (define GLU_NURBS_ERROR29                  100279)
  (define GLU_NURBS_ERROR30                  100280)
  (define GLU_NURBS_ERROR31                  100281)
  (define GLU_NURBS_ERROR32                  100282)
  (define GLU_NURBS_ERROR33                  100283)
  (define GLU_NURBS_ERROR34                  100284)
  (define GLU_NURBS_ERROR35                  100285)
  (define GLU_NURBS_ERROR36                  100286)
  (define GLU_NURBS_ERROR37                  100287)
  ;;;; NurbsProperty
  (define GLU_AUTO_LOAD_MATRIX               100200)
  (define GLU_CULLING                        100201)
  (define GLU_SAMPLING_TOLERANCE             100203)
  (define GLU_DISPLAY_MODE                   100204)
  (define GLU_PARAMETRIC_TOLERANCE           100202)
  (define GLU_SAMPLING_METHOD                100205)
  (define GLU_U_STEP                         100206)
  (define GLU_V_STEP                         100207)
  (define GLU_NURBS_MODE                     100160)
  (define GLU_NURBS_MODE_EXT                 100160)
  (define GLU_NURBS_TESSELLATOR              100161)
  (define GLU_NURBS_TESSELLATOR_EXT          100161)
  (define GLU_NURBS_RENDERER                 100162)
  (define GLU_NURBS_RENDERER_EXT             100162)
  ;;;; NurbsSampling
  (define GLU_OBJECT_PARAMETRIC_ERROR        100208)
  (define GLU_OBJECT_PARAMETRIC_ERROR_EXT    100208)
  (define GLU_OBJECT_PATH_LENGTH             100209)
  (define GLU_OBJECT_PATH_LENGTH_EXT         100209)
  (define GLU_PATH_LENGTH                    100215)
  (define GLU_PARAMETRIC_ERROR               100216)
  (define GLU_DOMAIN_DISTANCE                100217)
  ;;;; NurbsTrim
  (define GLU_MAP1_TRIM_2                    100210)
  (define GLU_MAP1_TRIM_3                    100211)
  ;;;; QuadricDrawStyle
  (define GLU_POINT                          100010)
  (define GLU_LINE                           100011)
  (define GLU_FILL                           100012)
  (define GLU_SILHOUETTE                     100013)
  ;;;; QuadricCallback
  ;;;;    GLU_ERROR
  ;;;; QuadricNormal
  (define GLU_SMOOTH                         100000)
  (define GLU_FLAT                           100001)
  (define GLU_NONE                           100002)
  ;;;; QuadricOrientation
  (define GLU_OUTSIDE                        100020)
  (define GLU_INSIDE                         100021)
  ;;;; TessCallback
  (define GLU_TESS_BEGIN                     100100)
  (define GLU_BEGIN                          100100)
  (define GLU_TESS_VERTEX                    100101)
  (define GLU_VERTEX                         100101)
  (define GLU_TESS_END                       100102)
  (define GLU_END                            100102)
  (define GLU_TESS_ERROR                     100103)
  (define GLU_TESS_EDGE_FLAG                 100104)
  (define GLU_EDGE_FLAG                      100104)
  (define GLU_TESS_COMBINE                   100105)
  (define GLU_TESS_BEGIN_DATA                100106)
  (define GLU_TESS_VERTEX_DATA               100107)
  (define GLU_TESS_END_DATA                  100108)
  (define GLU_TESS_ERROR_DATA                100109)
  (define GLU_TESS_EDGE_FLAG_DATA            100110)
  (define GLU_TESS_COMBINE_DATA              100111)
  ;;;; TessContour
  (define GLU_CW                             100120)
  (define GLU_CCW                            100121)
  (define GLU_INTERIOR                       100122)
  (define GLU_EXTERIOR                       100123)
  (define GLU_UNKNOWN                        100124)
  ;;;; TessProperty
  (define GLU_TESS_WINDING_RULE              100140)
  (define GLU_TESS_BOUNDARY_ONLY             100141)
  (define GLU_TESS_TOLERANCE                 100142)
  ;;;; TessError
  (define GLU_TESS_ERROR1                    100151)
  (define GLU_TESS_ERROR2                    100152)
  (define GLU_TESS_ERROR3                    100153)
  (define GLU_TESS_ERROR4                    100154)
  (define GLU_TESS_ERROR5                    100155)
  (define GLU_TESS_ERROR6                    100156)
  (define GLU_TESS_ERROR7                    100157)
  (define GLU_TESS_ERROR8                    100158)
  (define GLU_TESS_MISSING_BEGIN_POLYGON     100151)
  (define GLU_TESS_MISSING_BEGIN_CONTOUR     100152)
  (define GLU_TESS_MISSING_END_POLYGON       100153)
  (define GLU_TESS_MISSING_END_CONTOUR       100154)
  (define GLU_TESS_COORD_TOO_LARGE           100155)
  (define GLU_TESS_NEED_COMBINE_CALLBACK     100156)
  ;;;; TessWinding
  (define GLU_TESS_WINDING_ODD               100130)
  (define GLU_TESS_WINDING_NONZERO           100131)
  (define GLU_TESS_WINDING_POSITIVE          100132)
  (define GLU_TESS_WINDING_NEGATIVE          100133)
  (define GLU_TESS_WINDING_ABS_GEQ_TWO       100134)
  (define GLU_TESS_MAX_COORD                 1.0e150)

  ;; void gluBeginCurve (GLUnurbs* nurb)
  (define-function void gluBeginCurve (void*))

  ;; void gluBeginPolygon (GLUtesselator* tess)
  (define-function void gluBeginPolygon (void*))

  ;; void gluBeginSurface (GLUnurbs* nurb)
  (define-function void gluBeginSurface (void*))

  ;; void gluBeginTrim (GLUnurbs* nurb)
  (define-function void gluBeginTrim (void*))

  ;; GLint gluBuild1DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void* data)
  (define-function int gluBuild1DMipmapLevels (unsigned-int int int unsigned-int unsigned-int int int int void*))

  ;; GLint gluBuild1DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLenum format, GLenum type, const void* data)
  (define-function int gluBuild1DMipmaps (unsigned-int int int unsigned-int unsigned-int void*))

  ;; GLint gluBuild2DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void* data)
  (define-function int gluBuild2DMipmapLevels (unsigned-int int int int unsigned-int unsigned-int int int int void*))

  ;; GLint gluBuild2DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* data)
  (define-function int gluBuild2DMipmaps (unsigned-int int int int unsigned-int unsigned-int void*))

  ;; GLint gluBuild3DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void* data)
  (define-function int gluBuild3DMipmapLevels (unsigned-int int int int int unsigned-int unsigned-int int int int void*))

  ;; GLint gluBuild3DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* data)
  (define-function int gluBuild3DMipmaps (unsigned-int int int int int unsigned-int unsigned-int void*))

  ;; GLboolean gluCheckExtension (const GLubyte* extName, const GLubyte* extString)

  (define-function unsigned-8 gluCheckExtension (void* void*))

  ;; void gluCylinder (GLUquadric* quad, GLdouble base, GLdouble top, GLdouble height, GLint slices, GLint stacks)
  (define-function void gluCylinder (void* double double double int int))

  ;; void gluDeleteNurbsRenderer (GLUnurbs* nurb)
  (define-function void gluDeleteNurbsRenderer (void*))

  ;; void gluDeleteQuadric (GLUquadric* quad)
  (define-function void gluDeleteQuadric (void*))

  ;; void gluDeleteTess (GLUtesselator* tess)
  (define-function void gluDeleteTess (void*))

  ;; void gluDisk (GLUquadric* quad, GLdouble inner, GLdouble outer, GLint slices, GLint loops)
  (define-function void gluDisk (void* double double int int))

  ;; void gluEndCurve (GLUnurbs* nurb)
  (define-function void gluEndCurve (void*))

  ;; void gluEndPolygon (GLUtesselator* tess)
  (define-function void gluEndPolygon (void*))

  ;; void gluEndSurface (GLUnurbs* nurb)
  (define-function void gluEndSurface (void*))

  ;; void gluEndTrim (GLUnurbs* nurb)
  (define-function void gluEndTrim (void*))

  ;; const GLubyte* gluErrorString (GLenum error)
  (define-function void* gluErrorString (unsigned-int))

  ;; void gluGetNurbsProperty (GLUnurbs* nurb, GLenum property, GLfloat* data)
  (define-function void gluGetNurbsProperty (void* unsigned-int void*))

  ;; const GLubyte* gluGetString (GLenum name)
  (define-function void* gluGetString (unsigned-int))

  ;; void gluGetTessProperty (GLUtesselator* tess, GLenum which, GLdouble* data)
  (define-function void gluGetTessProperty (void* unsigned-int void*))

  ;; void gluLoadSamplingMatrices (GLUnurbs* nurb, const GLfloat* model, const GLfloat* perspective, const GLint* view)
  (define-function void gluLoadSamplingMatrices (void* void* void* void*))

  ;; void gluLookAt (GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ, GLdouble centerX, GLdouble centerY, GLdouble centerZ, GLdouble upX, GLdouble upY, GLdouble upZ)
  (define-function void gluLookAt (double double double double double double double double double))

  ;; GLUnurbs* gluNewNurbsRenderer (void)
  (define-function void* gluNewNurbsRenderer ())

  ;; GLUquadric* gluNewQuadric (void)
  (define-function void* gluNewQuadric ())

  ;; GLUtesselator* gluNewTess (void)
  (define-function void* gluNewTess ())

  ;; void gluNextContour (GLUtesselator* tess, GLenum type)
  (define-function void gluNextContour (void* unsigned-int))

  ;; void gluNurbsCallbackData (GLUnurbs* nurb, GLvoid* userData)
  (define-function void gluNurbsCallbackData (void* void*))

  ;; void gluNurbsCallbackDataEXT (GLUnurbs* nurb, GLvoid* userData)
  (define-function void gluNurbsCallbackDataEXT (void* void*))

  ;; void gluNurbsCurve (GLUnurbs* nurb, GLint knotCount, GLfloat* knots, GLint stride, GLfloat* control, GLint order, GLenum type)
  (define-function void gluNurbsCurve (void* int void* int void* int unsigned-int))

  ;; void gluNurbsProperty (GLUnurbs* nurb, GLenum property, GLfloat value)
  (define-function void gluNurbsProperty (void* unsigned-int float))

  ;; void gluNurbsSurface (GLUnurbs* nurb, GLint sKnotCount, GLfloat* sKnots, GLint tKnotCount, GLfloat* tKnots, GLint sStride, GLint tStride, GLfloat* control, GLint sOrder, GLint tOrder, GLenum type)
  (define-function void gluNurbsSurface (void* int void* int void* int int void* int int unsigned-int))

  ;; void gluOrtho2D (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top)
  (define-function void gluOrtho2D (double double double double))

  ;; void gluPartialDisk (GLUquadric* quad, GLdouble inner, GLdouble outer, GLint slices, GLint loops, GLdouble start, GLdouble sweep)
  (define-function void gluPartialDisk (void* double double int int double double))

  ;; void gluPerspective (GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar)
  (define-function void gluPerspective (double double double double))

  ;; void gluPickMatrix (GLdouble x, GLdouble y, GLdouble delX, GLdouble delY, GLint *viewport)
  (define-function void gluPickMatrix (double double double double int))

  ;; GLint gluProject (GLdouble objX, GLdouble objY, GLdouble objZ, const GLdouble* model, const GLdouble* proj, const GLint *view, GLdouble* winX, GLdouble* winY, GLdouble* winZ)
  (define-function int gluProject (double double double void* void* int void* void* void*))

  ;; void gluPwlCurve (GLUnurbs* nurb, GLint count, GLfloat* data, GLint stride, GLenum type)
  (define-function void gluPwlCurve (void* int void* int unsigned-int))

  ;; void gluQuadricDrawStyle (GLUquadric* quad, GLenum draw)
  (define-function void gluQuadricDrawStyle (void* unsigned-int))

  ;; void gluQuadricNormals (GLUquadric* quad, GLenum normal)
  (define-function void gluQuadricNormals (void* unsigned-int))

  ;; void gluQuadricOrientation (GLUquadric* quad, GLenum orientation)
  (define-function void gluQuadricOrientation (void* unsigned-int))

  ;; void gluQuadricTexture (GLUquadric* quad, GLboolean texture)
  (define-function void gluQuadricTexture (void* unsigned-8))

  ;; GLint gluScaleImage (GLenum format, GLsizei wIn, GLsizei hIn, GLenum typeIn, const void* dataIn, GLsizei wOut, GLsizei hOut, GLenum typeOut, GLvoid* dataOut)
  (define-function int gluScaleImage (unsigned-int int int unsigned-int void* int int unsigned-int void*))

  ;; void gluSphere (GLUquadric* quad, GLdouble radius, GLint slices, GLint stacks)
  (define-function void gluSphere (void* double int int))

  ;; void gluTessBeginContour (GLUtesselator* tess)
  (define-function void gluTessBeginContour (void*))

  ;; void gluTessBeginPolygon (GLUtesselator* tess, GLvoid* data)
  (define-function void gluTessBeginPolygon (void* void*))

  ;; void gluTessEndContour (GLUtesselator* tess)
  (define-function void gluTessEndContour (void*))

  ;; void gluTessEndPolygon (GLUtesselator* tess)
  (define-function void gluTessEndPolygon (void*))

  ;; void gluTessNormal (GLUtesselator* tess, GLdouble valueX, GLdouble valueY, GLdouble valueZ)
  (define-function void gluTessNormal (void* double double double))

  ;; void gluTessProperty (GLUtesselator* tess, GLenum which, GLdouble data)
  (define-function void gluTessProperty (void* unsigned-int double))

  ;; void gluTessVertex (GLUtesselator* tess, GLdouble* location, GLvoid* data)
  (define-function void gluTessVertex (void* void* void*))

  ;; GLint gluUnProject (GLdouble winX, GLdouble winY, GLdouble winZ, const GLdouble* model, const GLdouble* proj, const GLint *view, GLdouble* objX, GLdouble* objY, GLdouble* objZ)
  (define-function int gluUnProject (double double double void* void* int void* void* void*))

  ;; GLint gluUnProject4 (GLdouble winX, GLdouble winY, GLdouble winZ, GLdouble clipW, const GLdouble* model, const GLdouble* proj, const GLint *view, GLdouble nearVal, GLdouble farVal, GLdouble* objX, GLdouble* objY, GLdouble* objZ, GLdouble* objW)
  (define-function int gluUnProject4 (double double double double void* void* int double double void* void* void* void*))

  ;; void gluNurbsCallback (GLUnurbs* nurb, GLenum which, _GLUfuncptr CallBackFunc)

  ;; (define gluNurbsCallback
  ;;   (let ((thunk (c-function lib lib-name void __stdcall gluNurbsCallback (void* unsigned-int void*)))
  ;;         (alist `((,GLU_NURBS_BEGIN int)
  ;;                  (,GLU_NURBS_VERTEX float)
  ;;                  (,GLU_NURBS_NORMAL float)
  ;;                  (,GLU_NURBS_COLOR float)
  ;;                  (,GLU_NURBS_TEXTURE_COORD float)
  ;;                  (,GLU_NURBS_END)
  ;;                  (,GLU_NURBS_BEGIN_DATA int void*)
  ;;                  (,GLU_NURBS_VERTEX_DATA float void*)
  ;;                  (,GLU_NURBS_NORMAL_DATA float void*)
  ;;                  (,GLU_NURBS_COLOR_DATA float void*)
  ;;                  (,GLU_NURBS_TEXTURE_COORD_DATA float void*)
  ;;                  (,GLU_NURBS_END_DATA void*)
  ;;                  (,GLU_NURBS_ERROR int))))
  ;;     (lambda (nurb which callback)
  ;;       (if (procedure? callback)
  ;;           (let ((lst (assv which alist)))
  ;;             (or lst (assertion-violation 'gluNurbsCallback "invalid value in argument 2" (list nurb which callback)))
  ;;             (thunk nurb which (make-stdcall-callback 'void (cdr lst) callback)))
  ;;           (thunk nurb which callback)))))

  ;; void gluQuadricCallback (GLUquadric* quad, GLenum which, _GLUfuncptr CallBackFunc)

  ;; (define gluQuadricCallback
  ;;   (let ((thunk (c-function lib lib-name void __stdcall gluQuadricCallback (void* unsigned-int void*))))
  ;;     (lambda (quad which callback)
  ;;       (or (eqv? which GLU_ERROR)
  ;;           (assertion-violation 'gluQuadricCallback "invalid value in argument 2" (list quad which callback)))
  ;;       (if (procedure? callback)
  ;;           (thunk quad which (make-stdcall-callback 'void '(unsigned-int) callback))
  ;;           (thunk quad which callback)))))

  ;; void gluTessCallback (GLUtesselator* tess, GLenum which, _GLUfuncptr CallBackFunc)
  ;; (define gluTessCallback
  ;;   (let ((thunk (c-function lib lib-name void __stdcall gluTessCallback (void* unsigned-int void*)))
  ;;         (alist `((,GLU_TESS_BEGIN unsigned-int)
  ;;                  (,GLU_TESS_BEGIN_DATA unsigned-int void*)
  ;;                  (,GLU_TESS_EDGE_FLAG uint8_t)
  ;;                  (,GLU_TESS_EDGE_FLAG_DATA uint8_t void*)
  ;;                  (,GLU_TESS_VERTEX void*)
  ;;                  (,GLU_TESS_VERTEX_DATA void* void*)
  ;;                  (,GLU_TESS_END)
  ;;                  (,GLU_TESS_END_DATA void*)
  ;;                  (,GLU_TESS_COMBINE void* void* void* void*)
  ;;                  (,GLU_TESS_COMBINE_DATA void* void* void* void* void*)
  ;;                  (,GLU_TESS_ERROR unsigned-int)
  ;;                  (,GLU_TESS_ERROR_DATA unsigned-int void*))))
  ;;     (lambda (tess which callback)
  ;;       (if (procedure? callback)
  ;;           (let ((lst (assv which alist)))
  ;;             (or lst (assertion-violation 'gluTessCallback "invalid value in argument 2" (list tess which callback)))
  ;;             (thunk tess which (make-stdcall-callback 'void (cdr lst) callback)))
  ;;           (thunk tess which callback)))))

  ) ;[end]

Added glut.sls.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684

;;; Ypsilon Scheme System
;;; Copyright (c) 2004-2009 Y.FUJITA / LittleWing Company Limited.
;;; See license.txt for terms and conditions of use.

;;; Ported to Chez Scheme by Ed Cavazos (wayo.cavazos@gmail.com)

(library (glut)
  (export GLUT_RGB
          GLUT_RGBA
          GLUT_INDEX
          GLUT_SINGLE
          GLUT_DOUBLE
          GLUT_ACCUM
          GLUT_ALPHA
          GLUT_DEPTH
          GLUT_STENCIL
          GLUT_MULTISAMPLE
          GLUT_STEREO
          GLUT_LUMINANCE
          GLUT_NO_RECOVERY
          GLUT_LEFT_BUTTON
          GLUT_MIDDLE_BUTTON
          GLUT_RIGHT_BUTTON
          GLUT_DOWN
          GLUT_UP
          GLUT_KEY_F1
          GLUT_KEY_F2
          GLUT_KEY_F3
          GLUT_KEY_F4
          GLUT_KEY_F5
          GLUT_KEY_F6
          GLUT_KEY_F7
          GLUT_KEY_F8
          GLUT_KEY_F9
          GLUT_KEY_F10
          GLUT_KEY_F11
          GLUT_KEY_F12
          GLUT_KEY_LEFT
          GLUT_KEY_UP
          GLUT_KEY_RIGHT
          GLUT_KEY_DOWN
          GLUT_KEY_PAGE_UP
          GLUT_KEY_PAGE_DOWN
          GLUT_KEY_HOME
          GLUT_KEY_END
          GLUT_KEY_INSERT
          GLUT_LEFT
          GLUT_ENTERED
          GLUT_MENU_NOT_IN_USE
          GLUT_MENU_IN_USE
          GLUT_NOT_VISIBLE
          GLUT_VISIBLE
          GLUT_HIDDEN
          GLUT_FULLY_RETAINED
          GLUT_PARTIALLY_RETAINED
          GLUT_FULLY_COVERED
          GLUT_RED
          GLUT_GREEN
          GLUT_BLUE
          GLUT_NORMAL
          GLUT_OVERLAY
          glutInit
          glutInitDisplayString
          glutInitDisplayMode
          glutInitWindowPosition
          glutInitWindowSize
          glutMainLoop
          glutCreateWindow
          glutCreateSubWindow
          glutDestroyWindow
          glutPostRedisplay
          glutPostWindowRedisplay
          glutSwapBuffers
          glutGetWindow
          glutSetWindow
          glutSetWindowTitle
          glutSetIconTitle
          glutPositionWindow
          glutReshapeWindow
          glutPopWindow
          glutPushWindow
          glutIconifyWindow
          glutShowWindow
          glutHideWindow
          glutFullScreen
          glutSetCursor
          glutWarpPointer
          glutEstablishOverlay
          glutRemoveOverlay
          glutUseLayer
          glutPostOverlayRedisplay
          glutPostWindowOverlayRedisplay
          glutShowOverlay
          glutHideOverlay
          glutCreateMenu
          glutDestroyMenu
          glutGetMenu
          glutSetMenu
          glutAddMenuEntry
          glutAddSubMenu
          glutChangeToMenuEntry
          glutChangeToSubMenu
          glutRemoveMenuItem
          glutAttachMenu
          glutDetachMenu
          glutDisplayFunc
          glutReshapeFunc
          glutKeyboardFunc
          glutMouseFunc
          glutMotionFunc
          glutPassiveMotionFunc
          glutEntryFunc
          glutVisibilityFunc
          glutIdleFunc
          glutTimerFunc
          glutMenuStateFunc
          glutSpecialFunc
          glutSpaceballMotionFunc
          glutSpaceballRotateFunc
          glutSpaceballButtonFunc
          glutButtonBoxFunc
          glutDialsFunc
          glutTabletMotionFunc
          glutTabletButtonFunc
          glutMenuStatusFunc
          glutOverlayDisplayFunc
          glutWindowStatusFunc
          glutKeyboardUpFunc
          glutSpecialUpFunc
          glutJoystickFunc
          glutSetColor
          glutGetColor
          glutCopyColormap
          glutGet
          glutDeviceGet
          glutExtensionSupported
          glutGetModifiers
          glutLayerGet
          glutGetProcAddress
          glutBitmapCharacter
          glutBitmapWidth
          glutStrokeCharacter
          glutStrokeWidth
          glutBitmapLength
          glutStrokeLength
          glutWireSphere
          glutSolidSphere
          glutWireCone
          glutSolidCone
          glutWireCube
          glutSolidCube
          glutWireTorus
          glutSolidTorus
          glutWireDodecahedron
          glutSolidDodecahedron
          glutWireTeapot
          glutSolidTeapot
          glutWireOctahedron
          glutSolidOctahedron
          glutWireTetrahedron
          glutSolidTetrahedron
          glutWireIcosahedron
          glutSolidIcosahedron
          glutVideoResizeGet
          glutSetupVideoResizing
          glutStopVideoResizing
          glutVideoResize
          glutVideoPan
          glutReportErrors
          glutIgnoreKeyRepeat
          glutSetKeyRepeat
          glutForceJoystickFunc
          glutGameModeString
          glutEnterGameMode
          glutLeaveGameMode
          glutGameModeGet)
  
  (import (chezscheme))

  ;; (define libGLUT
  ;;   (cond (on-darwin  (load-shared-object "GLUT.framework/GLUT"))
  ;;         (on-windows (load-shared-object "glut32.dll"))
  ;;         (on-linux   (load-shared-object "libglut.so.3"))
  ;;         (on-freebsd (load-shared-object "libglut.so"))
  ;;         (on-openbsd (begin
  ;;                       (load-shared-object "libXmu.so.10.0")
  ;;                       (load-shared-object "libGLU.so.7.0")
  ;;                       (load-shared-object "libglut.so.3.7")))
  ;;         (else
  ;;          (assertion-violation
  ;;           #f
  ;;           "can not locate GLUT library, unknown operating system"))))

  (define no-op (load-shared-object "libglut.so.3"))

  ;; Display mode bit masks.
  (define GLUT_RGB                0)
  (define GLUT_RGBA               GLUT_RGB)
  (define GLUT_INDEX              1)
  (define GLUT_SINGLE             0)
  (define GLUT_DOUBLE             2)
  (define GLUT_ACCUM              4)
  (define GLUT_ALPHA              8)
  (define GLUT_DEPTH              16)
  (define GLUT_STENCIL            32)
  (define GLUT_MULTISAMPLE        128)
  (define GLUT_STEREO             256)
  (define GLUT_LUMINANCE          512)
  (define GLUT_NO_RECOVERY        1024)

  ;; Mouse buttons.
  (define GLUT_LEFT_BUTTON        0)
  (define GLUT_MIDDLE_BUTTON      1)
  (define GLUT_RIGHT_BUTTON       2)

  ;; Mouse button  state.
  (define GLUT_DOWN               0)
  (define GLUT_UP                 1)

  ;; function keys
  (define GLUT_KEY_F1             1)
  (define GLUT_KEY_F2             2)
  (define GLUT_KEY_F3             3)
  (define GLUT_KEY_F4             4)
  (define GLUT_KEY_F5             5)
  (define GLUT_KEY_F6             6)
  (define GLUT_KEY_F7             7)
  (define GLUT_KEY_F8             8)
  (define GLUT_KEY_F9             9)
  (define GLUT_KEY_F10            10)
  (define GLUT_KEY_F11            11)
  (define GLUT_KEY_F12            12)

  ;; directional keys
  (define GLUT_KEY_LEFT           100)
  (define GLUT_KEY_UP             101)
  (define GLUT_KEY_RIGHT          102)
  (define GLUT_KEY_DOWN           103)
  (define GLUT_KEY_PAGE_UP        104)
  (define GLUT_KEY_PAGE_DOWN      105)
  (define GLUT_KEY_HOME           106)
  (define GLUT_KEY_END            107)
  (define GLUT_KEY_INSERT         108)

  ;; Entry/exit  state.
  (define GLUT_LEFT               0)
  (define GLUT_ENTERED            1)

  ;; Menu usage  state.
  (define GLUT_MENU_NOT_IN_USE    0)
  (define GLUT_MENU_IN_USE        1)

  ;; Visibility  state.
  (define GLUT_NOT_VISIBLE        0)
  (define GLUT_VISIBLE            1)

  ;; Window status  state.
  (define GLUT_HIDDEN             0)
  (define GLUT_FULLY_RETAINED     1)
  (define GLUT_PARTIALLY_RETAINED 2)
  (define GLUT_FULLY_COVERED      3)

  ;; Color index component selection values.
  (define GLUT_RED                0)
  (define GLUT_GREEN              1)
  (define GLUT_BLUE               2)

  ;; Layers for use.
  (define GLUT_NORMAL             0)
  (define GLUT_OVERLAY            1)

  ;; (define-syntax define-function
  ;;   (syntax-rules ()
  ;;     ((_ ret name args)
  ;;      (define name
  ;;        (c-function libGLUT "GLUT library" ret __stdcall name args)))))

  (define-syntax define-function
    (syntax-rules ()
      ((_ ret name args)
       (define name
         (foreign-procedure (symbol->string 'name) args ret)))))

  (define-syntax define-function/single-callback
    (syntax-rules (callback)
      ((_ ret name ((callback c-ret c-params)))
       (define name
         (let ((f (foreign-procedure (symbol->string 'name) (int) ret)))
           (lambda (proc)
             (let ((code (foreign-callable proc c-params c-ret)))
               (lock-object code)
               (f (foreign-callable-entry-point code)))))))))

  ;; void glutInit(int *argcp, char **argv)
  ;; (define-function void glutInit ([int] [char*]))

  ;; (define glutInit
  ;;   (if on-windows
  ;;       (lambda (a1 a2)
  ;;         #;(c-argument 'glutInit 1 [int] a1)
  ;;         #;(c-argument 'glutInit 2 [char*] a2)
  ;;         ((c-function libGLUT "GLUT library" void __stdcall __glutInitWithExit ([int] [char*] [c-callback void (int)]))
  ;;          a1 a2 (lambda (n) (exit n))))
  ;;       (c-function libGLUT "GLUT library" void __stdcall glutInit ([int] [char*]))))

  ;; (define glutInit
  ;;   (foreign-procedure "glutInit" (u8* u8*) void))

  ;; This version ignores it's arguments.
  
  (define glutInit
    (let ((f (foreign-procedure "glutInit" (u8* u8*) void)))
      (lambda (a b)
        (f (bytevector 0 0 0 0)
           (bytevector 0)))))

  ;; void glutInitDisplayString(const char *string)
  (define-function void glutInitDisplayString (string))

  ;; void glutInitDisplayMode(unsigned int mode)
  (define-function void glutInitDisplayMode (int))

  ;; void glutInitWindowPosition(int x, int y)
  (define-function void glutInitWindowPosition (int int))

  ;; void glutInitWindowSize(int width, int height)
  (define-function void glutInitWindowSize (int int))

  ;; void glutMainLoop(void)
  (define-function void glutMainLoop ())

  ;; int glutCreateWindow(const char *title)
  (define-function int glutCreateWindow (string))

  ;; int glutCreateSubWindow(int win, int x, int y, int width, int height)
  (define-function int glutCreateSubWindow (int int int int int))

  ;; void glutDestroyWindow(int win)
  (define-function void glutDestroyWindow (int))

  ;; void glutPostRedisplay(void)
  (define-function void glutPostRedisplay ())

  ;; void glutPostWindowRedisplay(int win)
  (define-function void glutPostWindowRedisplay (int))

  ;; void glutSwapBuffers(void)
  (define-function void glutSwapBuffers ())

  ;; int glutGetWindow(void)
  (define-function int glutGetWindow ())

  ;; void glutSetWindow(int win)
  (define-function void glutSetWindow (int))

  ;; void glutSetWindowTitle(const char *title)
  (define-function void glutSetWindowTitle (string))

  ;; void glutSetIconTitle(const char *title)
  (define-function void glutSetIconTitle (string))

  ;; void glutPositionWindow(int x, int y)
  (define-function void glutPositionWindow (int int))

  ;; void glutReshapeWindow(int width, int height)
  (define-function void glutReshapeWindow (int int))

  ;; void glutPopWindow(void)
  (define-function void glutPopWindow ())

  ;; void glutPushWindow(void)
  (define-function void glutPushWindow ())

  ;; void glutIconifyWindow(void)
  (define-function void glutIconifyWindow ())

  ;; void glutShowWindow(void)
  (define-function void glutShowWindow ())

  ;; void glutHideWindow(void)
  (define-function void glutHideWindow ())

  ;; void glutFullScreen(void)
  (define-function void glutFullScreen ())

  ;; void glutSetCursor(int cursor)
  (define-function void glutSetCursor (int))

  ;; void glutWarpPointer(int x, int y)
  (define-function void glutWarpPointer (int int))

  ;; void glutEstablishOverlay(void)
  (define-function void glutEstablishOverlay ())

  ;; void glutRemoveOverlay(void)
  (define-function void glutRemoveOverlay ())

  ;; void glutUseLayer(GLenum layer)
  (define-function void glutUseLayer (int))

  ;; void glutPostOverlayRedisplay(void)
  (define-function void glutPostOverlayRedisplay ())

  ;; void glutPostWindowOverlayRedisplay(int win)
  (define-function void glutPostWindowOverlayRedisplay (int))

  ;; void glutShowOverlay(void)
  (define-function void glutShowOverlay ())

  ;; void glutHideOverlay(void)
  (define-function void glutHideOverlay ())

  ;; int glutCreateMenu(void (*)(int))

  ;; (define-function void glutCreateMenu ([c-callback void (int)]))

  (define-function/single-callback void glutCreateMenu ((callback void (int))))

  ;; void glutDestroyMenu(int menu)
  (define-function void glutDestroyMenu (int))

  ;; int glutGetMenu(void)
  (define-function int glutGetMenu ())

  ;; void glutSetMenu(int menu)
  (define-function void glutSetMenu (int))

  ;; void glutAddMenuEntry(const char *label, int value)
  (define-function void glutAddMenuEntry (string int))

  ;; void glutAddSubMenu(const char *label, int submenu)
  (define-function void glutAddSubMenu (string int))

  ;; void glutChangeToMenuEntry(int item, const char *label, int value)
  (define-function void glutChangeToMenuEntry (int string int))

  ;; void glutChangeToSubMenu(int item, const char *label, int submenu)
  (define-function void glutChangeToSubMenu (int string int))

  ;; void glutRemoveMenuItem(int item)
  (define-function void glutRemoveMenuItem (int))

  ;; void glutAttachMenu(int button)
  (define-function void glutAttachMenu (int))

  ;; void glutDetachMenu(int button)
  (define-function void glutDetachMenu (int))

  ;; void glutDisplayFunc(void (*func)(void))
  ;; (define-function void glutDisplayFunc ([c-callback void ()]))

  (define-function/single-callback void glutDisplayFunc ((callback void ())))

  ;; void glutReshapeFunc(void (*func)(int width, int height))
  ;; (define-function void glutReshapeFunc ([c-callback void (int int)]))

  (define-function/single-callback void glutReshapeFunc ([callback void (int int)]))

  ;; void glutKeyboardFunc(void (*func)(unsigned char key, int x, int y))
  (define-function/single-callback void glutKeyboardFunc ([callback void (int int int)]))

  ;; void glutMouseFunc(void (*func)(int button, int state, int x, int y))
  (define-function/single-callback void glutMouseFunc ([callback void (int int int int)]))

  ;; void glutMotionFunc(void (*func)(int x, int y))
  (define-function/single-callback void glutMotionFunc ([callback void (int int)]))

  ;; void glutPassiveMotionFunc(void (*func)(int x, int y))
  (define-function/single-callback void glutPassiveMotionFunc ([callback void (int int)]))

  ;; void glutEntryFunc(void (*func)(int state))
  (define-function/single-callback void glutEntryFunc ([callback void (int)]))

  ;; void glutVisibilityFunc(void (*func)(int state))
  (define-function/single-callback void glutVisibilityFunc ([callback void (int)]))

  ;; void glutIdleFunc(void (*func)(void))
  (define-function/single-callback void glutIdleFunc ([callback void ()]))

  ;; void glutTimerFunc(unsigned int millis, void (*func)(int value), int value)
  ;; (define-function void glutTimerFunc (int [c-callback void (int)] int))

  (define glutTimerFunc
    (let ((f (foreign-procedure "glutTimerFunc" (unsigned-int int int) void)))
      (lambda (millis proc value)
        (let ((code (foreign-callable proc (int) void)))
          (lock-object code)
          (f millis
             (foreign-callable-entry-point code)
             value)))))

  ;; void glutMenuStateFunc(void (*func)(int state))
  (define-function/single-callback void glutMenuStateFunc ([callback void (int)]))

  ;; void glutSpecialFunc(void (*func)(int key, int x, int y))
  (define-function/single-callback void glutSpecialFunc ([callback void (int int int)]))

  ;; void glutSpaceballMotionFunc(void (*func)(int x, int y, int z))
  (define-function/single-callback void glutSpaceballMotionFunc ([callback void (int int int)]))

  ;; void glutSpaceballRotateFunc(void (*func)(int x, int y, int z))
  (define-function/single-callback void glutSpaceballRotateFunc ([callback void (int int int)]))

  ;; void glutSpaceballButtonFunc(void (*func)(int button, int state))
  (define-function/single-callback void glutSpaceballButtonFunc ([callback void (int int)]))

  ;; void glutButtonBoxFunc(void (*func)(int button, int state))
  (define-function/single-callback void glutButtonBoxFunc ([callback void (int int)]))

  ;; void glutDialsFunc(void (*func)(int dial, int value))
  (define-function/single-callback void glutDialsFunc ([callback void (int int)]))

  ;; void glutTabletMotionFunc(void (*func)(int x, int y))
  (define-function/single-callback void glutTabletMotionFunc ([callback void (int int)]))

  ;; void glutTabletButtonFunc(void (*func)(int button, int state, int x, int y))
  (define-function/single-callback void glutTabletButtonFunc ([callback void (int int int int)]))

  ;; void glutMenuStatusFunc(void (*func)(int status, int x, int y))
  (define-function/single-callback void glutMenuStatusFunc ([callback void (int int int)]))

  ;; void glutOverlayDisplayFunc(void (*func)(void))
  (define-function/single-callback void glutOverlayDisplayFunc ([callback void ()]))

  ;; void glutWindowStatusFunc(void (*func)(int state))
  (define-function/single-callback void glutWindowStatusFunc ([callback void (int)]))

  ;; void glutKeyboardUpFunc(void (*func)(unsigned char key, int x, int y))
  (define-function/single-callback void glutKeyboardUpFunc ([callback void (int int int)]))

  ;; void glutSpecialUpFunc(void (*func)(int key, int x, int y))
  (define-function/single-callback void glutSpecialUpFunc ([callback void (int int int)]))

  ;; void glutJoystickFunc(void (*func)(unsigned int buttonMask, int x, int y, int z), int pollInterval)
  ;; (define-function void glutJoystickFunc ([c-callback void (int int int int)] int))

  (define glutJoystickFunc
    (let ((f (foreign-procedure "glutJoystickFunc" (int int) void)))
      (lambda (proc poll-interval)
        (let ((code (foreign-callable proc (unsigned-int int int int) void)))
          (lock-object code)
          (f (foreign-callable-entry-point code)
             poll-interval)))))

  ;; void glutSetColor(int, GLfloat red, GLfloat green, GLfloat blue)
  (define-function void glutSetColor (int float float float))

  ;; GLfloat glutGetColor(int ndx, int component)
  (define-function double glutGetColor (int int))

  ;; void glutCopyColormap(int win)
  (define-function void glutCopyColormap (int))

  ;; int glutGet(GLenum type)
  (define-function int glutGet (int))

  ;; int glutDeviceGet(GLenum type)
  (define-function int glutDeviceGet (int))

  ;; int glutExtensionSupported(const char *name)
  (define-function int glutExtensionSupported (string))

  ;; int glutGetModifiers(void)
  (define-function int glutGetModifiers ())

  ;; int glutLayerGet(GLenum type)
  (define-function int glutLayerGet (int))

  ;; void * glutGetProcAddress(const char *procName)
  (define-function void* glutGetProcAddress (string))

  ;; void glutBitmapCharacter(void *font, int character)
  (define-function void* glutBitmapCharacter (void* int))

  ;; int glutBitmapWidth(void *font, int character)
  (define-function int glutBitmapWidth (void* int))

  ;; void glutStrokeCharacter(void *font, int character)
  (define-function void glutStrokeCharacter (void* int))

  ;; int glutStrokeWidth(void *font, int character)
  (define-function int glutStrokeWidth (void* int))

  ;; int glutBitmapLength(void *font, const unsigned char *string)
  (define-function int glutBitmapLength (void* string))

  ;; int glutStrokeLength(void *font, const unsigned char *string)
  (define-function int glutStrokeLength (void* string))

  ;; void glutWireSphere(GLdouble radius, GLint slices, GLint stacks)
  (define-function int glutWireSphere (double int int))

  ;; void glutSolidSphere(GLdouble radius, GLint slices, GLint stacks)
  (define-function void glutSolidSphere (double int int))

  ;; void glutWireCone(GLdouble base, GLdouble height, GLint slices, GLint stacks)
  (define-function void glutWireCone (double double int int))

  ;; void glutSolidCone(GLdouble base, GLdouble height, GLint slices, GLint stacks)
  (define-function void glutSolidCone (double double int int))

  ;; void glutWireCube(GLdouble size)
  (define-function void glutWireCube (double))

  ;; void glutSolidCube(GLdouble size)
  (define-function void glutSolidCube (double))

  ;; void glutWireTorus(GLdouble innerRadius, GLdouble outerRadius, GLint sides, GLint rings)
  (define-function void glutWireTorus (double double int int))

  ;; void glutSolidTorus(GLdouble innerRadius, GLdouble outerRadius, GLint sides, GLint rings)
  (define-function void glutSolidTorus (double double int int))

  ;; void glutWireDodecahedron(void)
  (define-function void glutWireDodecahedron ())

  ;; void glutSolidDodecahedron(void)
  (define-function void glutSolidDodecahedron ())

  ;; void glutWireTeapot(GLdouble size)
  (define-function void glutWireTeapot (double))

  ;; void glutSolidTeapot(GLdouble size)
  (define-function void glutSolidTeapot (double))

  ;; void glutWireOctahedron(void)
  (define-function void glutWireOctahedron ())

  ;; void glutSolidOctahedron(void)
  (define-function void glutSolidOctahedron ())

  ;; void glutWireTetrahedron(void)
  (define-function void glutWireTetrahedron ())

  ;; void glutSolidTetrahedron(void)
  (define-function void glutSolidTetrahedron ())

  ;; void glutWireIcosahedron(void)
  (define-function void glutWireIcosahedron ())

  ;; void glutSolidIcosahedron(void)
  (define-function void glutSolidIcosahedron ())

  ;; int glutVideoResizeGet(GLenum param)
  (define-function int glutVideoResizeGet ())

  ;; void glutSetupVideoResizing(void)
  (define-function int glutSetupVideoResizing ())

  ;; void glutStopVideoResizing(void)
  (define-function void glutStopVideoResizing ())

  ;; void glutVideoResize(int x, int y, int width, int height)
  (define-function void glutVideoResize (int int int int))

  ;; void glutVideoPan(int x, int y, int width, int height)
  (define-function void glutVideoPan (int int int int))

  ;; void glutReportErrors(void)
  (define-function void glutReportErrors ())

  ;; void glutIgnoreKeyRepeat(int ignore)
  (define-function void glutIgnoreKeyRepeat (int))

  ;; void glutSetKeyRepeat(int repeatMode)
  (define-function void glutSetKeyRepeat (int))

  ;; void glutForceJoystickFunc(void)
  (define-function void glutForceJoystickFunc ())

  ;; void glutGameModeString(const char *string)
  (define-function void glutGameModeString (string))

  ;; int glutEnterGameMode(void)
  (define-function int glutEnterGameMode ())

  ;; void glutLeaveGameMode(void)
  (define-function void glutLeaveGameMode ())

  ;; int glutGameModeGet(GLenum mode)
  (define-function int glutGameModeGet (int))

  )

Added irregex-utils.sls.





























































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
;;; Chez-Scheme library for Alex Shinn's Irregex
;;; 
;;; Copyright (c) 2016 Federico Beffa <beffa@fbengineering.ch>
;;; 
;;; Permission to use, copy, modify, and distribute this software for
;;; any purpose with or without fee is hereby granted, provided that the
;;; above copyright notice and this permission notice appear in all
;;; copies.
;;; 
;;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
;;; WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
;;; AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
;;; DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
;;; OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
;;; TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
;;; PERFORMANCE OF THIS SOFTWARE.

(library (irregex-utils)
  (export
   irregex-quote
   irregex-opt
   sre->string)
  (import 
    (except (rnrs) error find filter remove)
    (only (chezscheme) include get-output-string open-output-string)
    (irregex)
    (only (srfi :1) every))

  ;; definition from irregex
  (define (error msg . args)
    (display msg)
    (for-each (lambda (x) (display " ") (write x)) args)
    (newline)
    (0))
  ;;;; irregex-utils.scm
;;
;; Copyright (c) 2010 Alex Shinn.  All rights reserved.
;; BSD-style license: http://synthcode.com/license.txt

(define rx-special-chars
  "\\|[](){}.*+?^$#")

(define (string-scan-char str c . o)
  (let ((end (string-length str)))
    (let scan ((i (if (pair? o) (car o) 0)))
      (cond ((= i end) #f)
            ((eqv? c (string-ref str i)) i)
            (else (scan (+ i 1)))))))

(define (irregex-quote str)
  (list->string
   (let loop ((ls (string->list str)) (res '()))
     (if (null? ls)
         (reverse res)
         (let ((c (car ls)))
           (if (string-scan-char rx-special-chars c)
               (loop (cdr ls) (cons c (cons #\\ res)))
               (loop (cdr ls) (cons c res))))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(define (irregex-opt ls)
  (define (make-alt ls)
    (cond ((null? (cdr ls)) (car ls))
          ((every char? ls) (list (list->string ls)))
          (else (cons 'or ls))))
  (define (make-seq ls)
    (cond ((null? (cdr ls)) (car ls))
          ((every (lambda (x) (or (string? x) (char? x))) ls)
           (apply string-append (map (lambda (x) (if (char? x) (string x) x)) ls)))
          (else (cons 'seq ls))))
  (cond
   ((null? ls) "")
   ((null? (cdr ls)) (car ls))
   (else
    (let ((chars (make-vector 256 '())))
      (let lp1 ((ls ls) (empty? #f))
        (if (null? ls)
            (let lp2 ((i 0) (res '()))
              (if (= i 256)
                  (let ((res (make-alt (reverse res))))
                    (if empty? `(? ,res) res))
                  (let ((c (integer->char i))
                        (opts (vector-ref chars i)))
                    (lp2 (+ i 1)
                         (cond
                          ((null? opts) res)
                          ((equal? opts '("")) `(,c ,@res))
                          (else `(,(make-seq (list c (irregex-opt opts)))
                                  ,@res)))))))
            (let* ((str (car ls))
                   (len (string-length str)))
              (if (zero? len)
                  (lp1 (cdr ls) #t)
                  (let ((i (char->integer (string-ref str 0))))
                    (vector-set!
                     chars
                     i
                     (cons (substring str 1 len) (vector-ref chars i)))
                    (lp1 (cdr ls) empty?))))))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(define (cset->string ls)
  (let ((out (open-output-string)))
    (let lp ((ls ls))
      (cond
       ((pair? ls)
        (cond
         ((pair? (car ls))
          (display (irregex-quote (string (caar ls))) out)
          (write-char #\- out)
          (display (irregex-quote (string (cdar ls))) out))
         (else (display (irregex-quote (string (car ls))) out)))
        (lp (cdr ls)))))
    (get-output-string out)))

(define (sre->string obj)
  (let ((out (open-output-string)))
    (let lp ((x obj))
      (cond
       ((pair? x)
        (case (car x)
          ((: seq)
           (cond
            ((and (pair? (cddr x)) (pair? (cddr x)) (not (eq? x obj)))
             (display "(?:" out) (for-each lp (cdr x)) (display ")" out))
            (else (for-each lp (cdr x)))))
          ((submatch)
           (display "(" out) (for-each lp (cdr x)) (display ")" out))
          ((submatch-named)
           (display "(?<" out) (display (cadr x) out) (display ">" out)
           (for-each lp (cddr x)) (display ")" out))
          ((or)
           (display "(?:" out)
           (lp (cadr x))
           (for-each (lambda (x) (display "|" out) (lp x)) (cddr x))
           (display ")" out))
          ((* + ? *? ??)
           (cond
            ((pair? (cddr x))
             (display "(?:" out) (for-each lp (cdr x)) (display ")" out))
            (else (lp (cadr x))))
           (display (car x) out))
          ((not)
           (cond
            ((and (pair? (cadr x)) (eq? 'cset (caadr x)))
             (display "[^" out)
             (display (cset->string (cdadr x)) out)
             (display "]" out))
            (else (error "can't represent general 'not' in strings" x))))
          ((cset)
           (display "[" out)
           (display (cset->string (cdr x)) out)
           (display "]" out))
          ((- & / ~)
           (cond
            ((or (eq? #\~ (car x))
                 (and (eq? '- (car x)) (pair? (cdr x)) (eq? 'any (cadr x))))
             (display "[^" out)
             (display (cset->string (if (eq? #\~ (car x)) (cdr x) (cddr x))) out)
             (display "]" out))
            (else
             (lp `(cset ,@(sre->cset x))))))
          ((w/case w/nocase)
           (display "(?" out)
           (if (eq? (car x) 'w/case) (display "-" out))
           (display ":" out)
           (for-each lp (cdr x))
           (display ")" out))
          (else
           (if (string? (car x))
               (lp `(cset ,@(string->list (car x))))
               (error "unknown sre operator" x)))))
       ((symbol? x)
        (case x
          ((bos bol) (display "^" out))
          ((eos eol) (display "$" out))
          ((any nonl) (display "." out))
          (else (error "unknown sre symbol" x))))
       ((string? x)
        (display (irregex-quote x) out))
       ((char? x)
        (display (irregex-quote (string x)) out))
       (else
        (error "unknown sre pattern" x))))
    (get-output-string out)))

)

Added irregex.sls.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
;;; Chez-Scheme library for Alex Shinn's Irregex
;;; 
;;; Copyright (c) 2016 Federico Beffa <beffa@fbengineering.ch>
;;; 
;;; Permission to use, copy, modify, and distribute this software for
;;; any purpose with or without fee is hereby granted, provided that the
;;; above copyright notice and this permission notice appear in all
;;; copies.
;;; 
;;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
;;; WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
;;; AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
;;; DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
;;; OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
;;; TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
;;; PERFORMANCE OF THIS SOFTWARE.

(library (irregex)
  (export 
    irregex
    string->irregex
    sre->irregex
    string->sre
    maybe-string->sre
    irregex?
    irregex-match-data?
    irregex-new-matches
    irregex-reset-matches!
    irregex-search
    irregex-search/matches
    irregex-match
    irregex-search/chunked
    irregex-match/chunked
    irregex-fold/chunked
    make-irregex-chunker
    irregex-match-substring
    irregex-match-subchunk
    irregex-match-start-chunk
    irregex-match-end-chunk
    irregex-match-start-index
    irregex-match-end-index
    irregex-match-num-submatches
    irregex-match-names
    irregex-match-valid-index?
    irregex-fold
    irregex-replace
    irregex-replace/all
    irregex-dfa
    irregex-dfa/search
    irregex-nfa
    irregex-flags
    irregex-lengths
    irregex-names
    irregex-num-submatches
    irregex-extract
    irregex-split
    sre->cset)
  (import 
    (except (rnrs) error find filter remove)
    (rnrs r5rs)
    (rnrs mutable-pairs)
    (rnrs mutable-strings)
    (only (chezscheme) include))

  ;; definition from irregex
  (define (error msg . args)
    (display msg)
    (for-each (lambda (x) (display " ") (write x)) args)
    (newline)
    (0))
  ;;;; irregex.scm -- IrRegular Expressions
;;
;; Copyright (c) 2005-2015 Alex Shinn.  All rights reserved.
;; BSD-style license: http://synthcode.com/license.txt

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; At this moment there was a loud ring at the bell, and I could
;; hear Mrs. Hudson, our landlady, raising her voice in a wail of
;; expostulation and dismay.
;;
;; "By heaven, Holmes," I said, half rising, "I believe that
;; they are really after us."
;;
;; "No, it's not quite so bad as that.  It is the unofficial
;; force, -- the Baker Street irregulars."

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Notes
;;
;; This code should not require any porting - it should work out of
;; the box in any R[45]RS Scheme implementation.  Slight modifications
;; are needed for R6RS (a separate R6RS-compatible version is included
;; in the distribution as irregex-r6rs.scm).
;;
;; The goal of portability makes this code a little clumsy and
;; inefficient.  Future versions will include both cleanup and
;; performance tuning, but you can only go so far while staying
;; portable.  AND-LET*, SRFI-9 records and custom macros would've been
;; nice.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; History
;; 0.9.4: 2015/12/14 - performance improvement for {n,m} matches
;; 0.9.3: 2014/07/01 - R7RS library
;; 0.9.2: 2012/11/29 - fixed a bug in -fold on conditional bos patterns
;; 0.9.1: 2012/11/27 - various accumulated bugfixes
;; 0.9.0: 2012/06/03 - Using tags for match extraction from Peter Bex.
;; 0.8.3: 2011/12/18 - various accumulated bugfixes
;; 0.8.2: 2010/08/28 - (...)? submatch extraction fix and alternate
;;                     named submatches from Peter Bex
;;                     Added irregex-split, irregex-extract,
;;                     irregex-match-names and irregex-match-valid-index?
;;                     to Chicken and Guile module export lists and made
;;                     the latter accept named submatches.  The procedures
;;                     irregex-match-{start,end}-{index,chunk} now also
;;                     accept named submatches, with the index argument
;;                     made optional.  Improved argument type checks.
;;                     Disallow negative submatch index.
;;                     Improve performance of backtracking matcher.
;;                     Refactor charset handling into a consistent API
;; 0.8.1: 2010/03/09 - backtracking irregex-match fix and other small fixes
;; 0.8.0: 2010/01/20 - optimizing DFA compilation, adding SRE escapes
;;                     inside PCREs, adding utility SREs
;; 0.7.5: 2009/08/31 - adding irregex-extract and irregex-split
;;                     *-fold copies match data (use *-fold/fast for speed)
;;                     irregex-opt now returns an SRE
;; 0.7.4: 2009/05/14 - empty alternates (or) and empty csets always fail,
;;                     bugfix in default finalizer for irregex-fold/chunked
;; 0.7.3: 2009/04/14 - adding irregex-fold/chunked, minor doc fixes
;; 0.7.2: 2009/02/11 - some bugfixes, much improved documentation
;; 0.7.1: 2008/10/30 - several bugfixes (thanks to Derick Eddington)
;; 0.7.0: 2008/10/20 - support abstract chunked strings
;; 0.6.2: 2008/07/26 - minor bugfixes, allow global disabling of utf8 mode,
;;                     friendlier error messages in parsing, \Q..\E support
;; 0.6.1: 2008/07/21 - added utf8 mode, more utils, bugfixes
;;   0.6: 2008/05/01 - most of PCRE supported
;;   0.5: 2008/04/24 - fully portable R4RS, many PCRE features implemented
;;   0.4: 2008/04/17 - rewriting NFA to use efficient closure compilation,
;;                     normal strings only, but all of the spencer tests pass
;;   0.3: 2008/03/10 - adding DFA converter (normal strings only)
;;   0.2: 2005/09/27 - adding irregex-opt (like elisp's regexp-opt) utility
;;   0.1: 2005/08/18 - simple NFA interpreter over abstract chunked strings

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Data Structures

(define irregex-tag '*irregex-tag*)

(define (make-irregex dfa dfa/search nfa flags submatches lengths names)
  (vector irregex-tag dfa dfa/search nfa flags submatches lengths names))

(define (irregex? obj)
  (and (vector? obj)
       (= 8 (vector-length obj))
       (eq? irregex-tag (vector-ref obj 0))))

(define (irregex-dfa x) (vector-ref x 1))
(define (irregex-dfa/search x) (vector-ref x 2))
(define (irregex-nfa x) (vector-ref x 3))
(define (irregex-flags x) (vector-ref x 4))
(define (irregex-num-submatches x) (vector-ref x 5))
(define (irregex-lengths x) (vector-ref x 6))
(define (irregex-names x) (vector-ref x 7))

(define (vector-copy v)
  (let ((r (make-vector (vector-length v))))
    (do ((i (- (vector-length v) 1) (- i 1)))
        ((< i 0) r)
      (vector-set! r i (vector-ref v i)))))

(define (irregex-new-matches irx)
  (make-irregex-match (irregex-num-submatches irx) (irregex-names irx)))

(define (irregex-reset-matches! m)
  (do ((i (- (vector-length m) 1) (- i 1)))
      ((<= i 3) m)
    (vector-set! m i #f)))

(define (irregex-copy-matches m)
  (and (vector? m) (vector-copy m)))

(define irregex-match-tag '*irregex-match-tag*)

(define (irregex-match-data? obj)
  (and (vector? obj)
       (>= (vector-length obj) 11)
       (eq? irregex-match-tag (vector-ref obj 0))))

(define (make-irregex-match count names)
  (let ((res (make-vector (+ (* 4 (+ 2 count)) 3) #f)))
    (vector-set! res 0 irregex-match-tag)
    (vector-set! res 2 names)
    res))

(define (irregex-match-num-submatches m)
  (- (quotient (- (vector-length m) 3) 4) 2))

(define (irregex-match-chunker m)
  (vector-ref m 1))
(define (irregex-match-names m)
  (vector-ref m 2))
(define (irregex-match-chunker-set! m str)
  (vector-set! m 1 str))

(define (%irregex-match-start-chunk m n) (vector-ref m (+ 3 (* n 4))))
(define (%irregex-match-start-index m n) (vector-ref m (+ 4 (* n 4))))
(define (%irregex-match-end-chunk m n)   (vector-ref m (+ 5 (* n 4))))
(define (%irregex-match-end-index m n)   (vector-ref m (+ 6 (* n 4))))

(define (%irregex-match-fail m)
  (vector-ref m (- (vector-length m) 1)))
(define (%irregex-match-fail-set! m x)
  (vector-set! m (- (vector-length m) 1) x))

;; public interface with error checking
(define (irregex-match-start-chunk m . opt)
  (let ((n (irregex-match-numeric-index "irregex-match-start-chunk" m opt)))
    (and n (%irregex-match-start-chunk m n))))
(define (irregex-match-start-index m . opt)
  (let ((n (irregex-match-numeric-index "irregex-match-start-index" m opt)))
    (and n (%irregex-match-start-index m n))))
(define (irregex-match-end-chunk m . opt)
  (let ((n (irregex-match-numeric-index "irregex-match-end-chunk" m opt)))
    (and n (%irregex-match-end-chunk m n))))
(define (irregex-match-end-index m . opt)
  (let ((n (irregex-match-numeric-index "irregex-match-end-index" m opt)))
    (and n (%irregex-match-end-index m n))))

(define (irregex-match-start-chunk-set! m n start)
  (vector-set! m (+ 3 (* n 4)) start))
(define (irregex-match-start-index-set! m n start)
  (vector-set! m (+ 4 (* n 4)) start))
(define (irregex-match-end-chunk-set! m n end)
  (vector-set! m (+ 5 (* n 4)) end))
(define (irregex-match-end-index-set! m n end)
  (vector-set! m (+ 6 (* n 4)) end))

;; Tags use indices that are aligned to start/end positions just like the
;; match vectors.  ie, a tag 0 is a start tag, 1 is its corresponding end tag.
;; They start at 0, which requires us to map them to submatch index 1.
;; Sorry for the horrible name ;)
(define (irregex-match-chunk&index-from-tag-set! m t chunk index)
  (vector-set! m (+ 7 (* t 2)) chunk)
  (vector-set! m (+ 8 (* t 2)) index))

;; Helper procedure to convert any type of index from a rest args list
;; to a numeric index.  Named submatches are converted to their corresponding
;; numeric index, and numeric submatches are checked for validity.
;; An error is raised for invalid numeric or named indices, #f is returned
;; for defined but nonmatching indices.
(define (irregex-match-numeric-index location m opt)
  (cond
   ((not (irregex-match-data? m))
    (error (string-append location ": not match data") m))
   ((not (pair? opt)) 0)
   ((pair? (cdr opt))
    (apply error (string-append location ": too many arguments") m opt))
   (else
    (let ((n (car opt)))
      (if (number? n)
          (if (and (integer? n) (exact? n))
              (if (irregex-match-valid-numeric-index? m n)
                  (and (irregex-match-matched-numeric-index? m n) n)
                  (error (string-append location ": not a valid index")
                         m n))
              (error (string-append location ": not an exact integer") n))
          (let lp ((ls (irregex-match-names m))
                   (unknown? #t))
            (cond
             ((null? ls)
              (and unknown?
                   (error (string-append location ": unknown match name") n)))
             ((eq? n (caar ls))
              (if (%irregex-match-start-chunk m (cdar ls))
                  (cdar ls)
                  (lp (cdr ls) #f)))
             (else (lp (cdr ls) unknown?)))))))))

(define (irregex-match-valid-numeric-index? m n)
  (and (>= n 0) (< (+ 3 (* n 4)) (- (vector-length m) 4))))

(define (irregex-match-matched-numeric-index? m n)
  (and (vector-ref m (+ 4 (* n 4)))
       #t))

(define (irregex-match-valid-named-index? m n)
  (and (assq n (irregex-match-names m))
       #t))

(define (irregex-match-valid-index? m n)
  (if (not (irregex-match-data? m))
      (error "irregex-match-valid-index?: not match data" m))
  (if (integer? n)
      (if (not (exact? n))
          (error "irregex-match-valid-index?: not an exact integer" n)
          (irregex-match-valid-numeric-index? m n))
      (irregex-match-valid-named-index? m n)))

(define (irregex-match-substring m . opt)
  (let* ((n (irregex-match-numeric-index "irregex-match-substring" m opt))
         (cnk (irregex-match-chunker m)))
    (and n
         ((chunker-get-substring cnk)
          (%irregex-match-start-chunk m n)
          (%irregex-match-start-index m n)
          (%irregex-match-end-chunk m n)
          (%irregex-match-end-index m n)))))

(define (irregex-match-subchunk m . opt)
  (let* ((n (irregex-match-numeric-index "irregex-match-subchunk" m opt))
         (cnk (irregex-match-chunker m))
         (get-subchunk (chunker-get-subchunk cnk)))
    (if (not get-subchunk)
        (error "this chunk type does not support match subchunks")
        (and n (get-subchunk
                (%irregex-match-start-chunk m n)
                (%irregex-match-start-index m n)
                (%irregex-match-end-chunk m n)
                (%irregex-match-end-index m n))))))

;; chunkers tell us how to navigate through chained chunks of strings

(define (make-irregex-chunker get-next get-str . o)
  (let* ((get-start (or (and (pair? o) (car o)) (lambda (cnk) 0)))
         (o (if (pair? o) (cdr o) o))
         (get-end (or (and (pair? o) (car o))
                      (lambda (cnk) (string-length (get-str cnk)))))
         (o (if (pair? o) (cdr o) o))
         (get-substr
          (or (and (pair? o) (car o))
              (lambda (cnk1 start cnk2 end)
                (if (eq? cnk1 cnk2)
                    (substring (get-str cnk1) start end)
                    (let loop ((cnk (get-next cnk1))
                               (res (list (substring (get-str cnk1)
                                                     start
                                                     (get-end cnk1)))))
                      (if (eq? cnk cnk2)
                          (string-cat-reverse
                           (cons (substring (get-str cnk)
                                            (get-start cnk)
                                            end)
                                 res))
                          (loop (get-next cnk)
                                (cons (substring (get-str cnk)
                                                 (get-start cnk)
                                                 (get-end cnk))
                                      res))))))))
         (o (if (pair? o) (cdr o) o))
         (get-subchunk (and (pair? o) (car o))))
    (if (not (and (procedure? get-next) (procedure? get-str)
                  (procedure? get-start) (procedure? get-substr)))
        (error "make-irregex-chunker: expected a procdure"))
    (vector get-next get-str get-start get-end get-substr get-subchunk)))

(define (chunker-get-next cnk) (vector-ref cnk 0))
(define (chunker-get-str cnk) (vector-ref cnk 1))
(define (chunker-get-start cnk) (vector-ref cnk 2))
(define (chunker-get-end cnk) (vector-ref cnk 3))
(define (chunker-get-substring cnk) (vector-ref cnk 4))
(define (chunker-get-subchunk cnk) (vector-ref cnk 5))

(define (chunker-prev-chunk cnk start end)
  (if (eq? start end)
      #f
      (let ((get-next (chunker-get-next cnk)))
        (let lp ((start start))
          (let ((next (get-next start)))
            (if (eq? next end)
                start
                (and next (lp next))))))))

(define (chunker-prev-char cnk start end)
  (let ((prev (chunker-prev-chunk cnk start end)))
    (and prev
         (string-ref ((chunker-get-str cnk) prev)
                     (- ((chunker-get-end cnk) prev) 1)))))

(define (chunker-next-char cnk src)
  (let ((next ((chunker-get-next cnk) src)))
    (and next
         (string-ref ((chunker-get-str cnk) next)
                     ((chunker-get-start cnk) next)))))

(define (chunk-before? cnk a b)
  (and (not (eq? a b))
       (let ((next ((chunker-get-next cnk) a)))
         (and next
              (if (eq? next b)
                  #t
                  (chunk-before? cnk next b))))))

;; For look-behind searches, wrap an existing chunker such that it
;; returns the same results but ends at a given point.
(define (wrap-end-chunker cnk src i)
  (make-irregex-chunker
   (lambda (x) (and (not (eq? x src)) ((chunker-get-next cnk) x)))
   (chunker-get-str cnk)
   (chunker-get-start cnk)
   (lambda (x) (if (eq? x src) i ((chunker-get-end cnk) x)))
   (chunker-get-substring cnk)
   (chunker-get-subchunk cnk)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; String Utilities

;; Unicode version (skip surrogates)
(define *all-chars*
  `(/ ,(integer->char 0) ,(integer->char #xD7FF)
      ,(integer->char #xE000) ,(integer->char #x10FFFF)))

;; ASCII version, offset to not assume 0-255
;; (define *all-chars* `(/ ,(integer->char (- (char->integer #\space) 32)) ,(integer->char (+ (char->integer #\space) 223))))

;; set to #f to ignore even an explicit request for utf8 handling
(define *allow-utf8-mode?* #t)

;; (define *named-char-properties* '())

(define (string-scan-char str c . o)
  (let ((end (string-length str)))
    (let scan ((i (if (pair? o) (car o) 0)))
      (cond ((= i end) #f)
            ((eqv? c (string-ref str i)) i)
            (else (scan (+ i 1)))))))

(define (string-scan-char-escape str c . o)
  (let ((end (string-length str)))
    (let scan ((i (if (pair? o) (car o) 0)))
      (cond ((= i end) #f)
            ((eqv? c (string-ref str i)) i)
            ((eqv? c #\\) (scan (+ i 2)))
            (else (scan (+ i 1)))))))

(define (string-scan-pred str pred . o)
  (let ((end (string-length str)))
    (let scan ((i (if (pair? o) (car o) 0)))
      (cond ((= i end) #f)
            ((pred (string-ref str i)) i)
            (else (scan (+ i 1)))))))

(define (string-split-char str c)
  (let ((end (string-length str)))
    (let lp ((i 0) (from 0) (res '()))
      (define (collect) (cons (substring str from i) res))
      (cond ((>= i end) (reverse (collect)))
            ((eqv? c (string-ref str i)) (lp (+ i 1) (+ i 1) (collect)))
            (else (lp (+ i 1) from res))))))

(define (char-alphanumeric? c)
  (or (char-alphabetic? c) (char-numeric? c)))

(define (%substring=? a b start1 start2 len)
  (let lp ((i 0))
    (cond ((>= i len)
           #t)
          ((char=? (string-ref a (+ start1 i)) (string-ref b (+ start2 i)))
           (lp (+ i 1)))
          (else
           #f))))

;; SRFI-13 extracts

(define (%%string-copy! to tstart from fstart fend)
  (do ((i fstart (+ i 1))
       (j tstart (+ j 1)))
      ((>= i fend))
    (string-set! to j (string-ref from i))))

(define (string-cat-reverse string-list)
  (string-cat-reverse/aux
   (fold (lambda (s a) (+ (string-length s) a)) 0 string-list)
   string-list))

(define (string-cat-reverse/aux len string-list)
  (let ((res (make-string len)))
    (let lp ((i len) (ls string-list))
      (if (pair? ls)
          (let* ((s (car ls))
                 (slen (string-length s))
                 (i (- i slen)))
            (%%string-copy! res i s 0 slen)
            (lp i (cdr ls)))))
    res))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; List Utilities

;; like the one-arg IOTA case
(define (zero-to n)
  (if (<= n 0)
      '()
      (let lp ((i (- n 1)) (res '()))
        (if (zero? i) (cons 0 res) (lp (- i 1) (cons i res))))))

;; SRFI-1 extracts (simplified 1-ary versions)

(define (find pred ls)
  (cond ((find-tail pred ls) => car)
        (else #f)))

(define (find-tail pred ls)
  (let lp ((ls ls))
    (cond ((null? ls) #f)
          ((pred (car ls)) ls)
          (else (lp (cdr ls))))))

(define (last ls)
  (if (not (pair? ls))
      (error "can't take last of empty list" ls)
      (let lp ((ls ls))
        (if (pair? (cdr ls))
            (lp (cdr ls))
            (car ls)))))

(define (any pred ls)
  (and (pair? ls)
       (let lp ((head (car ls)) (tail (cdr ls)))
         (if (null? tail)
             (pred head)
             (or (pred head) (lp (car tail) (cdr tail)))))))

(define (every pred ls)
  (or (null? ls)
      (let lp ((head (car ls))  (tail (cdr ls)))
        (if (null? tail)
            (pred head)
            (and (pred head) (lp (car tail) (cdr tail)))))))

(define (fold kons knil ls)
  (let lp ((ls ls) (res knil))
    (if (null? ls)
        res
        (lp (cdr ls) (kons (car ls) res)))))

(define (filter pred ls)
  (let lp ((ls ls) (res '()))
    (if (null? ls)
        (reverse res)
        (lp (cdr ls) (if (pred (car ls)) (cons (car ls) res) res)))))

(define (remove pred ls)
  (let lp ((ls ls) (res '()))
    (if (null? ls)
        (reverse res)
        (lp (cdr ls) (if (pred (car ls)) res (cons (car ls) res))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Flags

(define (bit-shr n i)
  (quotient n (expt 2 i)))

(define (bit-shl n i)
  (* n (expt 2 i)))

(define (bit-not n) (- #xFFFF n))

(define (bit-ior a b)
  (cond
   ((zero? a) b)
   ((zero? b) a)
   (else
    (+ (if (or (odd? a) (odd? b)) 1 0)
       (* 2 (bit-ior (quotient a 2) (quotient b 2)))))))

(define (bit-and a b)
  (cond
   ((zero? a) 0)
   ((zero? b) 0)
   (else
    (+ (if (and (odd? a) (odd? b)) 1 0)
       (* 2 (bit-and (quotient a 2) (quotient b 2)))))))

(define (integer-log n)
  (define (b8 n r)
    (if (>= n (bit-shl 1 8)) (b4 (bit-shr n 8) (+ r 8)) (b4 n r)))
  (define (b4 n r)
    (if (>= n (bit-shl 1 4)) (b2 (bit-shr n 4) (+ r 4)) (b2 n r)))
  (define (b2 n r)
    (if (>= n (bit-shl 1 2)) (b1 (bit-shr n 2) (+ r 2)) (b1 n r)))
  (define (b1 n r) (if (>= n (bit-shl 1 1)) (+ r 1) r))
  (if (>= n (bit-shl 1 16)) (b8 (bit-shr n 16) 16) (b8 n 0)))

(define (flag-set? flags i)
  (= i (bit-and flags i)))
(define (flag-join a b)
  (if b (bit-ior a b) a))
(define (flag-clear a b)
  (bit-and a (bit-not b)))

(define ~none 0)
(define ~searcher? 1)
(define ~consumer? 2)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Parsing Embedded SREs in PCRE Strings

;; (define (with-read-from-string str i proc)
;;   (define (port-size in)
;;     (let lp ((i 0)) (if (eof-object? (read-char in)) i (lp (+ i 1)))))
;;   (let* ((len (string-length str))
;;          (tail-len (- len i))
;;          (in (open-input-string (substring str i len)))
;;          (sre (read in))
;;          (unused-len (port-size in)))
;;     (close-input-port in)
;;     (proc sre (- tail-len unused-len))))

(define close-token (list 'close))
(define dot-token (string->symbol "."))

(define (with-read-from-string str i proc)
  (define end (string-length str))
  (define (read i k)
    (cond
     ((>= i end) (error "unterminated embedded SRE" str))
     (else
      (case (string-ref str i)
        ((#\()
         (let lp ((i (+ i 1)) (ls '()))
           (read
            i
            (lambda (x j)
              (cond
               ((eq? x close-token)
                (k (reverse ls) j))
               ((eq? x dot-token)
                (if (null? ls)
                    (error "bad dotted form" str)
                    (read j (lambda (y j2)
                              (read j2 (lambda (z j3)
                                         (if (not (eq? z close-token))
                                             (error "bad dotted form" str)
                                             (k (append (reverse (cdr ls))
                                                        (cons (car ls) y))
                                                j3))))))))
               (else
                (lp j (cons x ls))))))))
        ((#\))
         (k close-token (+ i 1)))
        ((#\;)
         (let skip ((i (+ i 1)))
           (if (or (>= i end) (eqv? #\newline (string-ref str i)))
               (read (+ i 1) k)
               (skip (+ i 1)))))
        ((#\' #\`)
         (read (+ i 1)
           (lambda (sexp j)
             (let ((q (if (eqv? #\' (string-ref str i)) 'quote 'quasiquote)))
               (k (list q sexp) j)))))
        ((#\,)
         (let* ((at? (and (< (+ i 1) end) (eqv? #\@ (string-ref str (+ i 1)))))
                (u (if at? 'uquote-splicing 'unquote))
                (j (if at? (+ i 2) (+ i 1))))
           (read j (lambda (sexp j) (k (list u sexp) j)))))
        ((#\")
         (let scan ((from (+ i 1)) (i (+ i 1)) (res '()))
           (define (collect)
             (if (= from i) res (cons (substring str from i) res)))
           (if (>= i end)
               (error "unterminated string in embeded SRE" str)
               (case (string-ref str i)
                 ((#\") (k (string-cat-reverse (collect)) (+ i 1)))
                 ((#\\) (scan (+ i 1) (+ i 2) (collect)))
                 (else (scan from (+ i 1) res))))))
        ((#\#)
         (case (string-ref str (+ i 1))
           ((#\;)
            (read (+ i 2) (lambda (sexp j) (read j k))))
           ((#\\)
            (read (+ i 2)
              (lambda (sexp j)
                (k (case sexp
                     ((space) #\space)
                     ((newline) #\newline)
                     (else (let ((s (if (number? sexp)
                                        (number->string sexp)
                                        (symbol->string sexp))))
                             (string-ref s 0))))
                   j))))
           ((#\t #\f)
            (k (eqv? #\t (string-ref str (+ i 1))) (+ i 2)))
           (else
            (error "bad # syntax in simplified SRE" i))))
        (else
         (cond
          ((char-whitespace? (string-ref str i))
           (read (+ i 1) k))
          (else ;; symbol/number
           (let scan ((j (+ i 1)))
             (cond
              ((or (>= j end)
                   (let ((c (string-ref str j)))
                     (or (char-whitespace? c)
                         (memv c '(#\; #\( #\) #\" #\# #\\)))))
               (let ((str2 (substring str i j)))
                 (k (or (string->number str2) (string->symbol str2)) j)))
              (else (scan (+ j 1))))))))))))
  (read i (lambda (res j)
            (if (eq? res 'close-token)
                (error "unexpected ')' in SRE" str j)
                (proc res j)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Parsing PCRE Strings

(define ~save? 1)
(define ~case-insensitive? 2)
(define ~multi-line? 4)
(define ~single-line? 8)
(define ~ignore-space? 16)
(define ~utf8? 32)

(define (symbol-list->flags ls)
  (let lp ((ls ls) (res ~none))
    (if (not (pair? ls))
        res
        (lp (cdr ls)
            (flag-join
             res
             (case (car ls)
               ((i ci case-insensitive) ~case-insensitive?)
               ((m multi-line) ~multi-line?)
               ((s single-line) ~single-line?)
               ((x ignore-space) ~ignore-space?)
               ((u utf8) (if *allow-utf8-mode?* ~utf8? ~none))
               (else #f)))))))

(define (maybe-string->sre obj)
  (if (string? obj) (string->sre obj) obj))

(define (string->sre str . o)
  (if (not (string? str)) (error "string->sre: expected a string" str))
  (let ((end (string-length str))
        (flags (symbol-list->flags o)))

    (let lp ((i 0) (from 0) (flags flags) (res '()) (st '()))

      ;; handle case sensitivity at the literal char/string level
      (define (cased-char ch)
        (if (and (flag-set? flags ~case-insensitive?)
                 (char-alphabetic? ch))
            `(or ,ch ,(char-altcase ch))
            ch))
      (define (cased-string str)
        (if (flag-set? flags ~case-insensitive?)
            (sre-sequence (map cased-char (string->list str)))
            str))
      ;; accumulate the substring from..i as literal text
      (define (collect)
        (if (= i from) res (cons (cased-string (substring str from i)) res)))
      ;; like collect but breaks off the last single character when
      ;; collecting literal data, as the argument to ?/*/+ etc.
      (define (collect/single)
        (let* ((utf8? (flag-set? flags ~utf8?))
               (j (if (and utf8? (> i 1))
                      (utf8-backup-to-initial-char str (- i 1))
                      (- i 1))))
          (cond
           ((< j from)
            res)
           (else
            (let ((c (cased-char (if utf8?
                                     (utf8-string-ref str j (- i j))
                                     (string-ref str j)))))
              (cond
               ((= j from)
                (cons c res))
               (else
                (cons c
                      (cons (cased-string (substring str from j))
                            res)))))))))
      ;; collects for use as a result, reversing and grouping OR
      ;; terms, and some ugly tweaking of `function-like' groups and
      ;; conditionals
      (define (collect/terms)
        (let* ((ls (collect))
               (func
                (and (pair? ls)
                     (memq (last ls)
                           '(atomic if look-ahead neg-look-ahead
                                    look-behind neg-look-behind
                                    => submatch-named
                                    w/utf8 w/noutf8))))
               (prefix (if (and func (memq (car func) '(=> submatch-named)))
                           (list 'submatch-named (cadr (reverse ls)))
                           (and func (list (car func)))))
               (ls (if func
                       (if (memq (car func) '(=> submatch-named))
                           (reverse (cddr (reverse ls)))
                           (reverse (cdr (reverse ls))))
                       ls)))
          (let lp ((ls ls) (term '()) (res '()))
            (define (shift)
              (cons (sre-sequence term) res))
            (cond
             ((null? ls)
              (let* ((res (sre-alternate (shift)))
                     (res (if (flag-set? flags ~save?)
                              (list 'submatch res)
                              res)))
                (if prefix
                    (if (eq? 'if (car prefix))
                        (cond
                         ((not (pair? res))
                          'epsilon)
                         ((memq (car res)
                                '(look-ahead neg-look-ahead
                                             look-behind neg-look-behind))
                          res)
                         ((eq? 'seq (car res))
                          `(if ,(cadr res)
                               ,(sre-sequence (cddr res))))
                         (else
                          `(if ,(cadadr res)
                               ,(sre-sequence (cddadr res))
                               ,(sre-alternate (cddr res)))))
                        `(,@prefix ,res))
                    res)))
             ((eq? 'or (car ls)) (lp (cdr ls) '() (shift)))
             (else (lp (cdr ls) (cons (car ls) term) res))))))
      (define (save)
        (cons (cons flags (collect)) st))

      ;; main parsing
      (if (>= i end)
          (if (pair? st)
              (error "unterminated parenthesis in regexp" str)
              (collect/terms))
          (let ((c (string-ref str i)))
            (case c
              ((#\.)
               (lp (+ i 1) (+ i 1) flags
                   (cons (if (flag-set? flags ~single-line?) 'any 'nonl)
                         (collect))
                   st))
              ((#\?)
               (let ((res (collect/single)))
                 (if (null? res)
                     (error "? can't follow empty pattern" str res)
                     (let ((x (car res)))
                       (lp (+ i 1)
                           (+ i 1)
                           flags
                           (cons
                            (if (pair? x)
                                (case (car x)
                                  ((*)  `(*? ,@(cdr x)))
                                  ((+)  `(**? 1 #f ,@(cdr x)))
                                  ((?)  `(?? ,@(cdr x)))
                                  ((**) `(**? ,@(cdr x)))
                                  ((=)  `(**? ,(cadr x) ,@(cdr x)))
                                  ((>=)  `(**? ,(cadr x) #f ,@(cddr x)))
                                  (else `(? ,x)))
                                `(? ,x))
                            (cdr res))
                           st)))))
              ((#\+ #\*)
               (let* ((res (collect/single))
                      (x (if (pair? res) (car res) 'epsilon))
                      (op (string->symbol (string c))))
                 (cond
                  ((sre-repeater? x)
                   (error "duplicate repetition (e.g. **) in pattern" str res))
                  ((sre-empty? x)
                   (error "can't repeat empty pattern (e.g. ()*)" str res))
                  (else
                   (lp (+ i 1) (+ i 1) flags
                       (cons (list op x) (cdr res))
                       st)))))
              ((#\()
               (cond
                ((>= (+ i 1) end)
                 (error "unterminated parenthesis in regexp" str))
                ((not (memv (string-ref str (+ i 1)) '(#\? #\*))) ; normal case
                 (lp (+ i 1) (+ i 1) (flag-join flags ~save?) '() (save)))
                ((>= (+ i 2) end)
                 (error "unterminated parenthesis in regexp" str))
                ((eqv? (string-ref str (+ i 1)) #\*)
                 (if (eqv? #\' (string-ref str (+ i 2)))
                     (with-read-from-string str (+ i 3)
                       (lambda (sre j)
                         (if (or (>= j end) (not (eqv? #\) (string-ref str j))))
                             (error "unterminated (*'...) SRE escape" str)
                             (lp (+ j 1) (+ j 1) flags (cons sre (collect)) st))))
                     (error "bad regexp syntax: (*FOO) not supported" str)))
                (else                   ;; (?...) case
                 (case (string-ref str (+ i 2))
                   ((#\#)
                    (let ((j (string-scan-char str #\) (+ i 3))))
                      (lp (+ j i) (+ j 1) flags (collect) st)))
                   ((#\:)
                    (lp (+ i 3) (+ i 3) (flag-clear flags ~save?) '() (save)))
                   ((#\=)
                    (lp (+ i 3) (+ i 3) (flag-clear flags ~save?)
                        '(look-ahead) (save)))
                   ((#\!)
                    (lp (+ i 3) (+ i 3) (flag-clear flags ~save?)
                        '(neg-look-ahead) (save)))
                   ((#\<)
                    (cond
                     ((>= (+ i 3) end)
                      (error "unterminated parenthesis in regexp" str))
                     (else
                      (case (string-ref str (+ i 3))
                        ((#\=)
                         (lp (+ i 4) (+ i 4) (flag-clear flags ~save?)
                             '(look-behind) (save)))
                        ((#\!)
                         (lp (+ i 4) (+ i 4) (flag-clear flags ~save?)
                             '(neg-look-behind) (save)))
                        (else
                         (let ((j (and (char-alphabetic?
                                        (string-ref str (+ i 3)))
                                       (string-scan-char str #\> (+ i 4)))))
                           (if j
                               (lp (+ j 1) (+ j 1) (flag-clear flags ~save?)
                                   `(,(string->symbol (substring str (+ i 3) j))
                                     submatch-named)
                                   (save))
                               (error "invalid (?< sequence" str))))))))
                   ((#\>)
                    (lp (+ i 3) (+ i 3) (flag-clear flags ~save?)
                        '(atomic) (save)))
                   ;;((#\' #\P) ; named subpatterns
                   ;; )
                   ;;((#\R) ; recursion
                   ;; )
                   ((#\()
                    (cond
                     ((>= (+ i 3) end)
                      (error "unterminated parenthesis in regexp" str))
                     ((char-numeric? (string-ref str (+ i 3)))
                      (let* ((j (string-scan-char str #\) (+ i 3)))
                             (n (string->number (substring str (+ i 3) j))))
                        (if (not n)
                            (error "invalid conditional reference" str)
                            (lp (+ j 1) (+ j 1) (flag-clear flags ~save?)
                                `(,n if) (save)))))
                     ((char-alphabetic? (string-ref str (+ i 3)))
                      (let* ((j (string-scan-char str #\) (+ i 3)))
                             (s (string->symbol (substring str (+ i 3) j))))
                        (lp (+ j 1) (+ j 1) (flag-clear flags ~save?)
                            `(,s if) (save))))
                     (else
                      (lp (+ i 2) (+ i 2) (flag-clear flags ~save?)
                          '(if) (save)))))
                   ((#\{)
                    (error "unsupported Perl-style cluster" str))
                   (else
                    (let ((old-flags flags))
                      (let lp2 ((j (+ i 2)) (flags flags) (invert? #f))
                        (define (join x)
                          ((if invert? flag-clear flag-join) flags x))
                        (define (new-res res)
                          (let ((before (flag-set? old-flags ~utf8?))
                                (after (flag-set? flags ~utf8?)))
                            (if (eq? before after)
                                res
                                (cons (if after 'w/utf8 'w/noutf8) res))))
                        (cond
                         ((>= j end)
                          (error "incomplete cluster" str i))
                         (else
                          (case (string-ref str j)
                            ((#\i)
                             (lp2 (+ j 1) (join ~case-insensitive?) invert?))
                            ((#\m)
                             (lp2 (+ j 1) (join ~multi-line?) invert?))
                            ((#\x)
                             (lp2 (+ j 1) (join ~ignore-space?) invert?))
                            ((#\u)
                             (if *allow-utf8-mode?*
                                 (lp2 (+ j 1) (join ~utf8?) invert?)
                                 (lp2 (+ j 1) flags invert?)))
                            ((#\-)
                             (lp2 (+ j 1) flags (not invert?)))
                            ((#\))
                             (lp (+ j 1) (+ j 1) flags (new-res (collect))
                                 st))
                            ((#\:)
                             (lp (+ j 1) (+ j 1) flags (new-res '())
                                 (cons (cons old-flags (collect)) st)))
                            (else
                             (error "unknown regex cluster modifier" str)
                             )))))))))))
              ((#\))
               (if (null? st)
                   (error "too many )'s in regexp" str)
                   (lp (+ i 1)
                       (+ i 1)
                       (caar st)
                       (cons (collect/terms) (cdar st))
                       (cdr st))))
              ((#\[)
               (apply
                (lambda (sre j)
                  (lp (+ j 1) (+ j 1) flags (cons sre (collect)) st))
                (string-parse-cset str (+ i 1) flags)))
              ((#\{)
               (cond
                ((or (>= (+ i 1) end)
                     (not (or (char-numeric? (string-ref str (+ i 1)))
                              (eqv? #\, (string-ref str (+ i 1))))))
                 (lp (+ i 1) from flags res st))
                (else
                 (let ((res (collect/single)))
                   (cond
                    ((null? res)
                     (error "{ can't follow empty pattern"))
                    (else
                     (let* ((x (car res))
                            (tail (cdr res))
                            (j (string-scan-char str #\} (+ i 1)))
                            (s2 (string-split-char (substring str (+ i 1) j)
                                                   #\,))
                            (n (string->number (car s2)))
                            (m (and (pair? (cdr s2))
                                    (string->number (cadr s2)))))
                       (cond
                        ((or (not n)
                             (and (pair? (cdr s2))
                                  (not (equal? "" (cadr s2)))
                                  (not m)))
                         (error "invalid {n} repetition syntax" s2))
                        ((null? (cdr s2))
                         (lp (+ j 1) (+ j 1) flags `((= ,n ,x) ,@tail) st))
                        (m
                         (lp (+ j 1) (+ j 1) flags `((** ,n ,m ,x) ,@tail) st))
                        (else
                         (lp (+ j 1) (+ j 1) flags `((>= ,n ,x) ,@tail) st)
                         )))))))))
              ((#\\)
               (cond
                ((>= (+ i 1) end)
                 (error "incomplete escape sequence" str))
                (else
                 (let ((c (string-ref str (+ i 1))))
                   (case c
                     ((#\d)
                      (lp (+ i 2) (+ i 2) flags `(numeric ,@(collect)) st))
                     ((#\D)
                      (lp (+ i 2) (+ i 2) flags `((~ numeric) ,@(collect)) st))
                     ((#\s)
                      (lp (+ i 2) (+ i 2) flags `(space ,@(collect)) st))
                     ((#\S)
                      (lp (+ i 2) (+ i 2) flags `((~ space) ,@(collect)) st))
                     ((#\w)
                      (lp (+ i 2) (+ i 2) flags
                          `((or alphanumeric ("_")) ,@(collect)) st))
                     ((#\W)
                      (lp (+ i 2) (+ i 2) flags
                          `((~ (or alphanumeric ("_"))) ,@(collect)) st))
                     ((#\b)
                      (lp (+ i 2) (+ i 2) flags
                          `((or bow eow) ,@(collect)) st))
                     ((#\B)
                      (lp (+ i 2) (+ i 2) flags `(nwb ,@(collect)) st))
                     ((#\A)
                      (lp (+ i 2) (+ i 2) flags `(bos ,@(collect)) st))
                     ((#\Z)
                      (lp (+ i 2) (+ i 2) flags
                          `((? #\newline) eos ,@(collect)) st))
                     ((#\z)
                      (lp (+ i 2) (+ i 2) flags `(eos ,@(collect)) st))
                     ((#\R)
                      (lp (+ i 2) (+ i 2) flags `(newline ,@(collect)) st))
                     ((#\K)
                      (lp (+ i 2) (+ i 2) flags `(reset ,@(collect)) st))
                     ;; these two are from Emacs and TRE, but not in PCRE
                     ((#\<)
                      (lp (+ i 2) (+ i 2) flags `(bow ,@(collect)) st))
                     ((#\>)
                      (lp (+ i 2) (+ i 2) flags `(eow ,@(collect)) st))
                     ((#\x)
                      (apply
                       (lambda (ch j)
                         (lp (+ j 1) (+ j 1) flags `(,ch ,@(collect)) st))
                       (string-parse-hex-escape str (+ i 2) end)))
                     ((#\k)
                      (let ((c (string-ref str (+ i 2))))
                        (if (not (memv c '(#\< #\{ #\')))
                            (error "bad \\k usage, expected \\k<...>" str)
                            (let* ((terminal (char-mirror c))
                                   (j (string-scan-char str terminal (+ i 2)))
                                   (s (and j (substring str (+ i 3) j)))
                                   (backref
                                    (if (flag-set? flags ~case-insensitive?)
                                        'backref-ci
                                        'backref)))
                              (if (not j)
                                  (error "unterminated named backref" str)
                                  (lp (+ j 1) (+ j 1) flags
                                      `((,backref ,(string->symbol s))
                                        ,@(collect))
                                      st))))))
                     ((#\Q)  ;; \Q..\E escapes
                      (let ((res (collect)))
                        (let lp2 ((j (+ i 2)))
                          (cond
                           ((>= j end)
                            (lp j (+ i 2) flags res st))
                           ((eqv? #\\ (string-ref str j))
                            (cond
                             ((>= (+ j 1) end)
                              (lp (+ j 1) (+ i 2) flags res st))
                             ((eqv? #\E (string-ref str (+ j 1)))
                              (lp (+ j 2) (+ j 2) flags
                                  (cons (substring str (+ i 2) j) res) st))
                             (else
                              (lp2 (+ j 2)))))
                           (else
                            (lp2 (+ j 1)))))))
                     ((#\')
                      (with-read-from-string str (+ i 2)
                       (lambda (sre j)
                         (lp j j flags (cons sre (collect)) st))))
                     ;;((#\p)  ; XXXX unicode properties
                     ;; )
                     ;;((#\P)
                     ;; )
                     (else
                      (cond
                       ((char-numeric? c)
                        (let* ((j (or (string-scan-pred
                                       str
                                       (lambda (c) (not (char-numeric? c)))
                                       (+ i 2))
                                      end))
                               (backref
                                (if (flag-set? flags ~case-insensitive?)
                                    'backref-ci
                                    'backref))
                               (res `((,backref ,(string->number
                                                  (substring str (+ i 1) j)))
                                      ,@(collect))))
                          (lp j j flags res st)))
                       ((char-alphabetic? c)
                        (let ((cell (assv c posix-escape-sequences)))
                          (if cell
                              (lp (+ i 2) (+ i 2) flags
                                  (cons (cdr cell) (collect)) st)
                              (error "unknown escape sequence" str c))))
                       (else
                        (lp (+ i 2) (+ i 1) flags (collect) st)))))))))
              ((#\|)
               (lp (+ i 1) (+ i 1) flags (cons 'or (collect)) st))
              ((#\^)
               (let ((sym (if (flag-set? flags ~multi-line?) 'bol 'bos)))
                 (lp (+ i 1) (+ i 1) flags (cons sym (collect)) st)))
              ((#\$)
               (let ((sym (if (flag-set? flags ~multi-line?) 'eol 'eos)))
                 (lp (+ i 1) (+ i 1) flags (cons sym (collect)) st)))
              ((#\space)
               (if (flag-set? flags ~ignore-space?)
                   (lp (+ i 1) (+ i 1) flags (collect) st)
                   (lp (+ i 1) from flags res st)))
              ((#\#)
               (if (flag-set? flags ~ignore-space?)
                   (let ((j (or (string-scan-char str #\newline (+ i 1))
                                (- end 1))))
                     (lp (+ j 1) (+ j 1) flags (collect) st))
                   (lp (+ i 1) from flags res st)))
              (else
               (lp (+ i 1) from flags res st))))))))

(define posix-escape-sequences
  `((#\n . #\newline)
    (#\r . ,(integer->char (+ (char->integer #\newline) 3)))
    (#\t . ,(integer->char (- (char->integer #\newline) 1)))
    (#\a . ,(integer->char (- (char->integer #\newline) 3)))
    (#\e . ,(integer->char (+ (char->integer #\newline) #x11)))
    (#\f . ,(integer->char (+ (char->integer #\newline) 2)))
    ))

(define (char-altcase c)
  (if (char-upper-case? c) (char-downcase c) (char-upcase c)))

(define (char-mirror c)
  (case c ((#\<) #\>) ((#\{) #\}) ((#\() #\)) ((#\[) #\]) (else c)))

(define (string-parse-hex-escape str i end)
  (cond
   ((>= i end)
    (error "incomplete hex escape" str i))
   ((eqv? #\{ (string-ref str i))
    (let ((j (string-scan-char-escape str #\} (+ i 1))))
      (if (not j)
          (error "incomplete hex brace escape" str i)
          (let* ((s (substring str (+ i 1) j))
                 (n (string->number s 16)))
            (if n
                (list (integer->char n) j)
                (error "bad hex brace escape" s))))))
   ((>= (+ i 1) end)
    (error "incomplete hex escape" str i))
   (else
    (let* ((s (substring str i (+ i 2)))
           (n (string->number s 16)))
      (if n
          (list (integer->char n) (+ i 2))
          (error "bad hex escape" s))))))

(define (string-parse-cset str start flags)
  (let* ((end (string-length str))
         (invert? (and (< start end) (eqv? #\^ (string-ref str start))))
         (utf8? (flag-set? flags ~utf8?)))
    (define (go i prev-char cset)
      (if (>= i end)
          (error "incomplete char set" str i end)
          (let ((c (string-ref str i)))
            (case c
              ((#\])
               (if (cset-empty? cset)
                   (go (+ i 1) #\] (cset-adjoin cset #\]))
                   (let ((ci? (flag-set? flags ~case-insensitive?)))
                     (list
                      (let ((res (if ci? (cset-case-insensitive cset) cset)))
                        (cset->sre (if invert? (cset-complement res) res)))
                      i))))
              ((#\-)
               (cond
                ((or (= i start)
                     (and (= i (+ start 1)) (eqv? #\^ (string-ref str start)))
                     (eqv? #\] (string-ref str (+ i 1))))
                 (go (+ i 1) c (cset-adjoin cset c)))
                ((not prev-char)
                 (error "bad char-set"))
                (else
                 (let ((char (string-ref str (+ i 1))))
                   (apply
                    (lambda (c j)
                      (if (char<? c prev-char)
                          (error "inverted range in char-set" prev-char c)
                          (go j #f (cset-union cset (range->cset prev-char c)))))
                    (cond
                     ((and (eqv? #\\ char) (assv char posix-escape-sequences))
                      => (lambda (x) (list (cdr x) (+ i 3))))
                     ((and (eqv? #\\ char)
                           (eqv? (string-ref str (+ i 2)) #\x))
                      (string-parse-hex-escape str (+ i 3) end))
                     ((and utf8? (<= #x80 (char->integer char) #xFF))
                      (let ((len (utf8-start-char->length char)))
                        (list (utf8-string-ref str (+ i 1) len) (+ i 1 len))))
                     (else
                      (list char (+ i 2)))))))))
              ((#\[)
               (let* ((inv? (eqv? #\^ (string-ref str (+ i 1))))
                      (i2 (if inv? (+ i 2) (+ i 1))))
                 (case (string-ref str i2)
                   ((#\:)
                    (let ((j (string-scan-char str #\: (+ i2 1))))
                      (if (or (not j) (not (eqv? #\] (string-ref str (+ j 1)))))
                          (error "incomplete character class" str)
                          (let* ((class (sre->cset
                                         (string->symbol
                                          (substring str (+ i2 1) j))))
                                 (class (if inv? (cset-complement class) class)))
                            (go (+ j 2) #f (cset-union cset class))))))
                   ((#\= #\.)
                    (error "collating sequences not supported" str))
                   (else
                    (go (+ i 1) #\[ (cset-adjoin cset #\[))))))
              ((#\\)
               (let ((c (string-ref str (+ i 1))))
                 (case c
                   ((#\d #\D #\s #\S #\w #\W)
                    (go (+ i 2) #f
                        (cset-union cset
                                    (sre->cset (string->sre (string #\\ c))))))
                   ((#\x)
                    (apply
                     (lambda (ch j)
                       (go j ch (cset-adjoin cset ch)))
                     (string-parse-hex-escape str (+ i 2) end)))
                   (else
                    (let ((c (cond ((assv c posix-escape-sequences) => cdr)
                                   (else c))))
                      (go (+ i 2) c (cset-adjoin cset c)))))))
              (else
               (if (and utf8? (<= #x80 (char->integer c) #xFF))
                   (let ((len (utf8-start-char->length c)))
                     (go (+ i len)
                         (utf8-string-ref str i len)
                         (cset-adjoin cset (utf8-string-ref str i len))))
                   (go (+ i 1) c (cset-adjoin cset c))))))))
    (if invert?
        (go (+ start 1)
            #f
            (if (flag-set? flags ~multi-line?)
                (char->cset #\newline)
                (make-cset)))
        (go start #f (make-cset)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; UTF-8 Utilities

;; Here are some hairy optimizations that need to be documented
;; better.  Thanks to these, we never do any utf8 processing once the
;; regexp is compiled.

;; two chars: ab..ef
;;            a[b..xFF]|[b-d][x80..xFF]|e[x80..xFF]

;; three chars: abc..ghi
;;              ab[c..xFF]|a[d..xFF][x80..xFF]|
;;              [b..f][x80..xFF][x80..xFF]|
;;              g[x80..g][x80..xFF]|gh[x80..i]

;; four chars: abcd..ghij
;;             abc[d..xFF]|ab[d..xFF][x80..xFF]|a[c..xFF][x80..xFF][x80..xFF]|
;;             [b..f][x80..xFF][x80..xFF][x80..xFF]|
;;             g[x80..g][x80..xFF][x80..xFF]|gh[x80..h][x80..xFF]|ghi[x80..j]

(define (high-char? c) (<= #x80 (char->integer c)))

;; number of total bytes in a utf8 char given the 1st byte

(define utf8-start-char->length
  (let ((table '#(
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 0x
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 1x
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 2x
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 3x
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 4x
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 5x
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 6x
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 7x
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 8x
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 9x
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; ax
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; bx
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ; cx
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ; dx
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 ; ex
4 4 4 4 4 4 4 4 5 5 5 5 6 6 0 0 ; fx
)))
    (lambda (c) (vector-ref table (char->integer c)))))

(define (utf8-string-ref str i len)
  (define (byte n) (char->integer (string-ref str n)))
  (case len
    ((1) ; shouldn't happen in this module
     (string-ref str i))
    ((2)
     (integer->char
      (+ (bit-shl (bit-and (byte i) #b00011111) 6)
         (bit-and (byte (+ i 1)) #b00111111))))
    ((3)
     (integer->char
      (+ (bit-shl (bit-and (byte i) #b00001111) 12)
         (bit-shl (bit-and (byte (+ i 1)) #b00111111) 6)
         (bit-and (byte (+ i 2)) #b00111111))))
    ((4)
     (integer->char
      (+ (bit-shl (bit-and (byte i) #b00000111) 18)
         (bit-shl (bit-and (byte (+ i 1)) #b00111111) 12)
         (bit-shl (bit-and (byte (+ i 2)) #b00111111) 6)
         (bit-and (byte (+ i 3)) #b00111111))))
    (else
     (error "invalid utf8 length" str len i))))

(define (utf8-backup-to-initial-char str i)
  (let lp ((i i))
    (if (= i 0)
        0
        (let ((c (char->integer (string-ref str i))))
          (if (or (< c #x80) (>= c #xC0))
              i
              (lp (- i 1)))))))

(define (utf8-lowest-digit-of-length len)
  (case len
    ((1) 0) ((2) #xC0) ((3) #xE0) ((4) #xF0)
    (else (error "invalid utf8 length" len))))

(define (utf8-highest-digit-of-length len)
  (case len
    ((1) #x7F) ((2) #xDF) ((3) #xEF) ((4) #xF7)
    (else (error "invalid utf8 length" len))))

(define (char->utf8-list c)
  (let ((i (char->integer c)))
    (cond
     ((<= i #x7F) (list i))
     ((<= i #x7FF)
      (list (bit-ior #b11000000 (bit-shr i 6))
            (bit-ior #b10000000 (bit-and i #b111111))))
     ((<= i #xFFFF)
      (list (bit-ior #b11100000 (bit-shr i 12))
            (bit-ior #b10000000 (bit-and (bit-shr i 6) #b111111))
            (bit-ior #b10000000 (bit-and i #b111111))))
     ((<= i #x1FFFFF)
      (list (bit-ior #b11110000 (bit-shr i 18))
            (bit-ior #b10000000 (bit-and (bit-shr i 12) #b111111))
            (bit-ior #b10000000 (bit-and (bit-shr i 6) #b111111))
            (bit-ior #b10000000 (bit-and i #b111111))))
     (else (error "unicode codepoint out of range:" i)))))

(define (unicode-range->utf8-pattern lo hi)
  (let ((lo-ls (char->utf8-list lo))
        (hi-ls (char->utf8-list hi)))
    (if (not (= (length lo-ls) (length hi-ls)))
        (sre-alternate (list (unicode-range-climb-digits lo-ls hi-ls)
                             (unicode-range-up-to hi-ls)))
        (let lp ((lo-ls lo-ls) (hi-ls hi-ls))
          (cond
           ((null? lo-ls)
            '())
           ((= (car lo-ls) (car hi-ls))
            (sre-sequence
             (list (integer->char (car lo-ls))
                   (lp (cdr lo-ls) (cdr hi-ls)))))
           ((= (+ (car lo-ls) 1) (car hi-ls))
            (sre-alternate (list (unicode-range-up-from lo-ls)
                                 (unicode-range-up-to hi-ls))))
           (else
            (sre-alternate (list (unicode-range-up-from lo-ls)
                                 (unicode-range-middle lo-ls hi-ls)
                                 (unicode-range-up-to hi-ls)))))))))

(define (unicode-range-helper one ls prefix res)
  (if (null? ls)
      res
      (unicode-range-helper
       one
       (cdr ls)
       (cons (car ls) prefix)
       (cons (sre-sequence
              `(,@(map integer->char prefix)
                ,(one (car ls))
                ,@(map (lambda (_)
                         `(/ ,(integer->char #x80)
                             ,(integer->char #xFF)))
                       (cdr ls))))
             res))))

(define (unicode-range-up-from lo-ls)
  (sre-sequence
   (list (integer->char (car lo-ls))
         (sre-alternate
          (unicode-range-helper
           (lambda (c)
             `(/ ,(integer->char (+ (car lo-ls) 1)) ,(integer->char #xFF)))
           (cdr (reverse (cdr lo-ls)))
           '()
           (list
            (sre-sequence
             (append
              (map integer->char (reverse (cdr (reverse (cdr lo-ls)))))
              `((/ ,(integer->char (last lo-ls))
                   ,(integer->char #xFF)))))))))))

(define (unicode-range-up-to hi-ls)
  (sre-sequence
   (list (integer->char (car hi-ls))
         (sre-alternate
          (unicode-range-helper
           (lambda (c)
             `(/ ,(integer->char #x80) ,(integer->char (- (car hi-ls) 1))))
           (cdr (reverse (cdr hi-ls)))
           '()
           (list
            (sre-sequence
             (append
              (map integer->char (reverse (cdr (reverse (cdr hi-ls)))))
              `((/ ,(integer->char #x80)
                   ,(integer->char (last hi-ls))))))))))))

(define (unicode-range-climb-digits lo-ls hi-ls)
  (let ((lo-len (length lo-ls)))
    (sre-alternate
     (append
      (list
       (sre-sequence
        (cons `(/ ,(integer->char (car lo-ls))
                  ,(integer->char (if (<= (car lo-ls) #x7F) #x7F #xFF)))
              (map (lambda (_)
                     `(/ ,(integer->char #x80) ,(integer->char #xFF)))
                   (cdr lo-ls)))))
      (map
       (lambda (i)
         (sre-sequence
          (cons
           `(/ ,(integer->char (utf8-lowest-digit-of-length (+ i lo-len 1)))
               ,(integer->char (utf8-highest-digit-of-length (+ i lo-len 1))))
           (map (lambda (_)
                  `(/ ,(integer->char #x80) ,(integer->char #xFF)))
                (zero-to (+ i lo-len))))))
       (zero-to (- (length hi-ls) (+ lo-len 1))))
      (list
       (sre-sequence
        (cons `(/ ,(integer->char
                    (utf8-lowest-digit-of-length
                     (utf8-start-char->length
                      (integer->char (- (car hi-ls) 1)))))
                  ,(integer->char (- (car hi-ls) 1)))
              (map (lambda (_)
                     `(/ ,(integer->char #x80) ,(integer->char #xFF)))
                   (cdr hi-ls)))))))))

(define (unicode-range-middle lo-ls hi-ls)
  (let ((lo (integer->char (+ (car lo-ls) 1)))
        (hi (integer->char (- (car hi-ls) 1))))
    (sre-sequence
     (cons (if (char=? lo hi) lo `(/ ,lo ,hi))
           (map (lambda (_) `(/ ,(integer->char #x80) ,(integer->char #xFF)))
                (cdr lo-ls))))))

;; Maybe this should just modify the input?
(define (cset->utf8-pattern cset)
  (let lp ((ls (cset->plist cset)) (alts '()) (lo-cset '()))
    (if (null? ls)
        (sre-alternate (append (reverse alts)
                               (if (null? lo-cset)
                                   '()
                                   (list (cons '/ (reverse lo-cset))))))
        (if (or (high-char? (car ls))  (high-char? (cadr ls)))
            (lp (cddr ls)
                (cons (unicode-range->utf8-pattern (car ls) (cadr ls)) alts)
                lo-cset)
            (lp (cddr ls) alts (cons (cadr ls) (cons (car ls) lo-cset)))))))

(define (sre-adjust-utf8 sre flags)
  (let adjust ((sre sre)
               (utf8? (flag-set? flags ~utf8?))
               (ci? (flag-set? flags ~case-insensitive?)))
    (define (rec sre) (adjust sre utf8? ci?))
    (cond
     ((pair? sre)
      (case (car sre)
        ((w/utf8) (adjust (sre-sequence (cdr sre)) #t ci?))
        ((w/noutf8) (adjust (sre-sequence (cdr sre)) #f ci?))
        ((w/case)
         (cons (car sre) (map (lambda (s) (adjust s utf8? #f)) (cdr sre))))
        ((w/nocase)
         (cons (car sre) (map (lambda (s) (adjust s utf8? #t)) (cdr sre))))
        ((/ ~ & -)
         (if (not utf8?)
             sre
             (let ((cset (sre->cset sre ci?)))
               (if (any high-char? (cset->plist cset))
                   (if ci?
                       (list 'w/case (cset->utf8-pattern cset))
                       (cset->utf8-pattern cset))
                   sre))))
        ((*)
         (case (sre-sequence (cdr sre))
           ;; special case optimization: .* w/utf8 == .* w/noutf8
           ((any) '(* any))
           ((nonl) '(* nonl))
           (else (cons '* (map rec (cdr sre))))))
        (else
         (cons (car sre) (map rec (cdr sre))))))
     (else
      (case sre
        ((any) 'utf8-any)
        ((nonl) 'utf8-nonl)
        (else
         (if (and utf8? (char? sre) (high-char? sre))
             (sre-sequence (map integer->char (char->utf8-list sre)))
             sre)))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Compilation

(define (irregex x . o)
  (cond
   ((irregex? x) x)
   ((string? x) (apply string->irregex x o))
   (else (apply sre->irregex x o))))

(define (string->irregex str . o)
  (apply sre->irregex (apply string->sre str o) o))

(define (sre->irregex sre . o)
  (let* ((pat-flags (symbol-list->flags o))
         (sre (if *allow-utf8-mode?*
                  (sre-adjust-utf8 sre pat-flags)
                  sre))
         (searcher? (sre-searcher? sre))
         (sre-dfa (if searcher? (sre-remove-initial-bos sre) sre))
         (dfa-limit (cond ((memq 'small o) 1) ((memq 'fast o) 50) (else 10)))
         ;; TODO: Maybe make these two promises; if we only want to search,
         ;; it's wasteful to compile the matcher, and vice versa
         ;; Maybe provide a flag to compile eagerly, to help benchmarking etc.
         (dfa/search
          (cond ((memq 'backtrack o) #f)
                (searcher? #t)
                ((sre->nfa `(seq (* any) ,sre-dfa) pat-flags)
                 => (lambda (nfa)
                      (nfa->dfa nfa (* dfa-limit (nfa-num-states nfa)))))
                (else #f)))
         (dfa (cond ((and dfa/search (sre->nfa sre-dfa pat-flags))
                     => (lambda (nfa)
                          (nfa->dfa nfa (* dfa-limit (nfa-num-states nfa)))))
                    (else #f)))
         (submatches (sre-count-submatches sre-dfa))
         (names (sre-names sre-dfa 1 '()))
         (lens (sre-length-ranges sre-dfa names))
         (flags (flag-join
                 (flag-join ~none (and searcher? ~searcher?))
                 (and (sre-consumer? sre) ~consumer?))))
    (cond
     (dfa
      (make-irregex dfa dfa/search #f flags submatches lens names))
     (else
      (let ((f (sre->procedure sre pat-flags names)))
        (make-irregex #f #f f flags submatches lens names))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; SRE Analysis

;; returns #t if the sre can ever be empty
(define (sre-empty? sre)
  (if (pair? sre)
      (case (car sre)
        ((* ? look-ahead look-behind neg-look-ahead neg-look-behind) #t)
        ((**) (or (not (number? (cadr sre))) (zero? (cadr sre))))
        ((or) (any sre-empty? (cdr sre)))
        ((: seq $ submatch => submatch-named + atomic)
         (every sre-empty? (cdr sre)))
        (else #f))
      (memq sre '(epsilon bos eos bol eol bow eow commit))))

(define (sre-any? sre)
  (or (eq? sre 'any)
      (and (pair? sre)
           (case (car sre)
             ((seq : $ submatch => submatch-named)
              (and (pair? (cdr sre)) (null? (cddr sre)) (sre-any? (cadr sre))))
             ((or) (every sre-any? (cdr sre)))
             (else #f)))))

(define (sre-repeater? sre)
  (and (pair? sre)
       (or (memq (car sre) '(* +))
           (and (memq (car sre) '($ submatch => submatch-named seq :))
                (pair? (cdr sre))
                (null? (cddr sre))
                (sre-repeater? (cadr sre))))))

(define (sre-searcher? sre)
  (if (pair? sre)
      (case (car sre)
        ((* +) (sre-any? (sre-sequence (cdr sre))))
        ((seq : $ submatch => submatch-named)
         (and (pair? (cdr sre)) (sre-searcher? (cadr sre))))
        ((or) (every sre-searcher? (cdr sre)))
        (else #f))
      (eq? 'bos sre)))

(define (sre-consumer? sre)
  (if (pair? sre)
      (case (car sre)
        ((* +) (sre-any? (sre-sequence (cdr sre))))
        ((seq : $ submatch => submatch-named)
         (and (pair? (cdr sre)) (sre-consumer? (last sre))))
        ((or) (every sre-consumer? (cdr sre)))
        (else #f))
      (eq? 'eos sre)))

(define (sre-has-submatches? sre)
  (and (pair? sre)
       (or (memq (car sre) '($ submatch => submatch-named))
           (if (eq? 'posix-string (car sre))
               (sre-has-submatches? (string->sre (cadr sre)))
               (any sre-has-submatches? (cdr sre))))))

(define (sre-count-submatches sre)
  (let count ((sre sre) (sum 0))
    (if (pair? sre)
        (fold count
              (+ sum (case (car sre)
                       (($ submatch => submatch-named) 1)
                       ((dsm) (+ (cadr sre) (caddr sre)))
                       ((posix-string)
                        (sre-count-submatches (string->sre (cadr sre))))
                       (else 0)))
              (cdr sre))
        sum)))

(define (sre-length-ranges sre . o)
  (let ((names (if (pair? o) (car o) (sre-names sre 1 '())))
        (sublens (make-vector (+ 1 (sre-count-submatches sre)) #f)))
    (vector-set!
     sublens
     0
     (let lp ((sre sre) (n 1) (lo 0) (hi 0) (return cons))
       (define (grow i) (return (+ lo i) (and hi (+ hi i))))
       (cond
        ((pair? sre)
         (if (string? (car sre))
             (grow 1)
             (case (car sre)
               ((/ ~ & -)
                (grow 1))
               ((posix-string)
                (lp (string->sre (cadr sre)) n lo hi return))
               ((seq : w/case w/nocase atomic)
                (let lp2 ((ls (cdr sre)) (n n) (lo2 0) (hi2 0))
                  (if (null? ls)
                      (return (+ lo lo2) (and hi hi2 (+ hi hi2)))
                      (lp (car ls) n 0 0
                          (lambda (lo3 hi3)
                            (lp2 (cdr ls)
                                 (+ n (sre-count-submatches (car ls)))
                                 (+ lo2 lo3)
                                 (and hi2 hi3 (+ hi2 hi3))))))))
               ((or)
                (let lp2 ((ls (cdr sre)) (n n) (lo2 #f) (hi2 0))
                  (if (null? ls)
                      (return (+ lo (or lo2 1)) (and hi hi2 (+ hi hi2)))
                      (lp (car ls) n 0 0
                          (lambda (lo3 hi3)
                            (lp2 (cdr ls)
                                 (+ n (sre-count-submatches (car ls)))
                                 (if lo2 (min lo2 lo3) lo3)
                                 (and hi2 hi3 (max hi2 hi3))))))))
               ((if)
                (cond
                 ((or (null? (cdr sre)) (null? (cddr sre)))
                  (return lo hi))
                 (else
                  (let ((n1 (sre-count-submatches (car sre)))
                        (n2 (sre-count-submatches (cadr sre))))
                    (lp (if (or (number? (cadr sre)) (symbol? (cadr sre)))
                            'epsilon
                            (cadr sre))
                        n lo hi
                        (lambda (lo2 hi2)
                          (lp (caddr sre) (+ n n1) 0 0
                              (lambda (lo3 hi3)
                                (lp (if (pair? (cdddr sre))
                                        (cadddr sre)
                                        'epsilon)
                                    (+ n n1 n2) 0 0
                                    (lambda (lo4 hi4)
                                      (return (+ lo2 (min lo3 lo4))
                                              (and hi2 hi3 hi4
                                                   (+ hi2 (max hi3 hi4))
                                                   ))))))))))))
               ((dsm)
                (lp (sre-sequence (cdddr sre)) (+ n (cadr sre)) lo hi return))
               (($ submatch => submatch-named)
                (lp (sre-sequence
                     (if (eq? 'submatch (car sre)) (cdr sre) (cddr sre)))
                    (+ n 1) lo hi
                    (lambda (lo2 hi2)
                      (vector-set! sublens n (cons lo2 hi2))
                      (return lo2 hi2))))
               ((backref backref-ci)
                (let ((n (cond
                          ((number? (cadr sre)) (cadr sre))
                          ((assq (cadr sre) names) => cdr)
                          (else (error "unknown backreference" (cadr sre))))))
                  (cond
                   ((or (not (integer? n))
                        (not (< 0 n (vector-length sublens))))
                    (error "sre-length: invalid backreference" sre))
                   ((not (vector-ref sublens n))
                    (error "sre-length: invalid forward backreference" sre))
                   (else
                    (let ((lo2 (car (vector-ref sublens n)))
                          (hi2 (cdr (vector-ref sublens n))))
                      (return (+ lo lo2) (and hi hi2 (+ hi hi2))))))))
               ((* *?)
                (lp (sre-sequence (cdr sre)) n lo hi (lambda (lo hi) #f))
                (return lo #f))
               ((** **?)
                (cond
                 ((or (and (number? (cadr sre))
                           (number? (caddr sre))
                           (> (cadr sre) (caddr sre)))
                      (and (not (cadr sre)) (caddr sre)))
                  (return lo hi))
                 (else
                  (if (caddr sre)
                      (lp (sre-sequence (cdddr sre)) n 0 0
                          (lambda (lo2 hi2)
                            (return (+ lo (* (cadr sre) lo2))
                                    (and hi hi2 (+ hi (* (caddr sre) hi2))))))
                      (lp (sre-sequence (cdddr sre)) n 0 0
                          (lambda (lo2 hi2)
                            (return (+ lo (* (cadr sre) lo2)) #f)))))))
               ((+)
                (lp (sre-sequence (cdr sre)) n lo hi
                    (lambda (lo2 hi2)
                      (return (+ lo lo2) #f))))
               ((? ??)
                (lp (sre-sequence (cdr sre)) n lo hi
                    (lambda (lo2 hi2)
                      (return lo (and hi hi2 (+ hi hi2))))))
               ((= =? >= >=?)
                (lp `(** ,(cadr sre)
                         ,(if (memq (car sre) '(>= >=?)) #f (cadr sre))
                         ,@(cddr sre))
                    n lo hi return))
               ((look-ahead neg-look-ahead look-behind neg-look-behind)
                (return lo hi))
               (else
                (cond
                 ((assq (car sre) sre-named-definitions)
                  => (lambda (cell)
                       (lp (apply (cdr cell) (cdr sre)) n lo hi return)))
                 (else
                  (error "sre-length-ranges: unknown sre operator" sre)))))))
        ((char? sre)
         (grow 1))
        ((string? sre)
         (grow (string-length sre)))
        ((memq sre '(any nonl))
         (grow 1))
        ((memq sre '(epsilon bos eos bol eol bow eow nwb commit))
         (return lo hi))
        (else
         (let ((cell (assq sre sre-named-definitions)))
           (if cell
               (lp (if (procedure? (cdr cell)) ((cdr cell)) (cdr cell))
                   n lo hi return)
               (error "sre-length-ranges: unknown sre" sre)))))))
    sublens))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; SRE Manipulation

;; build a (seq ls ...) sre from a list
(define (sre-sequence ls)
  (cond
   ((null? ls) 'epsilon)
   ((null? (cdr ls)) (car ls))
   (else (cons 'seq ls))))

;; build a (or ls ...) sre from a list
(define (sre-alternate ls)
  (cond
   ((null? ls) '(or))
   ((null? (cdr ls)) (car ls))
   (else (cons 'or ls))))

;; returns an equivalent SRE without any match information
(define (sre-strip-submatches sre)
  (if (not (pair? sre))
      sre
      (case (car sre)
        (($ submatch) (sre-strip-submatches (sre-sequence (cdr sre))))
        ((=> submatch-named) (sre-strip-submatches (sre-sequence (cddr sre))))
        ((dsm) (sre-strip-submatches (sre-sequence (cdddr sre))))
        (else (map sre-strip-submatches sre)))))

;; given a char-set list of chars and strings, flattens them into
;; chars only
(define (sre-flatten-ranges ls)
  (let lp ((ls ls) (res '()))
    (cond
     ((null? ls)
      (reverse res))
     ((string? (car ls))
      (lp (append (string->list (car ls)) (cdr ls)) res))
     (else
      (lp (cdr ls) (cons (car ls) res))))))

(define (sre-names sre n names)
  (if (not (pair? sre))
      names
      (case (car sre)
        (($ submatch)
         (sre-names (sre-sequence (cdr sre)) (+ n 1) names))
        ((=> submatch-named)
         (sre-names (sre-sequence (cddr sre))
                    (+ n 1)
                    (cons (cons (cadr sre) n) names)))
        ((dsm)
         (sre-names (sre-sequence (cdddr sre)) (+ n (cadr sre)) names))
        ((seq : or * + ? *? ?? w/case w/nocase atomic
          look-ahead look-behind neg-look-ahead neg-look-behind)
         (sre-sequence-names (cdr sre) n names))
        ((= >=)
         (sre-sequence-names (cddr sre) n names))
        ((** **?)
         (sre-sequence-names (cdddr sre) n names))
        (else
         names))))

(define (sre-sequence-names ls n names)
  (if (null? ls)
      names
      (sre-sequence-names (cdr ls)
                          (+ n (sre-count-submatches (car ls)))
                          (sre-names (car ls) n names))))

(define (sre-remove-initial-bos sre)
  (cond
   ((pair? sre)
    (case (car sre)
      ((seq : $ submatch => submatch-named * +)
       (cond
        ((not (pair? (cdr sre)))
         sre)
        ((eq? 'bos (cadr sre))
         (cons (car sre) (cddr sre)))
        (else
         (cons (car sre)
               (cons (sre-remove-initial-bos (cadr sre)) (cddr sre))))))
      ((or)
       (sre-alternate (map sre-remove-initial-bos (cdr sre))))
      (else
       sre)))
   (else
    sre)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Basic Matching

(define irregex-basic-string-chunker
  (make-irregex-chunker (lambda (x) #f)
                        car
                        cadr
                        caddr
                        (lambda (src1 i src2 j)
                          (substring (car src1) i j))))

(define (irregex-search x str . o)
  (if (not (string? str)) (error "irregex-search: not a string" str))
  (let ((start (or (and (pair? o) (car o)) 0))
        (end (or (and (pair? o) (pair? (cdr o)) (cadr o)) (string-length str))))
    (if (not (and (integer? start) (exact? start)))
        (error "irregex-search: not an exact integer" start))
    (if (not (and (integer? end) (exact? end)))
        (error "irregex-search: not an exact integer" end))
    (irregex-search/chunked x
                            irregex-basic-string-chunker
                            (list str start end)
                            start)))

(define (irregex-search/chunked x cnk src . o)
  (let* ((irx (irregex x))
         (matches (irregex-new-matches irx))
         (i (if (pair? o) (car o) ((chunker-get-start cnk) src))))
    (irregex-match-chunker-set! matches cnk)
    (irregex-search/matches irx cnk (cons src i) src i matches)))

;; internal routine, can be used in loops to avoid reallocating the
;; match vector
(define (irregex-search/matches irx cnk init src i matches)
  (cond
   ((irregex-dfa irx)
    (cond
     ((flag-set? (irregex-flags irx) ~searcher?)
      (cond
       ((dfa-match/longest (irregex-dfa irx) cnk src i #f #f matches 0)
        (irregex-match-start-chunk-set! matches 0 src)
        (irregex-match-start-index-set! matches 0 i)
        matches)
       (else
        #f)))
     ((dfa-match/shortest
       (irregex-dfa/search irx) cnk src i matches 0)
      (let ((dfa (irregex-dfa irx))
            (get-start (chunker-get-start cnk))
            (get-end (chunker-get-end cnk))
            (get-next (chunker-get-next cnk)))
        (let lp1 ((src src) (i i))
          (let ((end (get-end src)))
            (let lp2 ((i i))
              (cond
               ((dfa-match/longest dfa cnk src i #f #f matches 0)
                (irregex-match-start-chunk-set! matches 0 src)
                (irregex-match-start-index-set! matches 0 i)
                matches)
               ((>= i end)
                (let ((next (get-next src)))
                  (and next (lp1 next (get-start next)))))
               (else
                (lp2 (+ i 1)))))))))
     (else
      #f)))
   (else
    (let ((res (irregex-search/backtrack irx cnk init src i matches)))
      (if res (%irregex-match-fail-set! res #f))
      res))))

(define (irregex-search/backtrack irx cnk init src i matches)
  (let ((matcher (irregex-nfa irx))
        (str ((chunker-get-str cnk) src))
        (end ((chunker-get-end cnk) src))
        (get-next (chunker-get-next cnk)))
    (if (flag-set? (irregex-flags irx) ~searcher?)
        (matcher cnk init src str i end matches (lambda () #f))
        (let lp ((src2 src)
                 (str str)
                 (i i)
                 (end end))
          (cond
           ((matcher cnk init src2 str i end matches (lambda () #f))
            (irregex-match-start-chunk-set! matches 0 src2)
            (irregex-match-start-index-set! matches 0 i)
            matches)
           ((< i end)
            (lp src2 str (+ i 1) end))
           (else
            (let ((src2 (get-next src2)))
              (if src2
                  (lp src2
                      ((chunker-get-str cnk) src2)
                      ((chunker-get-start cnk) src2)
                      ((chunker-get-end cnk) src2))
                  #f))))))))

(define (irregex-match irx str . o)
  (if (not (string? str)) (error "irregex-match: not a string" str))
  (let ((start (or (and (pair? o) (car o)) 0))
        (end (or (and (pair? o) (pair? (cdr o)) (cadr o)) (string-length str))))
    (if (not (and (integer? start) (exact? start)))
        (error "irregex-match: not an exact integer" start))
    (if (not (and (integer? end) (exact? end)))
        (error "irregex-match: not an exact integer" end))
    (irregex-match/chunked irx
                           irregex-basic-string-chunker
                           (list str start end))))

(define (irregex-match/chunked irx cnk src)
  (let* ((irx (irregex irx))
         (matches (irregex-new-matches irx)))
    (irregex-match-chunker-set! matches cnk)
    (cond
     ((irregex-dfa irx)
      (and
       (dfa-match/longest
        (irregex-dfa irx) cnk src ((chunker-get-start cnk) src) #f #f matches 0)
       (= ((chunker-get-end cnk) (%irregex-match-end-chunk matches 0))
          (%irregex-match-end-index matches 0))
       (begin
         (irregex-match-start-chunk-set! matches 0 src)
         (irregex-match-start-index-set! matches
                                         0
                                         ((chunker-get-start cnk) src))
         matches)))
     (else
      (let* ((matcher (irregex-nfa irx))
             (str ((chunker-get-str cnk) src))
             (i ((chunker-get-start cnk) src))
             (end ((chunker-get-end cnk) src))
             (init (cons src i)))
        (let lp ((m (matcher cnk init src str i end matches (lambda () #f))))
          (and m
               (cond
                ((and (not ((chunker-get-next cnk)
                            (%irregex-match-end-chunk m 0)))
                      (= ((chunker-get-end cnk)
                          (%irregex-match-end-chunk m 0))
                         (%irregex-match-end-index m 0)))
                 (%irregex-match-fail-set! m #f)
                 m)
                ((%irregex-match-fail m)
                 (lp ((%irregex-match-fail m))))
                (else
                 #f)))))))))

(define (irregex-match? . args)
  (and (apply irregex-match args) #t))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; DFA Matching

;; inline these
(define (dfa-init-state dfa)
  (vector-ref dfa 0))
(define (dfa-next-state dfa node)
  (vector-ref dfa (cadr node)))
(define (dfa-cell-commands dfa node)
  (cddr node))
(define (dfa-finalizer dfa state)
  (car state))

;; this searches for the first end index for which a match is possible
(define (dfa-match/shortest dfa cnk src start matches index)
  (let ((get-str (chunker-get-str cnk))
        (get-start (chunker-get-start cnk))
        (get-end (chunker-get-end cnk))
        (get-next (chunker-get-next cnk))
        ;; Skip the "set-up" state, we don't need to set tags.
        (start-state (dfa-next-state dfa (cadr (dfa-init-state dfa)))))
    (let lp1 ((src src) (start start) (state start-state))
      (and
       src
       (let ((str (get-str src))
             (end (get-end src)))
         (let lp2 ((i start) (state state))
           (cond
            ((dfa-finalizer dfa state)
             (cond
              (index
               (irregex-match-end-chunk-set! matches index src)
               (irregex-match-end-index-set! matches index i)))
             #t)
            ((< i end)
             (let* ((ch (string-ref str i))
                    (next (find (lambda (x)
                                  (or (eqv? ch (car x))
                                      (and (not (char? (car x)))
                                           (cset-contains? (car x) ch))))
                                (cdr state))))
               (and next (lp2 (+ i 1) (dfa-next-state dfa next)))))
            (else
             (let ((next (get-next src)))
               (and next (lp1 next (get-start next) state)))))))))))

(define (finalize! finalizer memory matches)
  (for-each
   (lambda (tag&slot)
     (let* ((tag (car tag&slot))
            (slot (vector-ref memory (cdr tag&slot)))
            (chunk&pos (vector-ref slot tag)))
       (irregex-match-chunk&index-from-tag-set!
        matches tag
        (and chunk&pos (car chunk&pos))
        (and chunk&pos (cdr chunk&pos)))))
   finalizer))
(define (make-initial-memory slots matches)
  (let ((size (* (irregex-match-num-submatches matches) 2))
        (memory (make-vector slots)))
    (do ((i 0 (+ i 1)))
        ((= i slots) memory)
      (vector-set! memory i (make-vector size #f)))))

;; this finds the longest match starting at a given index
(define (dfa-match/longest dfa cnk src start end-src end matches index)
  (let* ((get-str (chunker-get-str cnk))
         (get-start (chunker-get-start cnk))
         (get-end (chunker-get-end cnk))
         (get-next (chunker-get-next cnk))
         (initial-state (dfa-init-state dfa))
         (memory-size (car initial-state))
         (submatches? (not (zero? memory-size)))
         ;; A vector of vectors, each of size <number of start/end submatches>
         (memory (make-initial-memory memory-size matches))
         (init-cell (cadr initial-state))
         (start-state (dfa-next-state dfa init-cell))
         (start-finalizer (dfa-finalizer dfa start-state)))
    (cond
     (index
      (irregex-match-end-chunk-set! matches index #f)
      (irregex-match-end-index-set! matches index #f)))
    (cond (submatches?
           (for-each (lambda (s)
                       (let ((slot (vector-ref memory (cdr s))))
                         (vector-set! slot (car s) (cons src start))))
                     (cdr (dfa-cell-commands dfa init-cell)))))
    (let lp1 ((src src)
              (start start)
              (state start-state)
              (res-src (and start-finalizer src))
              (res-index (and start-finalizer start))
              (finalizer start-finalizer))
      (let ((str (get-str src))
            (end (if (eq? src end-src) end (get-end src))))
        (let lp2 ((i start)
                  (state state)
                  (res-src res-src)
                  (res-index res-index)
                  (finalizer finalizer))
          (cond
           ((>= i end)
            (cond
             ((and index res-src)
              (irregex-match-end-chunk-set! matches index res-src)
              (irregex-match-end-index-set! matches index res-index)))
            (let ((next (and (not (eq? src end-src)) (get-next src))))
              (if next
                  (lp1 next (get-start next) state res-src res-index finalizer)
                  (and index
                       (%irregex-match-end-chunk matches index)
                       (or (not finalizer) (finalize! finalizer memory matches))
                       #t))))
           (else
            (let* ((ch (string-ref str i))
                   (cell (find (lambda (x)
                                 (or (eqv? ch (car x))
                                     (and (not (char? (car x)))
                                          (cset-contains? (car x) ch))))
                               (cdr state))))
              (cond
               (cell
                (let* ((next (dfa-next-state dfa cell))
                       (new-finalizer (dfa-finalizer dfa next)))
                  (cond
                   (submatches?
                    (let ((cmds (dfa-cell-commands dfa cell)))
                      ;; Save match when we're moving from accepting state to
                      ;; rejecting state; this could be the last accepting one.
                      (cond ((and finalizer (not new-finalizer))
                             (finalize! finalizer memory matches)))
                      (for-each (lambda (s)
                                  (let ((slot (vector-ref memory (cdr s)))
                                        (chunk&position (cons src (+ i 1))))
                                    (vector-set! slot (car s) chunk&position)))
                                (cdr cmds))
                      (for-each (lambda (c)
                                  (let* ((tag (vector-ref c 0))
                                         (ss (vector-ref memory (vector-ref c 1)))
                                         (ds (vector-ref memory (vector-ref c 2))))
                                    (vector-set! ds tag (vector-ref ss tag))))
                                (car cmds)))))
                  (if new-finalizer
                      (lp2 (+ i 1) next src (+ i 1) new-finalizer)
                      (lp2 (+ i 1) next res-src res-index #f))))
               (res-src
                (cond
                 (index
                  (irregex-match-end-chunk-set! matches index res-src)
                  (irregex-match-end-index-set! matches index res-index)))
                (cond (finalizer (finalize! finalizer memory matches)))
                #t)
               ((and index (%irregex-match-end-chunk matches index))
                (cond (finalizer (finalize! finalizer memory matches)))
                #t)
               (else
                #f))))))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Named Definitions

(define sre-named-definitions
  `((any . ,*all-chars*)
    (nonl . (- ,*all-chars* (,(string #\newline))))
    (alphabetic . (/ #\a #\z #\A #\Z))
    (alpha . alphabetic)
    (alphanumeric . (/ #\a #\z #\A #\Z #\0 #\9))
    (alphanum . alphanumeric)
    (alnum . alphanumeric)
    (lower-case . (/ #\a #\z))
    (lower . lower-case)
    (upper-case . (/ #\A #\Z))
    (upper . upper-case)
    (numeric . (/ #\0 #\9))
    (num . numeric)
    (digit . numeric)
    (punctuation . (or #\! #\" #\# #\% #\& #\' #\( #\) #\* #\, #\- #\.
                       #\/ #\: #\; #\? #\@ #\[ #\\ #\] #\_ #\{ #\}))
    (punct . punctuation)
    (graphic
     . (or alphanumeric punctuation #\$ #\+ #\< #\= #\> #\^ #\` #\| #\~))
    (graph . graphic)
    (blank . (or #\space ,(integer->char (- (char->integer #\space) 23))))
    (whitespace . (or blank #\newline))
    (space . whitespace)
    (white . whitespace)
    (printing or graphic whitespace)
    (print . printing)

    ;; XXXX we assume a (possibly shifted) ASCII-based ordering
    (control . (/ ,(integer->char (- (char->integer #\space) 32))
                  ,(integer->char (- (char->integer #\space) 1))))
    (cntrl . control)
    (hex-digit . (or numeric (/ #\a #\f #\A #\F)))
    (xdigit . hex-digit)
    (ascii . (/ ,(integer->char (- (char->integer #\space) 32))
                ,(integer->char (+ (char->integer #\space) 95))))
    (ascii-nonl . (/ ,(integer->char (- (char->integer #\space) 32))
                     ,(integer->char (- (char->integer #\newline) 1))
                     ,(integer->char (+ (char->integer #\newline) 1))
                     ,(integer->char (+ (char->integer #\space) 95))))
    (newline . (or (seq ,(integer->char (+ (char->integer #\newline) 3))
                        #\newline)
                   (/ #\newline
                      ,(integer->char (+ (char->integer #\newline) 3)))))

    ;; ... it's really annoying to support old Scheme48
    (word . (seq bow (+ (or alphanumeric #\_)) eow))
    (utf8-tail-char . (/ ,(integer->char (+ (char->integer #\space) #x60))
                         ,(integer->char (+ (char->integer #\space) #xA1))))
    (utf8-2-char . (seq (/ ,(integer->char (+ (char->integer #\space) #xA2))
                           ,(integer->char (+ (char->integer #\space) #xBF)))
                        utf8-tail-char))
    (utf8-3-char . (seq (/ ,(integer->char (+ (char->integer #\space) #xC0))
                           ,(integer->char (+ (char->integer #\space) #xCF)))
                        utf8-tail-char
                        utf8-tail-char))
    (utf8-4-char . (seq (/ ,(integer->char (+ (char->integer #\space) #xD0))
                           ,(integer->char (+ (char->integer #\space) #xD7)))
                        utf8-tail-char
                        utf8-tail-char
                        utf8-tail-char))
    (utf8-any . (or ascii utf8-2-char utf8-3-char utf8-4-char))
    (utf8-nonl . (or ascii-nonl utf8-2-char utf8-3-char utf8-4-char))

    ;; extended library patterns
    (integer . (seq (? (or #\+ #\-)) (+ numeric)))
    (real . (seq (? (or #\+ #\-))
                 (+ numeric) (? #\. (+ numeric))
                 (? (or #\e #\E) integer)))
    ;; slightly more lax than R5RS, allow ->foo, etc.
    (symbol-initial . (or alpha ("!$%&*/:<=>?^_~")))
    (symbol-subsequent . (or symbol-initial digit ("+-.@")))
    (symbol . (or (seq symbol-initial (* symbol-subsequent))
                  (seq ("+-") (? symbol-initial (* symbol-subsequent)))
                  (seq ".." (* "."))))
    (sexp-space . (seq (* (* space) ";" (* nonl) newline) (+ space)))
    (string . (seq #\" (escape #\\ #\") #\"))
    (escape . ,(lambda (esc . o) `(* (or (~ ,esc ,@o) (seq ,esc any)))))

    (ipv4-digit . (seq (? (/ "12")) (? numeric) numeric))
    (ipv4-address . (seq ipv4-digit (= 3 #\. ipv4-digit)))
    ;; XXXX lax, allows multiple double-colons or < 8 terms w/o a ::
    (ipv6-address . (seq (** 0 4 hex-digit)
                         (** 1 7 #\: (? #\:) (** 0 4 hex-digit))))
    (ip-address . (or ipv4-address ipv6-address))
    (domain-atom . (+ (or alphanumeric #\_ #\-)))
    (domain . (seq domain-atom (+ #\. domain-atom)))
    ;; XXXX now anything can be a top-level domain, but this is still handy
    (top-level-domain . (w/nocase (or "arpa" "com" "gov" "mil" "net" "org"
                                      "aero" "biz" "coop" "info" "museum"
                                      "name" "pro" (= 2 alpha))))
    (domain/common . (seq (+ domain-atom #\.) top-level-domain))
    ;;(email-local-part . (seq (+ (or (~ #\") string))))
    (email-local-part . (+ (or alphanumeric #\_ #\- #\. #\+)))
    (email . (seq email-local-part #\@ domain))
    (url-char . (or alnum #\_ #\- #\+ #\\ #\= #\~ #\. #\, #\& #\;
                    (seq "%" hex-digit hex-digit)))
    (url-final-char . (or alnum #\_ #\- #\+ #\\ #\= #\~ #\&
                          (seq "%" hex-digit hex-digit)))
    (http-url . (w/nocase
                 "http" (? "s") "://"
                 (or domain/common ipv4-address) ;; (seq "[" ipv6-address "]")
                 (? ":" (+ numeric)) ;; port
                 ;; path
                 (? "/" (* (or url-char "/"))
                    (? "?" (* url-char))                      ;; query
                    (? "#" (? (* url-char) url-final-char)) ;; fragment
                    )))

    ))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; SRE->tNFA compilation
;;
;; A tagged NFA (tNFA) state is a numbered node with a list of
;; pattern->number transitions, where pattern is character set range,
;; or epsilon (indicating an empty transition).
;;
;; (Only) epsilon transitions may be *tagged*.  Each tag represents
;; either the start or the end of a submatch.
;;
;; There may be overlapping ranges - since it's an NFA we process it
;; by considering all possible transitions.

(define *nfa-presize* 128)  ;; constant
(define *nfa-num-fields* 4) ;; constant

(define (nfa-num-states nfa) (quotient (vector-length nfa) *nfa-num-fields*))
(define (nfa-start-state nfa) (- (nfa-num-states nfa) 1))

(define (nfa-num-tags nfa)
  (vector-ref nfa 0))
(define (nfa-highest-map-index nfa)
  (vector-ref nfa 1))
(define (nfa-set-highest-map-index! nfa idx)
  (vector-set! nfa 1 idx))

(define (nfa-get-state-trans nfa i)
  (if (= i 0) '() (vector-ref nfa (* i *nfa-num-fields*))))
(define (nfa-set-state-trans! nfa i x)
  (vector-set! nfa (* i *nfa-num-fields*) x))

(define (nfa-get-epsilons nfa i)
  (if (= i 0) '() (vector-ref nfa (+ (* i *nfa-num-fields*) 1))))
(define (nfa-set-epsilons! nfa i x)
  (vector-set! nfa (+ (* i *nfa-num-fields*) 1) x))
(define (nfa-add-epsilon! nfa i x t)
  (let ((eps (nfa-get-epsilons nfa i)))
    (if (not (assv x eps))
        (nfa-set-epsilons! nfa i (cons (cons x t) eps)))))

(define (nfa-get-reorder-commands nfa mst)
  (cond ((assoc mst (vector-ref nfa (+ (* (mst-hash mst) *nfa-num-fields*) 2)))
         => cdr)
        (else #f)))
(define (nfa-set-reorder-commands! nfa mst x)
  (let ((i (+ (* (mst-hash mst) *nfa-num-fields*) 2)))
    (vector-set! nfa i (cons (cons mst x) (vector-ref nfa i)))))

(define (nfa-get-closure nfa mst)
  (cond ((assoc mst (vector-ref nfa (+ (* (mst-hash mst) *nfa-num-fields*) 3)))
         => cdr)
        (else #f)))
(define (nfa-add-closure! nfa mst x)
  (let ((i (+ (* (mst-hash mst) *nfa-num-fields*) 3)))
    (vector-set! nfa i (cons (cons mst x) (vector-ref nfa i)))))

;; Compile and return the vector of NFA states (in groups of
;; *nfa-num-fields* packed elements).  The start state will be the
;; last element(s) of the vector, and all remaining states will be in
;; descending numeric order, with state 0 being the unique accepting
;; state.
(define (sre->nfa sre init-flags)
  (let* ((buf (make-vector (* *nfa-presize* *nfa-num-fields*) '()))
         ;; Get cons cells and map them to numeric submatch indexes.
         ;; Doing it here is slightly easier than integrating into the loop below
         (match-index
          (let lp ((sre (list sre)) (max 0) (res '()))
            (cond
             ((not (pair? sre))
              ;; We abuse the transitions slot for state 0 (the final state,
              ;; which can have no transitions) to store the number of tags.
              (vector-set! buf 0 (* max 2))
              ;; We abuse the epsilons slot for state 0 to store the highest
              ;; encountered memory slot mapping index.  Initialize to -1.
              (vector-set! buf 1 -1)
              res)
             ((pair? (car sre))
              ;; The appends here should be safe (are they?)
              (case (caar sre)
                (($ submatch => submatch-named)
                 (lp (append (cdar sre) (cdr sre)) (+ max 1)
                     (cons (cons (car sre) max) res)))
                (else (lp (append (car sre) (cdr sre)) max res))))
             (else (lp (cdr sre) max res))))))
    ;; we loop over an implicit sequence list
    (define (lp ls n flags next)
      (define (new-state-number state)
        (max n (+ 1 state)))
      (define (add-state! n2 trans-ls)
        (if (>= (* n2 *nfa-num-fields*) (vector-length buf))
            (let ((tmp (make-vector (* 2 (vector-length buf)) '())))
              (do ((i (- (vector-length buf) 1) (- i 1)))
                  ((< i 0))
                (vector-set! tmp i (vector-ref buf i)))
              (set! buf tmp)))
        (nfa-set-state-trans! buf n2 trans-ls)
        n2)
      (define (extend-state! next trans-cs)
        (and next
             (add-state! (new-state-number next) (cons trans-cs next))))
      (define (add-char-state! next ch)
        (let ((alt (char-altcase ch)))
          (if (flag-set? flags ~case-insensitive?)
              (extend-state! next (cset-union (char->cset ch) (char->cset alt)))
              (extend-state! next (char->cset ch)))))
      (if (null? ls)
          next
          (cond
           ((or (eq? 'epsilon (car ls)) (equal? "" (car ls)))
            ;; chars and epsilons go directly into the transition table
            (let ((next (lp (cdr ls) n flags next)))
              (and next
                   (let ((new (add-state! (new-state-number next) '())))
                     (nfa-add-epsilon! buf new next #f)
                     new))))
           ((string? (car ls))
            ;; process literal strings a char at a time
            (let ((next (lp (cdr ls) n flags next)))
              (and next
                   (let lp2 ((i (- (string-length (car ls)) 1))
                             (next next))
                     (if (< i 0)
                         next
                         (lp2 (- i 1)
                              (add-char-state! next (string-ref (car ls) i))))
                     ))))
           ((char? (car ls))
            (add-char-state! (lp (cdr ls) n flags next) (car ls)))
           ((symbol? (car ls))
            (let ((cell (assq (car ls) sre-named-definitions)))
              (and cell
                   (lp (cons (if (procedure? (cdr cell))
                                 ((cdr cell))
                                 (cdr cell))
                             (cdr ls))
                       n
                       flags
                       next))))
           ((pair? (car ls))
            (cond
             ((string? (caar ls))       ; Enumerated character set
              (let ((set (if (flag-set? flags ~case-insensitive?)
                             (cset-case-insensitive (string->cset (caar ls)))
                             (string->cset (caar ls)))))
               (extend-state! (lp (cdr ls) n flags next) set)))
             (else
              (case (caar ls)
                ((seq :)
                 ;; for an explicit sequence, just append to the list
                 (lp (append (cdar ls) (cdr ls)) n flags next))
                ((w/case w/nocase w/utf8 w/noutf8)
                 (let* ((next (lp (cdr ls) n flags next))
                        (flags ((if (memq (caar ls) '(w/case w/utf8))
                                    flag-clear
                                    flag-join)
                                flags
                                (if (memq (caar ls) '(w/case w/nocase))
                                    ~case-insensitive?
                                    ~utf8?))))
                   (and next
                        (lp (cdar ls) (new-state-number next) flags next))))
                ((/ - & ~)
                 (let ((range (sre->cset (car ls)
                                         (flag-set? flags ~case-insensitive?))))
                   (extend-state! (lp (cdr ls) n flags next)
                                  range)))
                ((or)
                 (let ((next (lp (cdr ls) n flags next)))
                   (and
                    next
                    (if (null? (cdar ls))
                        ;; empty (or) always fails
                        (add-state! (new-state-number next) '())
                        ;; compile both branches and insert epsilon
                        ;; transitions to either
                        (let* ((b (lp (list (sre-alternate (cddar ls)))
                                      (new-state-number next)
                                      flags
                                      next))
                               (a (and b
                                       (lp (list (cadar ls))
                                           (new-state-number (max b next))
                                           flags
                                           next))))
                          (and a
                               (let ((c (add-state! (new-state-number a)
                                                    '())))
                                 (nfa-add-epsilon! buf c a #f)
                                 (nfa-add-epsilon! buf c b #f)
                                 c)))))))
                ((?)
                 (let ((next (lp (cdr ls) n flags next)))
                   ;; insert an epsilon transition directly to next
                   (and
                    next
                    (let ((a (lp (cdar ls) (new-state-number next) flags next)))
                      (if a
                          (nfa-add-epsilon! buf a next #f))
                      a))))
                ((+ *)
                 (let ((next (lp (cdr ls) n flags next)))
                   (and
                    next
                    (let* ((new (lp '(epsilon)
                                    (new-state-number next)
                                    flags
                                    next))
                           (a (lp (cdar ls) (new-state-number new) flags new)))
                      (cond
                       (a
                        ;; for *, insert an epsilon transition as in ? above
                        (if (eq? '* (caar ls))
                            (nfa-add-epsilon! buf a new #f))
                        ;; for both, insert a loop back to self
                        (nfa-add-epsilon! buf new a #f)))
                      a))))
                ;; need to add these to the match extractor first,
                ;; but they tend to generate large DFAs
                ;;((=)
                ;; (lp (append (vector->list
                ;;              (make-vector (cadar ls)
                ;;                           (sre-sequence (cddar ls))))
                ;;             (cdr ls))
                ;;     n flags next))
                ;;((>=)
                ;; (lp (append (vector->list
                ;;              (make-vector (- (cadar ls) 1)
                ;;                           (sre-sequence (cddar ls))))
                ;;             (cons `(+ ,@(cddar ls)) (cdr ls)))
                ;;     n flags next))
                ;;((**)
                ;; (lp (append (vector->list
                ;;              (make-vector (cadar ls)
                ;;                           (sre-sequence (cdddar ls))))
                ;;             (map
                ;;              (lambda (x) `(? ,x))
                ;;              (vector->list
                ;;               (make-vector (- (caddar ls) (cadar ls))
                ;;                            (sre-sequence (cdddar ls)))))
                ;;             (cdr ls))
                ;;     n flags next))
                ;; ignore submatches altogether
                (($ submatch)
                 (let* ((pre-tag (* (cdr (assq (car ls) match-index)) 2))
                        (post-tag (+ pre-tag 1))
                        (next (lp (cdr ls) n flags next)))
                   (and next
                        (let* ((after (add-state! (new-state-number next) '()))
                               (sub (lp (list (sre-sequence (cdar ls)))
                                        (new-state-number after) flags after))
                               (before (and sub (add-state! (new-state-number sub) '()))))
                          (cond (before
                                 (nfa-add-epsilon! buf before sub pre-tag)
                                 (nfa-add-epsilon! buf after next post-tag)))
                          before))))
                ((=> submatch-named)
                 (let* ((pre-tag (* (cdr (assq (car ls) match-index)) 2))
                        (post-tag (+ pre-tag 1))
                        (next (lp (cdr ls) n flags next)))
                   (and next
                        (let* ((after (add-state! (new-state-number next) '()))
                               (sub (lp (list (sre-sequence (cddar ls)))
                                        (new-state-number after) flags after))
                               (before (and sub (add-state! (new-state-number sub) '()))))
                          (cond (before
                                 (nfa-add-epsilon! buf before sub pre-tag)
                                 (nfa-add-epsilon! buf after next post-tag)))
                          before))))
                (else
                 (cond
                  ((assq (caar ls) sre-named-definitions)
                   => (lambda (cell)
                        (if (procedure? (cdr cell))
                            (lp (cons (apply (cdr cell) (cdar ls)) (cdr ls))
                                n flags next)
                            (error "non-procedure in op position" (caar ls)))))
                  (else #f)))))))
           (else
            #f))))
    (let ((len (lp (list sre) 1 init-flags 0)))
      (and len
           (let ((nfa (make-vector (* *nfa-num-fields* (+ len 1)))))
             (do ((i (- (vector-length nfa) 1) (- i 1)))
                 ((< i 0))
               (vector-set! nfa i (vector-ref buf i)))
             nfa)))))

;; We don't really want to use this, we use the closure compilation
;; below instead, but this is included for reference and testing the
;; sre->nfa conversion.

;; (define (nfa-match nfa str)
;;   (let ((matches (make-vector (nfa-num-tags nfa) #f)))
;;     (let lp ((pos 0) (ls (string->list str)) (state (nfa-start-state nfa)) (epsilons '()))
;;       (and (or (and (null? ls) (zero? state))
;;                (let ((t (nfa-get-state-trans nfa state)))
;;                  (and (not (null? t)) (not (null? ls))
;;                       (cset-contains? (car t) (car ls))
;;                       (lp (+ pos 1) (cdr ls) (cdr t) '())))
;;                (any (lambda (e)
;;                       (let ((old-matches (vector-copy matches)))
;;                         (cond ((cdr e)
;;                                (vector-set! matches (cdr e) pos)))
;;                         (or (and (not (memv (car e) epsilons))
;;                                  (lp pos ls (car e) (cons (car e) epsilons)))
;;                             ;; reset match, apparently this branch failed
;;                             (begin (set! matches old-matches) #f))))
;;                     (nfa-get-epsilons nfa state)))
;;            matches))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; NFA multi-state representation

(define *mst-first-state-index* 3)

(define (mst-mappings-summary mst)
  (vector-ref mst 0))

(define (mst-num-states mst)
  (vector-ref mst 1))

(define (mst-num-states-set! mst num)
  (vector-set! mst 1 num))

(define (mst-hash mst)
  ;; We could do (modulo X (nfa-num-states nfa)) here which would be faster,
  ;; but we can't assume a full numerical tower (and updating *could*
  ;; produce a bignum), so we do it each time when updating the hash.
  (vector-ref mst 2))

(define (mst-hash-set! mst hash)
  (vector-set! mst 2 hash))

;; Returns #f if NFA state does not occur in multi-state
(define (mst-state-mappings mst state)
  (vector-ref mst (+ state *mst-first-state-index*)))

(define (mst-state-mappings-set! mst state mappings)
  (vector-set! mst (+ state *mst-first-state-index*) mappings))

;; A multi-state holds a set of states with their tag-to-slot mappings.
;; Slot 0 contains a summary of all mappings for all states in the multi-state.
;; Slot 1 contains the total number of states in the multi-state.
;; Slot 2 contains a hash value, which is used for quick lookup of cached
;; reorder-commands or epsilon-closure in the NFA.  This is the sum of all
;; state numbers plus each tag value (once per occurrence).  This is a silly
;; hashing calculation, but it seems to produce a well-spread out hash table and
;; it has the added advantage that we can use the value as a quick check if the
;; state is definitely NOT equivalent to another in mst-same-states?
;; The other slots contain mappings for each corresponding state.

(define (make-mst nfa)
  (let ((mst (make-vector (+ (nfa-num-states nfa) *mst-first-state-index*) #f)))
    (vector-set! mst 0 (make-vector (nfa-num-tags nfa) '())) ; tag summary
    (vector-set! mst 1 0)               ; total number of states
    (vector-set! mst 2 0)               ; states and tags hash
    mst))

;; NOTE: This doesn't do a deep copy of the mappings.  Don't mutate them!
(define (mst-copy mst)
  (let ((v (vector-copy mst)))
    (vector-set! v 0 (vector-copy (vector-ref mst 0)))
    v))

(define (nfa-state->mst nfa state mappings)
  (let ((mst (make-mst nfa)))
    (mst-add! nfa mst state mappings)
    mst))

;; Extend multi-state with a state and add its tag->slot mappings.
(define (mst-add! nfa mst state mappings)
  (let ((hash-value (mst-hash mst)))
    (cond ((not (mst-state-mappings mst state)) ;  Update state hash & count?
           (set! hash-value (+ hash-value state))
           (mst-num-states-set! mst (+ (mst-num-states mst) 1))))
    (mst-state-mappings-set! mst state mappings)
    (let ((all-mappings (mst-mappings-summary mst)))
      (for-each
       (lambda (tag&slot)
         (let* ((t (car tag&slot))
                (s (cdr tag&slot))
                (m (vector-ref all-mappings t)))
           (cond ((not (memv s m))
                  (set! hash-value (+ hash-value t))
                  (vector-set! all-mappings t (cons s m))))))
       mappings))
    (mst-hash-set! mst (modulo hash-value (nfa-num-states nfa)))))

;; Same as above, but skip updating mappings summary.
;; Called when we know all the tag->slot mappings are already in the summary.
(define (mst-add/fast! nfa mst state mappings)
  (cond ((not (mst-state-mappings mst state)) ;  Update state hash & count?
         (mst-hash-set!
          mst (modulo (+ (mst-hash mst) state)
                      (nfa-num-states nfa)))
         (mst-num-states-set! mst (+ (mst-num-states mst) 1))))
  (mst-state-mappings-set! mst state mappings))

;; Same as above, assigning a new slot for a tag.  This slot is then
;; added to the summary, if it isn't in there yet.  This is more efficient
;; than looping through all the mappings.
(define (mst-add-tagged! nfa mst state mappings tag slot)
  (let* ((mappings-summary (mst-mappings-summary mst))
         (summary-tag-slots (vector-ref mappings-summary tag))
         (new-mappings (let lp ((m mappings)
                                (res '()))
                         (cond ((null? m) (cons (cons tag slot) res))
                               ((= (caar m) tag)
                                (append res (cons (cons tag slot) (cdr m))))
                               (else (lp (cdr m) (cons (car m) res))))))
         (hash-value (mst-hash mst)))
    (cond ((not (mst-state-mappings mst state)) ;  Update state hash & count?
           (set! hash-value (+ hash-value state))
           (mst-num-states-set! mst (+ (mst-num-states mst) 1))))
    (mst-state-mappings-set! mst state new-mappings)
    (cond ((not (memv slot summary-tag-slots)) ; Update tag/slot summary
           (set! hash-value (+ hash-value tag))
           (vector-set! mappings-summary tag (cons slot summary-tag-slots))))
    (mst-hash-set! mst (modulo hash-value (nfa-num-states nfa)))
    new-mappings))

(define (mst-same-states? a b)
  ;; First check if hash and state counts match, then check each state
  (and (= (mst-hash a) (mst-hash b))
       (= (mst-num-states a) (mst-num-states b))
       (let ((len (vector-length a)))
         (let lp ((i *mst-first-state-index*))
           (or (= i len)
               (and (equal? (not (vector-ref a i))
                            (not (vector-ref b i)))
                    (lp (+ i 1))))))))

(define (mst-fold mst kons knil)
  (let ((limit (vector-length mst)))
    (let lp ((i *mst-first-state-index*)
             (acc knil))
      (if (= i limit)
          acc
          (let ((m (vector-ref mst i)))
            (lp (+ i 1) (if m (kons (- i *mst-first-state-index*) m acc) acc)))))))

;; Find the lowest fresh index for this tag that's unused
;; in the multi-state.  This also updates the nfa's highest
;; tag counter if a completely new slot number was assigned.
(define (next-index-for-tag! nfa tag mst)
  (let* ((highest (nfa-highest-map-index nfa))
         (tag-slots (vector-ref (mst-mappings-summary mst) tag))
         (new-index (do ((slot 0 (+ slot 1)))
                        ((not (memv slot tag-slots)) slot))))
    (cond ((> new-index highest)
           (nfa-set-highest-map-index! nfa new-index)))
    new-index))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; tNFA->DFA compilation
;; During processing, the DFA is a list of the form:
;;
;;   ((annotated-tNFA-states ...) finalizer transitions ...)
;;
;; where the transitions are as in the NFA, except there are no
;; epsilons, duplicate characters or overlapping char-set ranges, and
;; the states moved to are closures (sets of NFA states).  Multiple
;; DFA states may be accepting states.  If the state is an accepting state,
;; the finalizer is a list of (tag . memory-slot) retrieval commands.
;; tNFA-states are annotated with mappings which store the tag values of
;; memory slots, if any.  There is always at most one slot for a tag.
;;
;; The DFA itself simulates a NFA by representing all the simultaneous
;; states the NFA can be in at any given point in time as one DFA state.
;; The tag values are ambiguous since each NFA transition can set a tag.
;; To solve this we keep a bank of memory slots around which tracks tag
;; values for each distinct path through the NFA.
;;
;; Once we get to a final state we can pluck the tag values from the
;; memory slots corresponding to the path through which the NFA could have
;; reached the final state.  To resolve ambiguities, states are assigned
;; priorities, and the path to the final state is chosen correspondingly.
;;
;; For a more detailed explanation about this process, see
;; Ville Laurikari; ``NFAs with Tagged Transitions, their Conversion to
;; Deterministic Automata and Application to Regular Expressions'' (2000).
;; Laurikari also wrote a master's thesis about this approach which is
;; less terse but the algorithms are not exactly the same.
;; ``Efficient submatch addressing for regular expressions'' (2001).
;; This implementation follows the 2000 paper where they differ.

(define (nfa->dfa nfa . o)
  (let* ((max-states (and (pair? o) (car o)))
         (start (nfa-state->mst nfa (nfa-start-state nfa) '()))
         (start-closure (nfa-epsilon-closure nfa start))
         ;; Set up a special "initializer" state from which we reach the
         ;; start-closure to ensure that leading tags are set properly.
         (init-set (tag-set-commands-for-closure nfa start start-closure '()))
         (dummy (make-mst nfa))
         (init-state (list dummy #f `((,start-closure #f () . ,init-set)))))
    ;; Unmarked states are just sets of NFA states with tag-maps, marked states
    ;; are sets of NFA states with transitions to sets of NFA states
    (let lp ((unmarked-states (list start-closure))
             (marked-states (list init-state))
             (dfa-size 0))
      (cond
       ((null? unmarked-states)
        ;; Abuse finalizer slot for storing the number of memory slots we need
        (set-car! (cdr init-state) (+ (nfa-highest-map-index nfa) 1))
        (dfa-renumber (reverse marked-states)))
       ((and max-states (> dfa-size max-states)) ; Too many DFA states
        #f)
       ((assoc (car unmarked-states) marked-states) ; Seen set of NFA-states?
        (lp (cdr unmarked-states) marked-states dfa-size))
       (else
        (let ((dfa-state (car unmarked-states)))
          (let lp2 ((trans (get-distinct-transitions nfa dfa-state))
                    (unmarked-states (cdr unmarked-states))
                    (dfa-trans '()))
            (if (null? trans)
                (let ((finalizer (mst-state-mappings dfa-state 0)))
                  (lp unmarked-states
                      (cons (list dfa-state finalizer dfa-trans) marked-states)
                      (+ dfa-size 1)))
                (let* ((closure (nfa-epsilon-closure nfa (cdar trans)))
                       (reordered
                        (find-reorder-commands nfa closure marked-states))
                       (copy-cmds (if reordered (cdr reordered) '()))
                       ;; Laurikari doesn't mention what "k" is, but it seems it
                       ;; must be the mappings of the state's reach
                       (set-cmds (tag-set-commands-for-closure
                                  nfa (cdar trans) closure copy-cmds))
                       (trans-closure (if reordered (car reordered) closure)))
                  (lp2 (cdr trans)
                       (if reordered
                           unmarked-states
                           (cons trans-closure unmarked-states))
                       (cons `(,trans-closure
                               ,(caar trans) ,copy-cmds . ,set-cmds)
                             dfa-trans)))))))))))

;; When the conversion is complete we renumber the DFA sets-of-states
;; in order and convert the result to a vector for fast lookup.
;; Charsets containing single characters are converted to those characters
;; for quick matching of the literal parts in a regex.
(define (dfa-renumber states)
  (let ((indexes (let lp ((i 0) (states states) (indexes '()))
                   (if (null? states)
                       indexes
                       (lp (+ i 1) (cdr states)
                           (cons (cons (caar states) i) indexes)))))
        (dfa (make-vector (length states))))
    (do ((i 0 (+ i 1))
         (states states (cdr states)))
        ((null? states) dfa)
      (let ((maybe-finalizer (cadar states))
            (transitions (caddar states)))
       (vector-set!
        dfa i
        (cons maybe-finalizer
              (map (lambda (tr)
                     `(,(and (cadr tr) (maybe-cset->char (cadr tr)))
                       ,(cdr (assoc (car tr) indexes)) . ,(cddr tr)))
                   transitions)))))))

;; Extract all distinct ranges and the potential states they can transition
;; to from a given set of states.  Any ranges that would overlap with
;; distinct characters are split accordingly.
;; This function is like "reach" in Laurikari's papers, but for each
;; possible distinct range of characters rather than per character.
(define (get-distinct-transitions nfa annotated-states)
  (define (csets-intersect? a b)
    (let ((i (cset-intersection a b)))
      (and (not (cset-empty? i)) i)))
  (mst-fold
   annotated-states
   (lambda (st mappings res)
     (let ((trans (nfa-get-state-trans nfa st))) ; Always one state per trans
       (if (null? trans)
           res
           (let lp ((ls res) (cs (car trans)) (state (cdr trans)) (res '()))
             (cond
              ;; State not seen yet?  Add a new state transition
              ((null? ls)
               ;; TODO: We should try to find an existing DFA state
               ;; with only this NFA state in it, and extend the cset
               ;; with the current one.  This produces smaller DFAs,
               ;; but takes longer to compile.
               (cons (cons cs (nfa-state->mst nfa state mappings))
                     res))
              ((cset=? cs (caar ls))
               ;; Add state to existing set for this charset
               (mst-add! nfa (cdar ls) state mappings)
               (append ls res))
              ((csets-intersect? cs (caar ls)) =>
               (lambda (intersection)
                 (let* ((only-in-new (cset-difference cs (caar ls)))
                        (only-in-old (cset-difference (caar ls) cs))
                        (states-in-both (cdar ls))
                        (states-for-old
                         (and (not (cset-empty? only-in-old))
                              (mst-copy states-in-both)))
                        (res (if states-for-old
                                 (cons (cons only-in-old states-for-old) res)
                                 res)))
                   (mst-add! nfa states-in-both state mappings)
                   ;; Add this state to the states already here and
                   ;; restrict to the overlapping charset and continue
                   ;; with the remaining subset of the new cset (if
                   ;; nonempty)
                   (if (cset-empty? only-in-new)
                       (cons (cons intersection states-in-both)
                             (append (cdr ls) res))
                       (lp (cdr ls) only-in-new state
                           (cons (cons intersection states-in-both) res))))))
              (else
               (lp (cdr ls) cs state (cons (car ls) res))))))))
   '()))

;; The epsilon-closure of a set of states is all the states reachable
;; through epsilon transitions, with the tags encountered on the way.
(define (nfa-epsilon-closure-internal nfa annotated-states)
  ;; The stack _MUST_ be in this order for some reason I don't fully understand
  (let lp ((stack (mst-fold annotated-states
                                        (lambda (st m res)
                                          (cons (cons st m) res))
                                        '()))
           (priorities (make-vector (nfa-num-states nfa) 0))
           (closure (mst-copy annotated-states)))
    (if (null? stack)
        closure
        (let ((prio/orig-state (caar stack)) ; priority is just the state nr.
              (mappings (cdar stack)))
          (let lp2 ((trans (nfa-get-epsilons nfa prio/orig-state))
                    (stack (cdr stack)))
            (if (null? trans)
                (lp stack priorities closure)
                (let ((state (caar trans)))
                  (cond
                   ;; Our priorities are inverted because we start at
                   ;; the highest state number and go downwards to 0.
                   ((> prio/orig-state (vector-ref priorities state))
                    (vector-set! priorities state prio/orig-state)
                    (cond
                     ((cdar trans) =>   ; tagged transition?
                      (lambda (tag)
                       (let* ((index (next-index-for-tag! nfa tag closure))
                              (new-mappings
                               (mst-add-tagged!
                                nfa closure state mappings tag index)))
                         (lp2 (cdr trans)
                              (cons (cons state new-mappings) stack)))))
                     (else
                      (mst-add/fast! nfa closure state mappings)
                      (lp2 (cdr trans) (cons (cons state mappings) stack)))))
                   (else (lp2 (cdr trans) stack))))))))))

(define (nfa-epsilon-closure nfa states)
  (or (nfa-get-closure nfa states)
      (let ((res (nfa-epsilon-closure-internal nfa states)))
        (nfa-add-closure! nfa states res)
        res)))

;; Generate "set" commands for all tags in the closure that are
;; not present in the original state.
(define (tag-set-commands-for-closure nfa orig-state closure copy-cmds)
  (let ((num-tags (nfa-num-tags nfa))
        (closure-summary (mst-mappings-summary closure))
        (state-summary (mst-mappings-summary orig-state)))
    (let lp ((t 0) (cmds '()))
      (if (= t num-tags)
          cmds
          (let lp2 ((s1 (vector-ref closure-summary t))
                    (s2 (vector-ref state-summary t))
                    (cmds cmds))
            (cond ((null? s1) (lp (+ t 1) cmds))
                  ((or (memv (car s1) s2) ; Tag in original state?
                       ;; Try to avoid generating set-commands for any slots
                       ;; that will be overwritten by copy commands, but only
                       ;; if that slot isn't copied to another slot.
                       (and (not (null? copy-cmds)) ; null check for performance
                            ;; Look for copy command overwriting this tag-slot
                            (any (lambda (c)
                                   (and (= (vector-ref c 0) t)
                                        (= (vector-ref c 2) (car s1))))
                                 copy-cmds)
                            ;; Ensure it's not copied to another slot before
                            ;; discarding the set-command.
                            (not (any (lambda (c)
                                        (and (= (vector-ref c 0) t)
                                             (= (vector-ref c 1) (car s1))))
                                      copy-cmds))))
                   (lp2 (cdr s1) s2 cmds))
                  (else (lp2 (cdr s1) s2
                             (cons (cons t (car s1)) cmds)))))))))

;; Look in dfa-states for an already existing state which matches
;; closure, but has different tag value mappings.
;; If found, calculate reordering commands so we can map the closure
;; to that state instead of adding a new DFA state.
;; This is completely handwaved away in Laurikari's paper (it basically
;; says "insert reordering algorithm here"), so this code was constructed
;; after some experimentation.  In other words, bugs be here.
(define (find-reorder-commands-internal nfa closure dfa-states)
  (let ((num-states (nfa-num-states nfa))
        (num-tags (nfa-num-tags nfa))
        (closure-summary (mst-mappings-summary closure)))
    (let lp ((dfa-states dfa-states))
      (if (null? dfa-states)
          #f
          (if (not (mst-same-states? (caar dfa-states) closure))
              (lp (cdr dfa-states))
              (let lp2 ((state-summary (mst-mappings-summary (caar dfa-states)))
                        (t 0) (cmds '()))
                (if (= t num-tags)
                    (cons (caar dfa-states) cmds)
                    (let lp3 ((closure-slots (vector-ref closure-summary t))
                              (state-slots (vector-ref state-summary t))
                              (cmds cmds))
                      (cond ((null? closure-slots)
                             (if (null? state-slots)
                                 (lp2 state-summary (+ t 1) cmds)
                                 (lp (cdr dfa-states))))
                            ((null? state-slots) (lp (cdr dfa-states)))
                            (else (lp3 (cdr closure-slots)
                                       (cdr state-slots)
                                       (if (= (car closure-slots) (car state-slots))
                                           cmds
                                           (cons (vector t (car closure-slots) (car state-slots))
                                                 cmds)))))))))))))

(define (find-reorder-commands nfa closure dfa-states)
  (or (nfa-get-reorder-commands nfa closure)
      (let ((res (find-reorder-commands-internal nfa closure dfa-states)))
        (nfa-set-reorder-commands! nfa closure res)
        res)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Closure Compilation
;;
;; We use this for non-regular expressions instead of an interpreted
;; NFA matcher.  We use backtracking anyway, but this gives us more
;; freedom of implementation, allowing us to support patterns that
;; can't be represented in the above NFA representation.

(define (sre->procedure sre . o)
  (define names
    (if (and (pair? o) (pair? (cdr o))) (cadr o) (sre-names sre 1 '())))
  (let lp ((sre sre)
           (n 1)
           (flags (if (pair? o) (car o) ~none))
           (next (lambda (cnk init src str i end matches fail)
                   (irregex-match-start-chunk-set! matches 0 (car init))
                   (irregex-match-start-index-set! matches 0 (cdr init))
                   (irregex-match-end-chunk-set! matches 0 src)
                   (irregex-match-end-index-set! matches 0 i)
                   (%irregex-match-fail-set! matches fail)
                   matches)))
    ;; XXXX this should be inlined
    (define (rec sre) (lp sre n flags next))
    (cond
     ((pair? sre)
      (if (string? (car sre))
          (sre-cset->procedure
           (sre->cset (car sre) (flag-set? flags ~case-insensitive?))
           next)
          (case (car sre)
            ((~ - & /)
             (sre-cset->procedure
              (sre->cset sre (flag-set? flags ~case-insensitive?))
              next))
            ((or)
             (case (length (cdr sre))
               ((0) (lambda (cnk init src str i end matches fail) (fail)))
               ((1) (rec (cadr sre)))
               (else
                (let* ((first (rec (cadr sre)))
                       (rest (lp (sre-alternate (cddr sre))
                                 (+ n (sre-count-submatches (cadr sre)))
                                 flags
                                 next)))
                  (lambda (cnk init src str i end matches fail)
                    (first cnk init src str i end matches
                           (lambda ()
                             (rest cnk init src str i end matches fail))))))))
            ((w/case)
             (lp (sre-sequence (cdr sre))
                 n
                 (flag-clear flags ~case-insensitive?)
                 next))
            ((w/nocase)
             (lp (sre-sequence (cdr sre))
                 n
                 (flag-join flags ~case-insensitive?)
                 next))
            ((w/utf8)
             (lp (sre-sequence (cdr sre)) n (flag-join flags ~utf8?) next))
            ((w/noutf8)
             (lp (sre-sequence (cdr sre)) n (flag-clear flags ~utf8?) next))
            ((seq :)
             (case (length (cdr sre))
               ((0) next)
               ((1) (rec (cadr sre)))
               (else
                (let ((rest (lp (sre-sequence (cddr sre))
                                (+ n (sre-count-submatches (cadr sre)))
                                flags
                                next)))
                  (lp (cadr sre) n flags rest)))))
            ((?)
             (let ((body (rec (sre-sequence (cdr sre)))))
               (lambda (cnk init src str i end matches fail)
                 (body cnk init src str i end matches
                       (lambda () (next cnk init src str i end matches fail))))))
            ((??)
             (let ((body (rec (sre-sequence (cdr sre)))))
               (lambda (cnk init src str i end matches fail)
                 (next cnk init src str i end matches
                       (lambda () (body cnk init src str i end matches fail))))))
            ((*)
             (cond
              ((sre-empty? (sre-sequence (cdr sre)))
               (error "invalid sre: empty *" sre))
              (else
               (letrec
                   ((body
                     (lp (sre-sequence (cdr sre))
                         n
                         flags
                         (lambda (cnk init src str i end matches fail)
                           (body cnk init src str i end matches
                                 (lambda ()
                                   (next cnk init src str i end matches fail)
                                   ))))))
                 (lambda (cnk init src str i end matches fail)
                   (body cnk init src str i end matches
                         (lambda ()
                           (next cnk init src str i end matches fail))))))))
            ((*?)
             (cond
              ((sre-empty? (sre-sequence (cdr sre)))
               (error "invalid sre: empty *?" sre))
              (else
               (letrec
                   ((body
                     (lp (sre-sequence (cdr sre))
                         n
                         flags
                         (lambda (cnk init src str i end matches fail)
                           (next cnk init src str i end matches
                                 (lambda ()
                                   (body cnk init src str i end matches fail)
                                   ))))))
                 (lambda (cnk init src str i end matches fail)
                   (next cnk init src str i end matches
                         (lambda ()
                           (body cnk init src str i end matches fail))))))))
            ((+)
             (lp (sre-sequence (cdr sre))
                 n
                 flags
                 (rec (list '* (sre-sequence (cdr sre))))))
            ((=)
             (rec `(** ,(cadr sre) ,(cadr sre) ,@(cddr sre))))
            ((>=)
             (rec `(** ,(cadr sre) #f ,@(cddr sre))))
            ((**)
             (cond
              ((or (and (number? (cadr sre))
                        (number? (caddr sre))
                        (> (cadr sre) (caddr sre)))
                   (and (not (cadr sre)) (caddr sre)))
               (lambda (cnk init src str i end matches fail) (fail)))
              (else
               (letrec
                   ((from (cadr sre))
                    (to (caddr sre))
                    (body-contents (sre-sequence (cdddr sre)))
                    (body
                     (lambda (count)
                       (lp body-contents
                           n
                           flags
                           (lambda (cnk init src str i end matches fail)
                             (if (and to (= count to))
                                 (next cnk init src str i end matches fail)
                                 ((body (+ 1 count))
                                  cnk init src str i end matches
                                  (lambda ()
                                    (if (>= count from)
                                        (next cnk init src str i end matches fail)
                                        (fail))))))))))
                 (if (and (zero? from) to (zero? to))
                     next
                     (lambda (cnk init src str i end matches fail)
                       ((body 1) cnk init src str i end matches
                        (lambda ()
                          (if (zero? from)
                              (next cnk init src str i end matches fail)
                              (fail))))))))))
            ((**?)
             (cond
              ((or (and (number? (cadr sre))
                        (number? (caddr sre))
                        (> (cadr sre) (caddr sre)))
                   (and (not (cadr sre)) (caddr sre)))
               (lambda (cnk init src str i end matches fail) (fail)))
              (else
               (letrec
                   ((from (cadr sre))
                    (to (caddr sre))
                    (body-contents (sre-sequence (cdddr sre)))
                    (body
                     (lambda (count)
                       (lp body-contents
                           n
                           flags
                           (lambda (cnk init src str i end matches fail)
                             (if (< count from)
                                 ((body (+ 1 count)) cnk init
                                  src str i end matches fail)
                                 (next cnk init src str i end matches
                                       (lambda ()
                                         (if (and to (= count to))
                                             (fail)
                                             ((body (+ 1 count)) cnk init
                                              src str i end matches fail))))))))))
                 (if (and (zero? from) to (zero? to))
                     next
                     (lambda (cnk init src str i end matches fail)
                       (if (zero? from)
                           (next cnk init src str i end matches
                                 (lambda ()
                                   ((body 1) cnk init src str i end matches fail)))
                           ((body 1) cnk init src str i end matches fail))))))))
            ((word)
             (rec `(seq bow ,@(cdr sre) eow)))
            ((word+)
             (rec `(seq bow (+ (& (or alphanumeric "_")
                                  (or ,@(cdr sre)))) eow)))
            ((posix-string)
             (rec (string->sre (cadr sre))))
            ((look-ahead)
             (let ((check
                    (lp (sre-sequence (cdr sre))
                        n
                        flags
                        (lambda (cnk init src str i end matches fail) i))))
               (lambda (cnk init src str i end matches fail)
                 (if (check cnk init src str i end matches (lambda () #f))
                     (next cnk init src str i end matches fail)
                     (fail)))))
            ((neg-look-ahead)
             (let ((check
                    (lp (sre-sequence (cdr sre))
                        n
                        flags
                        (lambda (cnk init src str i end matches fail) i))))
               (lambda (cnk init src str i end matches fail)
                 (if (check cnk init src str i end matches (lambda () #f))
                     (fail)
                     (next cnk init src str i end matches fail)))))
            ((look-behind neg-look-behind)
             (let ((check
                    (lp (sre-sequence
                         (cons '(* any) (append (cdr sre) '(eos))))
                        n
                        flags
                        (lambda (cnk init src str i end matches fail) i))))
               (lambda (cnk init src str i end matches fail)
                 (let* ((cnk* (wrap-end-chunker cnk src i))
                        (str* ((chunker-get-str cnk*) (car init)))
                        (i* (cdr init))
                        (end* ((chunker-get-end cnk*) (car init))))
                   (if ((if (eq? (car sre) 'look-behind) (lambda (x) x) not)
                        (check cnk* init (car init) str* i* end* matches
                               (lambda () #f)))
                       (next cnk init src str i end matches fail)
                       (fail))))))
            ((atomic)
             (let ((once
                    (lp (sre-sequence (cdr sre))
                        n
                        flags
                        (lambda (cnk init src str i end matches fail) i))))
               (lambda (cnk init src str i end matches fail)
                 (let ((j (once cnk init src str i end matches (lambda () #f))))
                   (if j
                       (next cnk init src str j end matches fail)
                       (fail))))))
            ((if)
             (let* ((test-submatches (sre-count-submatches (cadr sre)))
                    (pass (lp (caddr sre) flags (+ n test-submatches) next))
                    (fail (if (pair? (cdddr sre))
                              (lp (cadddr sre)
                                  (+ n test-submatches
                                     (sre-count-submatches (caddr sre)))
                                  flags
                                  next)
                              (lambda (cnk init src str i end matches fail)
                                (fail)))))
               (cond
                ((or (number? (cadr sre)) (symbol? (cadr sre)))
                 (let ((index
                        (if (symbol? (cadr sre))
                            (cond
                             ((assq (cadr sre) names) => cdr)
                             (else
                              (error "unknown named backref in SRE IF" sre)))
                            (cadr sre))))
                   (lambda (cnk init src str i end matches fail2)
                     (if (%irregex-match-end-chunk matches index)
                         (pass cnk init src str i end matches fail2)
                         (fail cnk init src str i end matches fail2)))))
                (else
                 (let ((test (lp (cadr sre) n flags pass)))
                   (lambda (cnk init src str i end matches fail2)
                     (test cnk init src str i end matches
                           (lambda () (fail cnk init src str i end matches fail2)))
                     ))))))
            ((backref backref-ci)
             (let ((n (cond ((number? (cadr sre)) (cadr sre))
                            ((assq (cadr sre) names) => cdr)
                            (else (error "unknown backreference" (cadr sre)))))
                   (compare (if (or (eq? (car sre) 'backref-ci)
                                    (flag-set? flags ~case-insensitive?))
                                string-ci=?
                                string=?)))
               (lambda (cnk init src str i end matches fail)
                 (let ((s (irregex-match-substring matches n)))
                   (if (not s)
                       (fail)
                       ;; XXXX create an abstract subchunk-compare
                       (let lp ((src src)
                                (str str)
                                (i i)
                                (end end)
                                (j 0)
                                (len (string-length s)))
                         (cond
                          ((<= len (- end i))
                           (cond
                            ((compare (substring s j (string-length s))
                                      (substring str i (+ i len)))
                             (next cnk init src str (+ i len) end matches fail))
                            (else
                             (fail))))
                          (else
                           (cond
                            ((compare (substring s j (+ j (- end i)))
                                      (substring str i end))
                             (let ((src2 ((chunker-get-next cnk) src)))
                               (if src2
                                   (lp src2
                                       ((chunker-get-str cnk) src2)
                                       ((chunker-get-start cnk) src2)
                                       ((chunker-get-end cnk) src2)
                                       (+ j (- end i))
                                       (- len (- end i)))
                                   (fail))))
                            (else
                             (fail)))))))))))
            ((dsm)
             (lp (sre-sequence (cdddr sre)) (+ n (cadr sre)) flags next))
            (($ submatch)
             (let ((body
                    (lp (sre-sequence (cdr sre))
                        (+ n 1)
                        flags
                        (lambda (cnk init src str i end matches fail)
                          (let ((old-source
                                 (%irregex-match-end-chunk matches n))
                                (old-index
                                 (%irregex-match-end-index matches n)))
                            (irregex-match-end-chunk-set! matches n src)
                            (irregex-match-end-index-set! matches n i)
                            (next cnk init src str i end matches
                                  (lambda ()
                                    (irregex-match-end-chunk-set!
                                     matches n old-source)
                                    (irregex-match-end-index-set!
                                     matches n old-index)
                                    (fail))))))))
               (lambda (cnk init src str i end matches fail)
                 (let ((old-source (%irregex-match-start-chunk matches n))
                       (old-index (%irregex-match-start-index matches n)))
                   (irregex-match-start-chunk-set! matches n src)
                   (irregex-match-start-index-set! matches n i)
                   (body cnk init src str i end matches
                         (lambda ()
                           (irregex-match-start-chunk-set!
                            matches n old-source)
                           (irregex-match-start-index-set!
                            matches n old-index)
                           (fail)))))))
            ((=> submatch-named)
             (rec `(submatch ,@(cddr sre))))
            (else
             (error "unknown regexp operator" sre)))))
     ((symbol? sre)
      (case sre
        ((any)
         (lambda (cnk init src str i end matches fail)
           (if (< i end)
               (next cnk init src str (+ i 1) end matches fail)
               (let ((src2 ((chunker-get-next cnk) src)))
                 (if src2
                     (let ((str2 ((chunker-get-str cnk) src2))
                           (i2 ((chunker-get-start cnk) src2))
                           (end2 ((chunker-get-end cnk) src2)))
                       (next cnk init src2 str2 (+ i2 1) end2 matches fail))
                     (fail))))))
        ((nonl)
         (lambda (cnk init src str i end matches fail)
           (if (< i end)
               (if (not (eqv? #\newline (string-ref str i)))
                   (next cnk init src str (+ i 1) end matches fail)
                   (fail))
               (let ((src2 ((chunker-get-next cnk) src)))
                 (if src2
                     (let ((str2 ((chunker-get-str cnk) src2))
                           (i2 ((chunker-get-start cnk) src2))
                           (end2 ((chunker-get-end cnk) src2)))
                       (if (not (eqv? #\newline (string-ref str2 i2)))
                           (next cnk init src2 str2 (+ i2 1) end2 matches fail)
                           (fail)))
                     (fail))))))
        ((bos)
         (lambda (cnk init src str i end matches fail)
           (if (and (eq? src (car init)) (eqv? i (cdr init)))
               (next cnk init src str i end matches fail)
               (fail))))
        ((bol)
         (lambda (cnk init src str i end matches fail)
           (if (or (and (eq? src (car init)) (eqv? i (cdr init)))
                   (and (> i ((chunker-get-start cnk) src))
                        (eqv? #\newline (string-ref str (- i 1)))))
               (next cnk init src str i end matches fail)
               (fail))))
        ((bow)
         (lambda (cnk init src str i end matches fail)
           (if (and (or (if (> i ((chunker-get-start cnk) src))
                            (not (char-alphanumeric? (string-ref str (- i 1))))
                            (let ((ch (chunker-prev-char cnk src end)))
                              (and ch (not (char-alphanumeric? ch)))))
                        (and (eq? src (car init)) (eqv? i (cdr init))))
                    (if (< i end)
                        (char-alphanumeric? (string-ref str i))
                        (let ((next ((chunker-get-next cnk) src)))
                          (and next
                               (char-alphanumeric?
                                (string-ref ((chunker-get-str cnk) next)
                                            ((chunker-get-start cnk) next)))))))
               (next cnk init src str i end matches fail)
               (fail))))
        ((eos)
         (lambda (cnk init src str i end matches fail)
           (if (and (>= i end) (not ((chunker-get-next cnk) src)))
               (next cnk init src str i end matches fail)
               (fail))))
        ((eol)
         (lambda (cnk init src str i end matches fail)
           (if (if (< i end)
                   (eqv? #\newline (string-ref str i))
                   (let ((src2 ((chunker-get-next cnk) src)))
                     (if (not src2)
                         #t
                         (eqv? #\newline
                               (string-ref ((chunker-get-str cnk) src2)
                                           ((chunker-get-start cnk) src2))))))
               (next cnk init src str i end matches fail)
               (fail))))
        ((eow)
         (lambda (cnk init src str i end matches fail)
           (if (and (if (< i end)
                        (not (char-alphanumeric? (string-ref str i)))
                        (let ((ch (chunker-next-char cnk src)))
                          (or (not ch) (not (char-alphanumeric? ch)))))
                    (if (> i ((chunker-get-start cnk) src))
                        (char-alphanumeric? (string-ref str (- i 1)))
                        (let ((prev (chunker-prev-char cnk init src)))
                          (or (not prev) (char-alphanumeric? prev)))))
               (next cnk init src str i end matches fail)
               (fail))))
        ((nwb)  ;; non-word-boundary
         (lambda (cnk init src str i end matches fail)
           (let ((c1 (if (< i end)
                         (string-ref str i)
                         (chunker-next-char cnk src)))
                 (c2 (if (> i ((chunker-get-start cnk) src))
                         (string-ref str (- i 1))
                         (chunker-prev-char cnk init src))))
             (if (and c1 c2
                      (if (char-alphanumeric? c1)
                          (char-alphanumeric? c2)
                          (not (char-alphanumeric? c2))))
                 (next cnk init src str i end matches fail)
                 (fail)))))
        ((epsilon)
         next)
        (else
         (let ((cell (assq sre sre-named-definitions)))
           (if cell
               (rec (cdr cell))
               (error "unknown regexp" sre))))))
     ((char? sre)
      (if (flag-set? flags ~case-insensitive?)
          ;; case-insensitive
          (lambda (cnk init src str i end matches fail)
            (if (>= i end)
                (let lp ((src2 ((chunker-get-next cnk) src)))
                  (if src2
                      (let ((str2 ((chunker-get-str cnk) src2))
                            (i2 ((chunker-get-start cnk) src2))
                            (end2 ((chunker-get-end cnk) src2)))
                        (if (>= i2 end2)
                            (lp ((chunker-get-next cnk) src2))
                            (if (char-ci=? sre (string-ref str2 i2))
                                (next cnk init src2 str2 (+ i2 1) end2
                                      matches fail)
                                (fail))))
                      (fail)))
                (if (char-ci=? sre (string-ref str i))
                    (next cnk init src str (+ i 1) end matches fail)
                    (fail))))
          ;; case-sensitive
          (lambda (cnk init src str i end matches fail)
            (if (>= i end)
                (let lp ((src2 ((chunker-get-next cnk) src)))
                  (if src2
                      (let ((str2 ((chunker-get-str cnk) src2))
                            (i2 ((chunker-get-start cnk) src2))
                            (end2 ((chunker-get-end cnk) src2)))
                        (if (>= i2 end2)
                            (lp ((chunker-get-next cnk) src2))
                            (if (char=? sre (string-ref str2 i2))
                                (next cnk init src2 str2 (+ i2 1) end2
                                      matches fail)
                                (fail))))
                      (fail)))
                (if (char=? sre (string-ref str i))
                    (next cnk init src str (+ i 1) end matches fail)
                    (fail))))
          ))
     ((string? sre)
      (rec (sre-sequence (string->list sre)))
;; XXXX reintroduce faster string matching on chunks
;;       (if (flag-set? flags ~case-insensitive?)
;;           (rec (sre-sequence (string->list sre)))
;;           (let ((len (string-length sre)))
;;             (lambda (cnk init src str i end matches fail)
;;               (if (and (<= (+ i len) end)
;;                        (%substring=? sre str 0 i len))
;;                   (next str (+ i len) matches fail)
;;                   (fail)))))
      )
     (else
      (error "unknown regexp" sre)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Character Sets
;;
;; Simple character sets as lists of ranges, as used in the NFA/DFA
;; compilation.  This is not especially efficient, but is portable and
;; scalable for any range of character sets.

(define (sre-cset->procedure cset next)
  (lambda (cnk init src str i end matches fail)
    (if (< i end)
        (if (cset-contains? cset (string-ref str i))
            (next cnk init src str (+ i 1) end matches fail)
            (fail))
        (let ((src2 ((chunker-get-next cnk) src)))
          (if src2
              (let ((str2 ((chunker-get-str cnk) src2))
                    (i2 ((chunker-get-start cnk) src2))
                    (end2 ((chunker-get-end cnk) src2)))
                (if (cset-contains? cset (string-ref str2 i2))
                    (next cnk init src2 str2 (+ i2 1) end2 matches fail)
                    (fail)))
              (fail))))))

(define (make-cset) (vector))
(define (range->cset from to) (vector (cons from to)))
(define (char->cset ch) (vector (cons ch ch)))
(define (cset-empty? cs) (zero? (vector-length cs)))
(define (maybe-cset->char cs)
  (if (and (= (vector-length cs) 1)
           (char=? (car (vector-ref cs 0)) (cdr (vector-ref cs 0))))
      (car (vector-ref cs 0))
      cs))

;; Since csets are sorted, there's only one possible representation of any cset
(define cset=? equal?)

(define (cset-size cs)
  (let ((len (vector-length cs)))
   (let lp ((i 0) (size 0))
     (if (= i len)
         size
         (lp (+ i 1) (+ size 1
                        (- (char->integer (cdr (vector-ref cs i)))
                           (char->integer (car (vector-ref cs i))))))))))

(define (cset->plist cs)
  (let lp ((i (- (vector-length cs) 1))
           (res '()))
    (if (= i -1)
        res
        (lp (- i 1) (cons (car (vector-ref cs i))
                          (cons (cdr (vector-ref cs i)) res))))))

(define (plist->cset ls)
  (let lp ((ls ls) (res (make-cset)))
    (if (null? ls)
        res
        (lp (cddr ls) (cset-union (range->cset (car ls) (cadr ls)) res)))))

(define (string->cset s)
  (fold (lambda (ch cs)
          (cset-adjoin cs ch))
        (make-cset)
        (string->list s)))

(define (sre->cset sre . o)
  (let lp ((sre sre) (ci? (and (pair? o) (car o))))
    (define (rec sre) (lp sre ci?))
    (cond
     ((pair? sre)
      (if (string? (car sre))
          (if ci?
              (cset-case-insensitive (string->cset (car sre)))
              (string->cset (car sre)))
          (case (car sre)
            ((~)
             (cset-complement
              (fold cset-union (rec (cadr sre)) (map rec (cddr sre)))))
            ((&)
             (fold cset-intersection (rec (cadr sre)) (map rec (cddr sre))))
            ((-)
             (fold (lambda (x res) (cset-difference res x))
                   (rec (cadr sre))
                   (map rec (cddr sre))))
            ((/)
             (let ((res (plist->cset (sre-flatten-ranges (cdr sre)))))
               (if ci?
                   (cset-case-insensitive res)
                   res)))
            ((or)
             (fold cset-union (rec (cadr sre)) (map rec (cddr sre))))
            ((w/case)
             (lp (sre-alternate (cdr sre)) #f))
            ((w/nocase)
             (lp (sre-alternate (cdr sre)) #t))
            (else
             (error "not a valid sre char-set operator" sre)))))
     ((char? sre) (if ci?
                      (cset-case-insensitive (range->cset sre sre))
                      (range->cset sre sre)))
     ((string? sre) (rec (list sre)))
     (else
      (let ((cell (assq sre sre-named-definitions)))
        (if cell
            (rec (cdr cell))
            (error "not a valid sre char-set" sre)))))))

(define (cset->sre cset)
  (cons '/
        (fold (lambda (x res) (cons (car x) (cons (cdr x) res)))
              '()
              (vector->list cset))))

(define (cset-contains? cset ch)
  (let ((len (vector-length cset)))
    (case len
      ((0) #f)
      ((1) (let ((range (vector-ref cset 0)))
             (and (char<=? ch (cdr range)) (char<=? (car range) ch))))
      (else (let lp ((lower 0) (upper len))
              (let* ((middle (quotient (+ upper lower) 2))
                     (range (vector-ref cset middle)))
                (cond ((char<? (cdr range) ch)
                       (let ((next (+ middle 1)))
                         (and (< next upper) (lp next upper))))
                      ((char<? ch (car range))
                       (and (< lower middle) (lp lower middle)))
                      (else #t))))))))

(define (char-ranges-union a b)
  (cons (if (char<=? (car a) (car b)) (car a) (car b))
        (if (char>=? (cdr a) (cdr b)) (cdr a) (cdr b))))

(define (cset-union a b)
  (let union-range ((a (vector->list a))
                    (b (vector->list b))
                    (res '()))
    (cond
     ((null? a) (list->vector (reverse (append (reverse b) res))))
     ((null? b) (list->vector (reverse (append (reverse a) res))))
     (else
      (let ((a-range (car a))
            (b-range (car b)))
        (cond
         ;; Can't use next-char here since it will cause an error if we are
         ;; comparing a cset with the maximum character as high char.
         ((< (+ (char->integer (cdr a-range)) 1) (char->integer (car b-range)))
          (union-range (cdr a) b (cons a-range res)))
         ((> (char->integer (car a-range)) (+ (char->integer (cdr b-range)) 1))
          (union-range (cdr b) a (cons b-range res)))
         ((char>=? (cdr a-range) (car b-range))
          (union-range (cons (char-ranges-union a-range b-range) (cdr a))
                       (cdr b)
                       res))
         (else (union-range (cdr a)
                            (cons (char-ranges-union a-range b-range) (cdr b))
                            res))))))))

(define (cset-adjoin cs ch) (cset-union cs (char->cset ch)))

(define (next-char c)
  (integer->char (+ (char->integer c) 1)))

(define (prev-char c)
  (integer->char (- (char->integer c) 1)))

(define (cset-difference a b)
  (let diff ((a (vector->list a))
             (b (vector->list b))
             (res '()))
    (cond ((null? a) (list->vector (reverse res)))
          ((null? b) (list->vector (append (reverse res) a)))
          (else
           (let ((a-range (car a))
                 (b-range (car b)))
             (cond
              ((char<? (cdr a-range) (car b-range))
               (diff (cdr a) b (cons a-range res)))
              ((char>? (car a-range) (cdr b-range))
               (diff a (cdr b) res))
              ((and (char<=? (car b-range) (car a-range))
                    (char>=? (cdr b-range) (cdr a-range)))
               (diff (cdr a) b res))
              (else (let ((left (and (char<? (car a-range) (car b-range))
                                     (cons (car a-range)
                                           (prev-char (car b-range)))))
                          (right (and (char>? (cdr a-range) (cdr b-range))
                                      (cons (next-char (cdr b-range))
                                            (cdr a-range)))))
                      (diff (if right (cons right (cdr a)) (cdr a))
                            b
                            (if left (cons left res) res))))))))))

(define (min-char a b)
  (if (char<? a b) a b))

(define (max-char a b)
  (if (char<? a b) b a))

(define (cset-intersection a b)
  (let intersect ((a (vector->list a))
                  (b (vector->list b))
                  (res '()))
    (if (or (null? a) (null? b))
        (list->vector (reverse res))
        (let ((a-range (car a))
              (b-range (car b)))
          (cond
           ((char<? (cdr a-range) (car b-range))
            (intersect (cdr a) b res))
           ((char>? (car a-range) (cdr b-range))
            (intersect a (cdr b) res))
           (else
            (let ((result (cons (max-char (car b-range) (car a-range))
                                (min-char (cdr a-range) (cdr b-range)))))
              (intersect (if (char>? (cdr a-range) (cdr result))
                             a (cdr a))
                         (if (char>? (cdr b-range) (cdr result))
                             b (cdr b))
                         (cons result res)))))))))

(define (cset-complement a)
  (cset-difference (sre->cset *all-chars*) a))

;; This could use some optimization :)
(define (cset-case-insensitive a)
  (let lp ((ls (vector->list a)) (res '()))
    (cond ((null? ls) (list->vector (reverse res)))
          ((and (char-alphabetic? (caar ls))
                (char-alphabetic? (cdar ls)))
           (lp (cdr ls)
               (reverse
                (vector->list
                 (cset-union (cset-union (list->vector (reverse res))
                                         (vector (car ls)))
                             (range->cset (char-altcase (caar ls))
                                          (char-altcase (cdar ls))))))))
          (else (lp (cdr ls) (reverse (vector->list
                                       (cset-union (list->vector (reverse res))
                                                   (vector (car ls))))))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Match and Replace Utilities

(define (irregex-fold/fast irx kons knil str . o)
  (if (not (string? str)) (error "irregex-fold: not a string" str))
  (let* ((irx (irregex irx))
         (matches (irregex-new-matches irx))
         (finish (or (and (pair? o) (car o)) (lambda (i acc) acc)))
         (start (if (and (pair? o) (pair? (cdr o))) (cadr o) 0))
         (end (if (and (pair? o) (pair? (cdr o)) (pair? (cddr o)))
                  (caddr o)
                  (string-length str)))
         (init-src (list str start end))
         (init (cons init-src start)))
    (if (not (and (integer? start) (exact? start)))
        (error "irregex-fold: not an exact integer" start))
    (if (not (and (integer? end) (exact? end)))
        (error "irregex-fold: not an exact integer" end))
    (irregex-match-chunker-set! matches irregex-basic-string-chunker)
    (let lp ((src init-src) (i start) (acc knil))
      (if (>= i end)
          (finish i acc)
          (let ((m (irregex-search/matches
                    irx
                    irregex-basic-string-chunker
                    init
                    src
                    i
                    matches)))
            (if (not m)
                (finish i acc)
                (let ((j (%irregex-match-end-index m 0)))
                  (if (= j i)
                      ;; skip one char forward if we match the empty string
                      (lp (list str (+ j 1) end) (+ j 1) acc)
                      (let ((acc (kons i m acc)))
                        (irregex-reset-matches! matches)
                        ;; no need to continue looping if this is a
                        ;; searcher - it's already consumed the only
                        ;; available match
                        (if (flag-set? (irregex-flags irx) ~searcher?)
                            (finish j acc)
                            (lp (list str j end) j acc)))))))))))

(define (irregex-fold irx kons . args)
  (if (not (procedure? kons)) (error "irregex-fold: not a procedure" kons))
  (let ((kons2 (lambda (i m acc) (kons i (irregex-copy-matches m) acc))))
    (apply irregex-fold/fast irx kons2 args)))

(define (irregex-fold/chunked/fast irx kons knil cnk start . o)
  (let* ((irx (irregex irx))
         (matches (irregex-new-matches irx))
         (finish (or (and (pair? o) (car o)) (lambda (src i acc) acc)))
         (i (if (and (pair? o) (pair? (cdr o)))
                (cadr o)
                ((chunker-get-start cnk) start)))
         (init (cons start i)))
    (if (not (integer? i)) (error "irregex-fold/chunked: not an integer" i))
    (irregex-match-chunker-set! matches cnk)
    (let lp ((start start) (i i) (acc knil))
      (if (not start)
          (finish start i acc)
          (let ((m (irregex-search/matches irx cnk init start i matches)))
            (if (not m)
                (finish start i acc)
                (let ((end-src (%irregex-match-end-chunk m 0))
                      (end-index (%irregex-match-end-index m 0)))
                  (if (and (eq? end-src start) (= end-index i))
                      (if (>= end-index ((chunker-get-end cnk) end-src ))
                          (let ((next ((chunker-get-next cnk) end-src)))
                            (lp next ((chunker-get-start cnk) next) acc))
                          (lp end-src (+ end-index 1) acc))
                      (let ((acc (kons start i m acc)))
                        (irregex-reset-matches! matches)
                        ;; no need to continue looping if this is a
                        ;; searcher - it's already consumed the only
                        ;; available match
                        (if (flag-set? (irregex-flags irx) ~searcher?)
                            (finish end-src end-index acc)
                            (lp end-src end-index acc)))))))))))

(define (irregex-fold/chunked irx kons . args)
  (if (not (procedure? kons)) (error "irregex-fold/chunked: not a procedure" kons))
  (let ((kons2 (lambda (s i m acc) (kons s i (irregex-copy-matches m) acc))))
    (apply irregex-fold/chunked/fast irx kons2 args)))

(define (irregex-replace irx str . o)
  (if (not (string? str)) (error "irregex-replace: not a string" str))
  (let ((m (irregex-search irx str)))
    (if m
        (string-cat-reverse
         (cons (substring str (%irregex-match-end-index m 0) (string-length str))
               (append (irregex-apply-match m o)
                       (list (substring str 0 (%irregex-match-start-index m 0)))
                       )))
        str)))

(define (irregex-replace/all irx str . o)
  (if (not (string? str)) (error "irregex-replace/all: not a string" str))
  (irregex-fold/fast
   irx
   (lambda (i m acc)
     (let ((m-start (%irregex-match-start-index m 0)))
       (append (irregex-apply-match m o)
               (if (>= i m-start)
                   acc
                   (cons (substring str i m-start) acc)))))
   '()
   str
   (lambda (i acc)
     (let ((end (string-length str)))
       (string-cat-reverse (if (>= i end)
                               acc
                               (cons (substring str i end) acc)))))))

(define (irregex-apply-match m ls)
  (let lp ((ls ls) (res '()))
    (if (null? ls)
        res
        (cond
         ((integer? (car ls))
          (lp (cdr ls)
              (cons (or (irregex-match-substring m (car ls)) "") res)))
         ((procedure? (car ls))
          (lp (cdr ls) (cons ((car ls) m) res)))
         ((symbol? (car ls))
          (case (car ls)
            ((pre)
             (lp (cdr ls)
                 (cons (substring (car (%irregex-match-start-chunk m 0))
                                  0
                                  (%irregex-match-start-index m 0))
                       res)))
            ((post)
             (let ((str (car (%irregex-match-start-chunk m 0))))
               (lp (cdr ls)
                   (cons (substring str
                                    (%irregex-match-end-index m 0)
                                    (string-length str))
                         res))))
            (else
             (cond
              ((assq (car ls) (irregex-match-names m))
               => (lambda (x) (lp (cons (cdr x) (cdr ls)) res)))
              (else
               (error "unknown match replacement" (car ls)))))))
         (else
          (lp (cdr ls) (cons (car ls) res)))))))

(define (irregex-extract irx str . o)
  (if (not (string? str)) (error "irregex-extract: not a string" str))
  (apply irregex-fold/fast
         irx
         (lambda (i m a) (cons (irregex-match-substring m) a))
         '()
         str
         (lambda (i a) (reverse a))
         o))

(define (irregex-split irx str . o)
  (if (not (string? str)) (error "irregex-split: not a string" str))
  (let ((start (if (pair? o) (car o) 0))
        (end (if (and (pair? o) (pair? (cdr o))) (cadr o) (string-length str))))
    (irregex-fold/fast
     irx
     (lambda (i m a)
       (if (= i (%irregex-match-start-index m 0))
           a
           (cons (substring str i (%irregex-match-start-index m 0)) a)))
     '()
     str
     (lambda (i a)
       (reverse (if (= i end) a (cons (substring str i end) a))))
     start
     end)))
)

Deleted match.scm.

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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
;;;; match.scm -- portable hygienic pattern matcher -*- coding: utf-8 -*-
;;
;; This code is written by Alex Shinn and placed in the
;; Public Domain.  All warranties are disclaimed.

;;> \example-import[(srfi 9)]

;;> A portable hygienic pattern matcher.

;;> This is a full superset of the popular \hyperlink[
;;> "http://www.cs.indiana.edu/scheme-repository/code.match.html"]{match}
;;> package by Andrew Wright, written in fully portable \scheme{syntax-rules}
;;> and thus preserving hygiene.

;;> The most notable extensions are the ability to use \emph{non-linear}
;;> patterns - patterns in which the same identifier occurs multiple
;;> times, tail patterns after ellipsis, and the experimental tree patterns.

;;> \section{Patterns}

;;> Patterns are written to look like the printed representation of
;;> the objects they match.  The basic usage is

;;> \scheme{(match expr (pat body ...) ...)}

;;> where the result of \var{expr} is matched against each pattern in
;;> turn, and the corresponding body is evaluated for the first to
;;> succeed.  Thus, a list of three elements matches a list of three
;;> elements.

;;> \example{(let ((ls (list 1 2 3))) (match ls ((1 2 3) #t)))}

;;> If no patterns match an error is signalled.

;;> Identifiers will match anything, and make the corresponding
;;> binding available in the body.

;;> \example{(match (list 1 2 3) ((a b c) b))}

;;> If the same identifier occurs multiple times, the first instance
;;> will match anything, but subsequent instances must match a value
;;> which is \scheme{equal?} to the first.

;;> \example{(match (list 1 2 1) ((a a b) 1) ((a b a) 2))}

;;> The special identifier \scheme{_} matches anything, no matter how
;;> many times it is used, and does not bind the result in the body.

;;> \example{(match (list 1 2 1) ((_ _ b) 1) ((a b a) 2))}

;;> To match a literal identifier (or list or any other literal), use
;;> \scheme{quote}.

;;> \example{(match 'a ('b 1) ('a 2))}

;;> Analogous to its normal usage in scheme, \scheme{quasiquote} can
;;> be used to quote a mostly literally matching object with selected
;;> parts unquoted.

;;> \example|{(match (list 1 2 3) (`(1 ,b ,c) (list b c)))}|

;;> Often you want to match any number of a repeated pattern.  Inside
;;> a list pattern you can append \scheme{...} after an element to
;;> match zero or more of that pattern (like a regexp Kleene star).

;;> \example{(match (list 1 2) ((1 2 3 ...) #t))}
;;> \example{(match (list 1 2 3) ((1 2 3 ...) #t))}
;;> \example{(match (list 1 2 3 3 3) ((1 2 3 ...) #t))}

;;> Pattern variables matched inside the repeated pattern are bound to
;;> a list of each matching instance in the body.

;;> \example{(match (list 1 2) ((a b c ...) c))}
;;> \example{(match (list 1 2 3) ((a b c ...) c))}
;;> \example{(match (list 1 2 3 4 5) ((a b c ...) c))}

;;> More than one \scheme{...} may not be used in the same list, since
;;> this would require exponential backtracking in the general case.
;;> However, \scheme{...} need not be the final element in the list,
;;> and may be succeeded by a fixed number of patterns.

;;> \example{(match (list 1 2 3 4) ((a b c ... d e) c))}
;;> \example{(match (list 1 2 3 4 5) ((a b c ... d e) c))}
;;> \example{(match (list 1 2 3 4 5 6 7) ((a b c ... d e) c))}

;;> \scheme{___} is provided as an alias for \scheme{...} when it is
;;> inconvenient to use the ellipsis (as in a syntax-rules template).

;;> The \scheme{..1} syntax is exactly like the \scheme{...} except
;;> that it matches one or more repetitions (like a regexp "+").

;;> \example{(match (list 1 2) ((a b c ..1) c))}
;;> \example{(match (list 1 2 3) ((a b c ..1) c))}

;;> The boolean operators \scheme{and}, \scheme{or} and \scheme{not}
;;> can be used to group and negate patterns analogously to their
;;> Scheme counterparts.

;;> The \scheme{and} operator ensures that all subpatterns match.
;;> This operator is often used with the idiom \scheme{(and x pat)} to
;;> bind \var{x} to the entire value that matches \var{pat}
;;> (c.f. "as-patterns" in ML or Haskell).  Another common use is in
;;> conjunction with \scheme{not} patterns to match a general case
;;> with certain exceptions.

;;> \example{(match 1 ((and) #t))}
;;> \example{(match 1 ((and x) x))}
;;> \example{(match 1 ((and x 1) x))}

;;> The \scheme{or} operator ensures that at least one subpattern
;;> matches.  If the same identifier occurs in different subpatterns,
;;> it is matched independently.  All identifiers from all subpatterns
;;> are bound if the \scheme{or} operator matches, but the binding is
;;> only defined for identifiers from the subpattern which matched.

;;> \example{(match 1 ((or) #t) (else #f))}
;;> \example{(match 1 ((or x) x))}
;;> \example{(match 1 ((or x 2) x))}

;;> The \scheme{not} operator succeeds if the given pattern doesn't
;;> match.  None of the identifiers used are available in the body.

;;> \example{(match 1 ((not 2) #t))}

;;> The more general operator \scheme{?} can be used to provide a
;;> predicate.  The usage is \scheme{(? predicate pat ...)} where
;;> \var{predicate} is a Scheme expression evaluating to a predicate
;;> called on the value to match, and any optional patterns after the
;;> predicate are then matched as in an \scheme{and} pattern.

;;> \example{(match 1 ((? odd? x) x))}

;;> The field operator \scheme{=} is used to extract an arbitrary
;;> field and match against it.  It is useful for more complex or
;;> conditional destructuring that can't be more directly expressed in
;;> the pattern syntax.  The usage is \scheme{(= field pat)}, where
;;> \var{field} can be any expression, and should result in a
;;> procedure of one argument, which is applied to the value to match
;;> to generate a new value to match against \var{pat}.

;;> Thus the pattern \scheme{(and (= car x) (= cdr y))} is equivalent
;;> to \scheme{(x . y)}, except it will result in an immediate error
;;> if the value isn't a pair.

;;> \example{(match '(1 . 2) ((= car x) x))}
;;> \example{(match 4 ((= square x) x))}

;;> The record operator \scheme{$} is used as a concise way to match
;;> records defined by SRFI-9 (or SRFI-99).  The usage is
;;> \scheme{($ rtd field ...)}, where \var{rtd} should be the record
;;> type descriptor specified as the first argument to
;;> \scheme{define-record-type}, and each \var{field} is a subpattern
;;> matched against the fields of the record in order.  Not all fields
;;> must be present.

;;> \example{
;;> (let ()
;;>   (define-record-type employee
;;>     (make-employee name title)
;;>     employee?
;;>     (name get-name)
;;>     (title get-title))
;;>   (match (make-employee "Bob" "Doctor")
;;>     (($ employee n t) (list t n))))
;;> }

;;> For records with more fields it can be helpful to match them by
;;> name rather than position.  For this you can use the \scheme{@}
;;> operator, originally a Gauche extension:

;;> \example{
;;> (let ()
;;>   (define-record-type employee
;;>     (make-employee name title)
;;>     employee?
;;>     (name get-name)
;;>     (title get-title))
;;>   (match (make-employee "Bob" "Doctor")
;;>     ((@ employee (title t) (name n)) (list t n))))
;;> }

;;> The \scheme{set!} and \scheme{get!} operators are used to bind an
;;> identifier to the setter and getter of a field, respectively.  The
;;> setter is a procedure of one argument, which mutates the field to
;;> that argument.  The getter is a procedure of no arguments which
;;> returns the current value of the field.

;;> \example{(let ((x (cons 1 2))) (match x ((1 . (set! s)) (s 3) x)))}
;;> \example{(match '(1 . 2) ((1 . (get! g)) (g)))}

;;> The new operator \scheme{***} can be used to search a tree for
;;> subpatterns.  A pattern of the form \scheme{(x *** y)} represents
;;> the subpattern \var{y} located somewhere in a tree where the path
;;> from the current object to \var{y} can be seen as a list of the
;;> form \scheme{(x ...)}.  \var{y} can immediately match the current
;;> object in which case the path is the empty list.  In a sense it's
;;> a 2-dimensional version of the \scheme{...} pattern.

;;> As a common case the pattern \scheme{(_ *** y)} can be used to
;;> search for \var{y} anywhere in a tree, regardless of the path
;;> used.

;;> \example{(match '(a (a (a b))) ((x *** 'b) x))}
;;> \example{(match '(a (b) (c (d e) (f g))) ((x *** 'g) x))}

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Notes

;; The implementation is a simple generative pattern matcher - each
;; pattern is expanded into the required tests, calling a failure
;; continuation if the tests fail.  This makes the logic easy to
;; follow and extend, but produces sub-optimal code in cases where you
;; have many similar clauses due to repeating the same tests.
;; Nonetheless a smart compiler should be able to remove the redundant
;; tests.  For MATCH-LET and DESTRUCTURING-BIND type uses there is no
;; performance hit.

;; The original version was written on 2006/11/29 and described in the
;; following Usenet post:
;;   http://groups.google.com/group/comp.lang.scheme/msg/0941234de7112ffd
;; and is still available at
;;   http://synthcode.com/scheme/match-simple.scm
;; It's just 80 lines for the core MATCH, and an extra 40 lines for
;; MATCH-LET, MATCH-LAMBDA and other syntactic sugar.
;;
;; A variant of this file which uses COND-EXPAND in a few places for
;; performance can be found at
;;   http://synthcode.com/scheme/match-cond-expand.scm
;;
;; 2016/03/06 - fixing named match-let (thanks to Stefan Israelsson Tampe)
;; 2015/05/09 - fixing bug in var extraction of quasiquote patterns
;; 2014/11/24 - adding Gauche's `@' pattern for named record field matching
;; 2012/12/26 - wrapping match-let&co body in lexical closure
;; 2012/11/28 - fixing typo s/vetor/vector in largely unused set! code
;; 2012/05/23 - fixing combinatorial explosion of code in certain or patterns
;; 2011/09/25 - fixing bug when directly matching an identifier repeated in
;;              the pattern (thanks to Stefan Israelsson Tampe)
;; 2011/01/27 - fixing bug when matching tail patterns against improper lists
;; 2010/09/26 - adding `..1' patterns (thanks to Ludovic Courtès)
;; 2010/09/07 - fixing identifier extraction in some `...' and `***' patterns
;; 2009/11/25 - adding `***' tree search patterns
;; 2008/03/20 - fixing bug where (a ...) matched non-lists
;; 2008/03/15 - removing redundant check in vector patterns
;; 2008/03/06 - you can use `...' portably now (thanks to Taylor Campbell)
;; 2007/09/04 - fixing quasiquote patterns
;; 2007/07/21 - allowing ellipsis patterns in non-final list positions
;; 2007/04/10 - fixing potential hygiene issue in match-check-ellipsis
;;              (thanks to Taylor Campbell)
;; 2007/04/08 - clean up, commenting
;; 2006/12/24 - bugfixes
;; 2006/12/01 - non-linear patterns, shared variables in OR, get!/set!

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; force compile-time syntax errors with useful messages

(define-syntax match-syntax-error
  (syntax-rules ()
    ((_) (match-syntax-error "invalid match-syntax-error usage"))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;> \section{Syntax}

;;> \macro{(match expr (pattern . body) ...)\br{}
;;> (match expr (pattern (=> failure) . body) ...)}

;;> The result of \var{expr} is matched against each \var{pattern} in
;;> turn, according to the pattern rules described in the previous
;;> section, until the the first \var{pattern} matches.  When a match is
;;> found, the corresponding \var{body}s are evaluated in order,
;;> and the result of the last expression is returned as the result
;;> of the entire \scheme{match}.  If a \var{failure} is provided,
;;> then it is bound to a procedure of no arguments which continues,
;;> processing at the next \var{pattern}.  If no \var{pattern} matches,
;;> an error is signalled.

;; The basic interface.  MATCH just performs some basic syntax
;; validation, binds the match expression to a temporary variable `v',
;; and passes it on to MATCH-NEXT.  It's a constant throughout the
;; code below that the binding `v' is a direct variable reference, not
;; an expression.

(define-syntax match
  (syntax-rules ()
    ((match)
     (match-syntax-error "missing match expression"))
    ((match atom)
     (match-syntax-error "no match clauses"))
    ((match (app ...) (pat . body) ...)
     (let ((v (app ...)))
       (match-next v ((app ...) (set! (app ...))) (pat . body) ...)))
    ((match #(vec ...) (pat . body) ...)
     (let ((v #(vec ...)))
       (match-next v (v (set! v)) (pat . body) ...)))
    ((match atom (pat . body) ...)
     (let ((v atom))
       (match-next v (atom (set! atom)) (pat . body) ...)))
    ))

;; MATCH-NEXT passes each clause to MATCH-ONE in turn with its failure
;; thunk, which is expanded by recursing MATCH-NEXT on the remaining
;; clauses.  `g+s' is a list of two elements, the get! and set!
;; expressions respectively.

(define-syntax match-next
  (syntax-rules (=>)
    ;; no more clauses, the match failed
    ((match-next v g+s)
     (error 'match "no matching pattern"))
    ;; named failure continuation
    ((match-next v g+s (pat (=> failure) . body) . rest)
     (let ((failure (lambda () (match-next v g+s . rest))))
       ;; match-one analyzes the pattern for us
       (match-one v pat g+s (match-drop-ids (begin . body)) (failure) ())))
    ;; anonymous failure continuation, give it a dummy name
    ((match-next v g+s (pat . body) . rest)
     (match-next v g+s (pat (=> failure) . body) . rest))))

;; MATCH-ONE first checks for ellipsis patterns, otherwise passes on to
;; MATCH-TWO.

(define-syntax match-one
  (syntax-rules ()
    ;; If it's a list of two or more values, check to see if the
    ;; second one is an ellipsis and handle accordingly, otherwise go
    ;; to MATCH-TWO.
    ((match-one v (p q . r) g+s sk fk i)
     (match-check-ellipsis
      q
      (match-extract-vars p (match-gen-ellipsis v p r  g+s sk fk i) i ())
      (match-two v (p q . r) g+s sk fk i)))
    ;; Go directly to MATCH-TWO.
    ((match-one . x)
     (match-two . x))))

;; This is the guts of the pattern matcher.  We are passed a lot of
;; information in the form:
;;
;;   (match-two var pattern getter setter success-k fail-k (ids ...))
;;
;; usually abbreviated
;;
;;   (match-two v p g+s sk fk i)
;;
;; where VAR is the symbol name of the current variable we are
;; matching, PATTERN is the current pattern, getter and setter are the
;; corresponding accessors (e.g. CAR and SET-CAR! of the pair holding
;; VAR), SUCCESS-K is the success continuation, FAIL-K is the failure
;; continuation (which is just a thunk call and is thus safe to expand
;; multiple times) and IDS are the list of identifiers bound in the
;; pattern so far.

;; Replace '_' with ':_' as the former is forbidden as an auxiliariy
;; keyword in R6RS. (FBE)
(define-syntax match-two
  (syntax-rules (:_ ___ ..1 *** quote quasiquote ? $ struct @ object = and or not set! get!)
    ((match-two v () g+s (sk ...) fk i)
     (if (null? v) (sk ... i) fk))
    ((match-two v (quote p) g+s (sk ...) fk i)
     (if (equal? v 'p) (sk ... i) fk))
    ((match-two v (quasiquote p) . x)
     (match-quasiquote v p . x))
    ((match-two v (and) g+s (sk ...) fk i) (sk ... i))
    ((match-two v (and p q ...) g+s sk fk i)
     (match-one v p g+s (match-one v (and q ...) g+s sk fk) fk i))
    ((match-two v (or) g+s sk fk i) fk)
    ((match-two v (or p) . x)
     (match-one v p . x))
    ((match-two v (or p ...) g+s sk fk i)
     (match-extract-vars (or p ...) (match-gen-or v (p ...) g+s sk fk i) i ()))
    ((match-two v (not p) g+s (sk ...) fk i)
     (match-one v p g+s (match-drop-ids fk) (sk ... i) i))
    ((match-two v (get! getter) (g s) (sk ...) fk i)
     (let ((getter (lambda () g))) (sk ... i)))
    ((match-two v (set! setter) (g (s ...)) (sk ...) fk i)
     (let ((setter (lambda (x) (s ... x)))) (sk ... i)))
    ((match-two v (? pred . p) g+s sk fk i)
     (if (pred v) (match-one v (and . p) g+s sk fk i) fk))
    ((match-two v (= proc p) . x)
     (let ((w (proc v))) (match-one w p . x)))
    ((match-two v (p ___ . r) g+s sk fk i)
     (match-extract-vars p (match-gen-ellipsis v p r g+s sk fk i) i ()))
    ((match-two v (p) g+s sk fk i)
     (if (and (pair? v) (null? (cdr v)))
         (let ((w (car v)))
           (match-one w p ((car v) (set-car! v)) sk fk i))
         fk))
    ((match-two v (p *** q) g+s sk fk i)
     (match-extract-vars p (match-gen-search v p q g+s sk fk i) i ()))
    ((match-two v (p *** . q) g+s sk fk i)
     (match-syntax-error "invalid use of ***" (p *** . q)))
    ((match-two v (p ..1) g+s sk fk i)
     (if (pair? v)
         (match-one v (p ___) g+s sk fk i)
         fk))
    ((match-two v ($ rec p ...) g+s sk fk i)
     (if (is-a? v rec)
         (match-record-refs v rec 0 (p ...) g+s sk fk i)
         fk))
    ((match-two v (struct rec p ...) g+s sk fk i)
     (if (is-a? v rec)
         (match-record-refs v rec 0 (p ...) g+s sk fk i)
         fk))
    ((match-two v (@ rec p ...) g+s sk fk i)
     (if (is-a? v rec)
         (match-record-named-refs v rec (p ...) g+s sk fk i)
         fk))
    ((match-two v (object rec p ...) g+s sk fk i)
     (if (is-a? v rec)
         (match-record-named-refs v rec (p ...) g+s sk fk i)
         fk))
    ((match-two v (p . q) g+s sk fk i)
     (if (pair? v)
         (let ((w (car v)) (x (cdr v)))
           (match-one w p ((car v) (set-car! v))
                      (match-one x q ((cdr v) (set-cdr! v)) sk fk)
                      fk
                      i))
         fk))
    ((match-two v #(p ...) g+s . x)
     (match-vector v 0 () (p ...) . x))
    ;; Next line: replace '_' with ':_'. (FBE)
    ((match-two v :_ g+s (sk ...) fk i) (sk ... i))
    ;; Not a pair or vector or special literal, test to see if it's a
    ;; new symbol, in which case we just bind it, or if it's an
    ;; already bound symbol or some other literal, in which case we
    ;; compare it with EQUAL?.
    ((match-two v x g+s (sk ...) fk (id ...))
     (let-syntax
         ((new-sym?
           (syntax-rules (id ...)
             ((new-sym? x sk2 fk2) sk2)
             ((new-sym? y sk2 fk2) fk2))))
       (new-sym? random-sym-to-match
                 (let ((x v)) (sk ... (id ... x)))
                 (if (equal? v x) (sk ... (id ...)) fk))))
    ))

;; QUASIQUOTE patterns

(define-syntax match-quasiquote
  (syntax-rules (unquote unquote-splicing quasiquote)
    ((_ v (unquote p) g+s sk fk i)
     (match-one v p g+s sk fk i))
    ((_ v ((unquote-splicing p) . rest) g+s sk fk i)
     (if (pair? v)
       (match-one v
                  (p . tmp)
                  (match-quasiquote tmp rest g+s sk fk)
                  fk
                  i)
       fk))
    ((_ v (quasiquote p) g+s sk fk i . depth)
     (match-quasiquote v p g+s sk fk i #f . depth))
    ((_ v (unquote p) g+s sk fk i x . depth)
     (match-quasiquote v p g+s sk fk i . depth))
    ((_ v (unquote-splicing p) g+s sk fk i x . depth)
     (match-quasiquote v p g+s sk fk i . depth))
    ((_ v (p . q) g+s sk fk i . depth)
     (if (pair? v)
       (let ((w (car v)) (x (cdr v)))
         (match-quasiquote
          w p g+s
          (match-quasiquote-step x q g+s sk fk depth)
          fk i . depth))
       fk))
    ((_ v #(elt ...) g+s sk fk i . depth)
     (if (vector? v)
       (let ((ls (vector->list v)))
         (match-quasiquote ls (elt ...) g+s sk fk i . depth))
       fk))
    ((_ v x g+s sk fk i . depth)
     (match-one v 'x g+s sk fk i))))

(define-syntax match-quasiquote-step
  (syntax-rules ()
    ((match-quasiquote-step x q g+s sk fk depth i)
     (match-quasiquote x q g+s sk fk i . depth))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Utilities

;; Takes two values and just expands into the first.
(define-syntax match-drop-ids
  (syntax-rules ()
    ((_ expr ids ...) expr)))

(define-syntax match-tuck-ids
  (syntax-rules ()
    ((_ (letish args (expr ...)) ids ...)
     (letish args (expr ... ids ...)))))

(define-syntax match-drop-first-arg
  (syntax-rules ()
    ((_ arg expr) expr)))

;; To expand an OR group we try each clause in succession, passing the
;; first that succeeds to the success continuation.  On failure for
;; any clause, we just try the next clause, finally resorting to the
;; failure continuation fk if all clauses fail.  The only trick is
;; that we want to unify the identifiers, so that the success
;; continuation can refer to a variable from any of the OR clauses.

(define-syntax match-gen-or
  (syntax-rules ()
    ((_ v p g+s (sk ...) fk (i ...) ((id id-ls) ...))
     (let ((sk2 (lambda (id ...) (sk ... (i ... id ...)))))
       (match-gen-or-step v p g+s (match-drop-ids (sk2 id ...)) fk (i ...))))))

(define-syntax match-gen-or-step
  (syntax-rules ()
    ((_ v () g+s sk fk . x)
     ;; no OR clauses, call the failure continuation
     fk)
    ((_ v (p) . x)
     ;; last (or only) OR clause, just expand normally
     (match-one v p . x))
    ((_ v (p . q) g+s sk fk i)
     ;; match one and try the remaining on failure
     (let ((fk2 (lambda () (match-gen-or-step v q g+s sk fk i))))
       (match-one v p g+s sk (fk2) i)))
    ))

;; We match a pattern (p ...) by matching the pattern p in a loop on
;; each element of the variable, accumulating the bound ids into lists.

;; Look at the body of the simple case - it's just a named let loop,
;; matching each element in turn to the same pattern.  The only trick
;; is that we want to keep track of the lists of each extracted id, so
;; when the loop recurses we cons the ids onto their respective list
;; variables, and on success we bind the ids (what the user input and
;; expects to see in the success body) to the reversed accumulated
;; list IDs.

(define-syntax match-gen-ellipsis
  (syntax-rules ()
    ((_ v p () g+s (sk ...) fk i ((id id-ls) ...))
     (match-check-identifier p
       ;; simplest case equivalent to (p ...), just bind the list
       (let ((p v))
         (if (list? p)
             (sk ... i)
             fk))
       ;; simple case, match all elements of the list
       (let loop ((ls v) (id-ls '()) ...)
         (cond
           ((null? ls)
            (let ((id (reverse id-ls)) ...) (sk ... i)))
           ((pair? ls)
            (let ((w (car ls)))
              (match-one w p ((car ls) (set-car! ls))
                         (match-drop-ids (loop (cdr ls) (cons id id-ls) ...))
                         fk i)))
           (else
            fk)))))
    ((_ v p r g+s (sk ...) fk i ((id id-ls) ...))
     ;; general case, trailing patterns to match, keep track of the
     ;; remaining list length so we don't need any backtracking
     (match-verify-no-ellipsis
      r
      (let* ((tail-len (length 'r))
             (ls v)
             (len (and (list? ls) (length ls))))
        (if (or (not len) (< len tail-len))
            fk
            (let loop ((ls ls) (n len) (id-ls '()) ...)
              (cond
                ((= n tail-len)
                 (let ((id (reverse id-ls)) ...)
                   (match-one ls r (#f #f) (sk ...) fk i)))
                ((pair? ls)
                 (let ((w (car ls)))
                   (match-one w p ((car ls) (set-car! ls))
                              (match-drop-ids
                               (loop (cdr ls) (- n 1) (cons id id-ls) ...))
                              fk
                              i)))
                (else
                 fk)))))))))

;; This is just a safety check.  Although unlike syntax-rules we allow
;; trailing patterns after an ellipsis, we explicitly disable multiple
;; ellipsis at the same level.  This is because in the general case
;; such patterns are exponential in the number of ellipsis, and we
;; don't want to make it easy to construct very expensive operations
;; with simple looking patterns.  For example, it would be O(n^2) for
;; patterns like (a ... b ...) because we must consider every trailing
;; element for every possible break for the leading "a ...".

(define-syntax match-verify-no-ellipsis
  (syntax-rules ()
    ((_ (x . y) sk)
     (match-check-ellipsis
      x
      (match-syntax-error
       "multiple ellipsis patterns not allowed at same level")
      (match-verify-no-ellipsis y sk)))
    ((_ () sk)
     sk)
    ((_ x sk)
     (match-syntax-error "dotted tail not allowed after ellipsis" x))))

;; To implement the tree search, we use two recursive procedures.  TRY
;; attempts to match Y once, and on success it calls the normal SK on
;; the accumulated list ids as in MATCH-GEN-ELLIPSIS.  On failure, we
;; call NEXT which first checks if the current value is a list
;; beginning with X, then calls TRY on each remaining element of the
;; list.  Since TRY will recursively call NEXT again on failure, this
;; effects a full depth-first search.
;;
;; The failure continuation throughout is a jump to the next step in
;; the tree search, initialized with the original failure continuation
;; FK.

(define-syntax match-gen-search
  (syntax-rules ()
    ((match-gen-search v p q g+s sk fk i ((id id-ls) ...))
     (letrec ((try (lambda (w fail id-ls ...)
                     (match-one w q g+s
                                (match-tuck-ids
                                 (let ((id (reverse id-ls)) ...)
                                   sk))
                                (next w fail id-ls ...) i)))
              (next (lambda (w fail id-ls ...)
                      (if (not (pair? w))
                          (fail)
                          (let ((u (car w)))
                            (match-one
                             u p ((car w) (set-car! w))
                             (match-drop-ids
                              ;; accumulate the head variables from
                              ;; the p pattern, and loop over the tail
                              (let ((id-ls (cons id id-ls)) ...)
                                (let lp ((ls (cdr w)))
                                  (if (pair? ls)
                                      (try (car ls)
                                           (lambda () (lp (cdr ls)))
                                           id-ls ...)
                                      (fail)))))
                             (fail) i))))))
       ;; the initial id-ls binding here is a dummy to get the right
       ;; number of '()s
       (let ((id-ls '()) ...)
         (try v (lambda () fk) id-ls ...))))))

;; Vector patterns are just more of the same, with the slight
;; exception that we pass around the current vector index being
;; matched.

(define-syntax match-vector
  (syntax-rules (___)
    ((_ v n pats (p q) . x)
     (match-check-ellipsis q
                          (match-gen-vector-ellipsis v n pats p . x)
                          (match-vector-two v n pats (p q) . x)))
    ((_ v n pats (p ___) sk fk i)
     (match-gen-vector-ellipsis v n pats p sk fk i))
    ((_ . x)
     (match-vector-two . x))))

;; Check the exact vector length, then check each element in turn.

(define-syntax match-vector-two
  (syntax-rules ()
    ((_ v n ((pat index) ...) () sk fk i)
     (if (vector? v)
         (let ((len (vector-length v)))
           (if (= len n)
               (match-vector-step v ((pat index) ...) sk fk i)
               fk))
         fk))
    ((_ v n (pats ...) (p . q) . x)
     (match-vector v (+ n 1) (pats ... (p n)) q . x))))

(define-syntax match-vector-step
  (syntax-rules ()
    ((_ v () (sk ...) fk i) (sk ... i))
    ((_ v ((pat index) . rest) sk fk i)
     (let ((w (vector-ref v index)))
       (match-one w pat ((vector-ref v index) (vector-set! v index))
                  (match-vector-step v rest sk fk)
                  fk i)))))

;; With a vector ellipsis pattern we first check to see if the vector
;; length is at least the required length.

(define-syntax match-gen-vector-ellipsis
  (syntax-rules ()
    ((_ v n ((pat index) ...) p sk fk i)
     (if (vector? v)
       (let ((len (vector-length v)))
         (if (>= len n)
           (match-vector-step v ((pat index) ...)
                              (match-vector-tail v p n len sk fk)
                              fk i)
           fk))
       fk))))

(define-syntax match-vector-tail
  (syntax-rules ()
    ((_ v p n len sk fk i)
     (match-extract-vars p (match-vector-tail-two v p n len sk fk i) i ()))))

(define-syntax match-vector-tail-two
  (syntax-rules ()
    ((_ v p n len (sk ...) fk i ((id id-ls) ...))
     (let loop ((j n) (id-ls '()) ...)
       (if (>= j len)
         (let ((id (reverse id-ls)) ...) (sk ... i))
         (let ((w (vector-ref v j)))
           (match-one w p ((vector-ref v j) (vector-set! v j))
                      (match-drop-ids (loop (+ j 1) (cons id id-ls) ...))
                      fk i)))))))

(define-syntax match-record-refs
  (syntax-rules ()
    ((_ v rec n (p . q) g+s sk fk i)
     (let ((w (slot-ref rec v n)))
       (match-one w p ((slot-ref rec v n) (slot-set! rec v n))
                  (match-record-refs v rec (+ n 1) q g+s sk fk) fk i)))
    ((_ v rec n () g+s (sk ...) fk i)
     (sk ... i))))

(define-syntax match-record-named-refs
  (syntax-rules ()
    ((_ v rec ((f p) . q) g+s sk fk i)
     (let ((w (slot-ref rec v 'f)))
       (match-one w p ((slot-ref rec v 'f) (slot-set! rec v 'f))
                  (match-record-named-refs v rec q g+s sk fk) fk i)))
    ((_ v rec () g+s (sk ...) fk i)
     (sk ... i))))

;; Extract all identifiers in a pattern.  A little more complicated
;; than just looking for symbols, we need to ignore special keywords
;; and non-pattern forms (such as the predicate expression in ?
;; patterns), and also ignore previously bound identifiers.
;;
;; Calls the continuation with all new vars as a list of the form
;; ((orig-var tmp-name) ...), where tmp-name can be used to uniquely
;; pair with the original variable (e.g. it's used in the ellipsis
;; generation for list variables).
;;
;; (match-extract-vars pattern continuation (ids ...) (new-vars ...))

;; Replace '_' with ':_' as the former is forbidden as an auxiliariy
;; keyword in R6RS. (FBE)
(define-syntax match-extract-vars
  (syntax-rules (:_ ___ ..1 *** ? $ struct @ object = quote quasiquote and or not get! set!)
    ((match-extract-vars (? pred . p) . x)
     (match-extract-vars p . x))
    ((match-extract-vars ($ rec . p) . x)
     (match-extract-vars p . x))
    ((match-extract-vars (struct rec . p) . x)
     (match-extract-vars p . x))
    ((match-extract-vars (@ rec (f p) ...) . x)
     (match-extract-vars (p ...) . x))
    ((match-extract-vars (object rec (f p) ...) . x)
     (match-extract-vars (p ...) . x))
    ((match-extract-vars (= proc p) . x)
     (match-extract-vars p . x))
    ((match-extract-vars (quote x) (k ...) i v)
     (k ... v))
    ((match-extract-vars (quasiquote x) k i v)
     (match-extract-quasiquote-vars x k i v (#t)))
    ((match-extract-vars (and . p) . x)
     (match-extract-vars p . x))
    ((match-extract-vars (or . p) . x)
     (match-extract-vars p . x))
    ((match-extract-vars (not . p) . x)
     (match-extract-vars p . x))
    ;; A non-keyword pair, expand the CAR with a continuation to
    ;; expand the CDR.
    ((match-extract-vars (p q . r) k i v)
     (match-check-ellipsis
      q
      (match-extract-vars (p . r) k i v)
      (match-extract-vars p (match-extract-vars-step (q . r) k i v) i ())))
    ((match-extract-vars (p . q) k i v)
     (match-extract-vars p (match-extract-vars-step q k i v) i ()))
    ((match-extract-vars #(p ...) . x)
     (match-extract-vars (p ...) . x))
    ;; Next line: replace '_' with ':_'. (FBE)
    ((match-extract-vars :_ (k ...) i v)    (k ... v))
    ((match-extract-vars ___ (k ...) i v)  (k ... v))
    ((match-extract-vars *** (k ...) i v)  (k ... v))
    ((match-extract-vars ..1 (k ...) i v)  (k ... v))
    ;; This is the main part, the only place where we might add a new
    ;; var if it's an unbound symbol.
    ((match-extract-vars p (k ...) (i ...) v)
     (let-syntax
         ((new-sym?
           (syntax-rules (i ...)
             ((new-sym? p sk fk) sk)
             ((new-sym? any sk fk) fk))))
       (new-sym? random-sym-to-match
                 (k ... ((p p-ls) . v))
                 (k ... v))))
    ))

;; Stepper used in the above so it can expand the CAR and CDR
;; separately.

(define-syntax match-extract-vars-step
  (syntax-rules ()
    ((_ p k i v ((v2 v2-ls) ...))
     (match-extract-vars p k (v2 ... . i) ((v2 v2-ls) ... . v)))
    ))

(define-syntax match-extract-quasiquote-vars
  (syntax-rules (quasiquote unquote unquote-splicing)
    ((match-extract-quasiquote-vars (quasiquote x) k i v d)
     (match-extract-quasiquote-vars x k i v (#t . d)))
    ((match-extract-quasiquote-vars (unquote-splicing x) k i v d)
     (match-extract-quasiquote-vars (unquote x) k i v d))
    ((match-extract-quasiquote-vars (unquote x) k i v (#t))
     (match-extract-vars x k i v))
    ((match-extract-quasiquote-vars (unquote x) k i v (#t . d))
     (match-extract-quasiquote-vars x k i v d))
    ((match-extract-quasiquote-vars (x . y) k i v d)
     (match-extract-quasiquote-vars
      x
      (match-extract-quasiquote-vars-step y k i v d) i () d))
    ((match-extract-quasiquote-vars #(x ...) k i v d)
     (match-extract-quasiquote-vars (x ...) k i v d))
    ((match-extract-quasiquote-vars x (k ...) i v d)
     (k ... v))
    ))

(define-syntax match-extract-quasiquote-vars-step
  (syntax-rules ()
    ((_ x k i v d ((v2 v2-ls) ...))
     (match-extract-quasiquote-vars x k (v2 ... . i) ((v2 v2-ls) ... . v) d))
    ))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Gimme some sugar baby.

;;> Shortcut for \scheme{lambda} + \scheme{match}.  Creates a
;;> procedure of one argument, and matches that argument against each
;;> clause.

(define-syntax match-lambda
  (syntax-rules ()
    ((_ (pattern . body) ...) (lambda (expr) (match expr (pattern . body) ...)))))

;;> Similar to \scheme{match-lambda}.  Creates a procedure of any
;;> number of arguments, and matches the argument list against each
;;> clause.

(define-syntax match-lambda*
  (syntax-rules ()
    ((_ (pattern . body) ...) (lambda expr (match expr (pattern . body) ...)))))

;;> Matches each var to the corresponding expression, and evaluates
;;> the body with all match variables in scope.  Raises an error if
;;> any of the expressions fail to match.  Syntax analogous to named
;;> let can also be used for recursive functions which match on their
;;> arguments as in \scheme{match-lambda*}.

(define-syntax match-let
  (syntax-rules ()
    ((_ ((var value) ...) . body)
     (match-let/helper let () () ((var value) ...) . body))
    ((_ loop ((var init) ...) . body)
     (match-named-let loop () ((var init) ...) . body))))

;;> Similar to \scheme{match-let}, but analogously to \scheme{letrec}
;;> matches and binds the variables with all match variables in scope.

(define-syntax match-letrec
  (syntax-rules ()
    ((_ ((var value) ...) . body)
     (match-let/helper letrec () () ((var value) ...) . body))))

(define-syntax match-let/helper
  (syntax-rules ()
    ((_ let ((var expr) ...) () () . body)
     (let ((var expr) ...) . body))
    ((_ let ((var expr) ...) ((pat tmp) ...) () . body)
     (let ((var expr) ...)
       (match-let* ((pat tmp) ...)
         . body)))
    ((_ let (v ...) (p ...) (((a . b) expr) . rest) . body)
     (match-let/helper
      let (v ... (tmp expr)) (p ... ((a . b) tmp)) rest . body))
    ((_ let (v ...) (p ...) ((#(a ...) expr) . rest) . body)
     (match-let/helper
      let (v ... (tmp expr)) (p ... (#(a ...) tmp)) rest . body))
    ((_ let (v ...) (p ...) ((a expr) . rest) . body)
     (match-let/helper let (v ... (a expr)) (p ...) rest . body))))

(define-syntax match-named-let
  (syntax-rules ()
    ((_ loop ((pat expr var) ...) () . body)
     (let loop ((var expr) ...)
       (match-let ((pat var) ...)
         . body)))
    ((_ loop (v ...) ((pat expr) . rest) . body)
     (match-named-let loop (v ... (pat expr tmp)) rest . body))))

;;> \macro{(match-let* ((var value) ...) body ...)}

;;> Similar to \scheme{match-let}, but analogously to \scheme{let*}
;;> matches and binds the variables in sequence, with preceding match
;;> variables in scope.

(define-syntax match-let*
  (syntax-rules ()
    ((_ () . body)
     (let () . body))
    ((_ ((pat expr) . rest) . body)
     (match expr (pat (match-let* rest . body))))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Otherwise COND-EXPANDed bits.

;; To avoid depending on srfi-0 we comment the following form and copy
;; the generic version below it. (FBE)

;; (cond-expand
;;  (chibi
;;   (define-syntax match-check-ellipsis
;;     (er-macro-transformer
;;      (lambda (expr rename compare)
;;        (if (compare '... (cadr expr))
;;            (car (cddr expr))
;;            (cadr (cddr expr))))))
;;   (define-syntax match-check-identifier
;;     (er-macro-transformer
;;      (lambda (expr rename compare)
;;        (if (identifier? (cadr expr))
;;            (car (cddr expr))
;;            (cadr (cddr expr)))))))

;;  (else
;;   ;; Portable versions
;;   ;;
;;   ;; This *should* work, but doesn't :(
;;   ;;   (define-syntax match-check-ellipsis
;;   ;;     (syntax-rules (...)
;;   ;;       ((_ ... sk fk) sk)
;;   ;;       ((_ x sk fk) fk)))
;;   ;;
;;   ;; This is a little more complicated, and introduces a new let-syntax,
;;   ;; but should work portably in any R[56]RS Scheme.  Taylor Campbell
;;   ;; originally came up with the idea.
;;   (define-syntax match-check-ellipsis
;;     (syntax-rules ()
;;       ;; these two aren't necessary but provide fast-case failures
;;       ((match-check-ellipsis (a . b) success-k failure-k) failure-k)
;;       ((match-check-ellipsis #(a ...) success-k failure-k) failure-k)
;;       ;; matching an atom
;;       ((match-check-ellipsis id success-k failure-k)
;;        (let-syntax ((ellipsis? (syntax-rules ()
;;                                  ;; iff `id' is `...' here then this will
;;                                  ;; match a list of any length
;;                                  ((ellipsis? (foo id) sk fk) sk)
;;                                  ((ellipsis? other sk fk) fk))))
;;          ;; this list of three elements will only match the (foo id) list
;;          ;; above if `id' is `...'
;;          (ellipsis? (a b c) success-k failure-k)))))

;;   ;; This is portable but can be more efficient with non-portable
;;   ;; extensions.  This trick was originally discovered by Oleg Kiselyov.
;;   (define-syntax match-check-identifier
;;     (syntax-rules ()
;;       ;; fast-case failures, lists and vectors are not identifiers
;;       ((_ (x . y) success-k failure-k) failure-k)
;;       ((_ #(x ...) success-k failure-k) failure-k)
;;       ;; x is an atom
;;       ((_ x success-k failure-k)
;;        (let-syntax
;;            ((sym?
;;              (syntax-rules ()
;;                ;; if the symbol `abracadabra' matches x, then x is a
;;                ;; symbol
;;                ((sym? x sk fk) sk)
;;                ;; otherwise x is a non-symbol datum
;;                ((sym? y sk fk) fk))))
;;          (sym? abracadabra success-k failure-k)))))))

;; Portable versions
;;
;; This *should* work, but doesn't :(
;;   (define-syntax match-check-ellipsis
;;     (syntax-rules (...)
;;       ((_ ... sk fk) sk)
;;       ((_ x sk fk) fk)))
;;
;; This is a little more complicated, and introduces a new let-syntax,
;; but should work portably in any R[56]RS Scheme.  Taylor Campbell
;; originally came up with the idea.
(define-syntax match-check-ellipsis
  (syntax-rules ()
    ;; these two aren't necessary but provide fast-case failures
    ((match-check-ellipsis (a . b) success-k failure-k) failure-k)
    ((match-check-ellipsis #(a ...) success-k failure-k) failure-k)
    ;; matching an atom
    ((match-check-ellipsis id success-k failure-k)
     (let-syntax ((ellipsis? (syntax-rules ()
                               ;; iff `id' is `...' here then this will
                               ;; match a list of any length
                               ((ellipsis? (foo id) sk fk) sk)
                               ((ellipsis? other sk fk) fk))))
       ;; this list of three elements will only match the (foo id) list
       ;; above if `id' is `...'
       (ellipsis? (a b c) success-k failure-k)))))

;; This is portable but can be more efficient with non-portable
;; extensions.  This trick was originally discovered by Oleg Kiselyov.
(define-syntax match-check-identifier
  (syntax-rules ()
    ;; fast-case failures, lists and vectors are not identifiers
    ((_ (x . y) success-k failure-k) failure-k)
    ((_ #(x ...) success-k failure-k) failure-k)
    ;; x is an atom
    ((_ x success-k failure-k)
     (let-syntax
         ((sym?
           (syntax-rules ()
             ;; if the symbol `abracadabra' matches x, then x is a
             ;; symbol
             ((sym? x sk fk) sk)
             ;; otherwise x is a non-symbol datum
             ((sym? y sk fk) fk))))
       (sym? abracadabra success-k failure-k)))))
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Changes to matchable.sls.

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






























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































;;; OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
;;; TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
;;; PERFORMANCE OF THIS SOFTWARE.

;; The reader in #!r6rs mode doesn't allow the '..1' identifier.
#!chezscheme
(library (matchable)
  (export 
    match
    match-lambda 
    match-lambda* 
    match-let 
    match-let* 
    match-letrec
    match-named-let
    :_ ___ ..1 *** ? $ struct @ object)
  
  #;(import 
   (rnrs base)
   (rnrs lists)
   (rnrs mutable-pairs)
   (rnrs records syntactic)
   (rnrs records procedural)
   (rnrs records inspection)
   (rnrs syntax-case)
   (only (chezscheme) iota include)
   ;; avoid dependence on chez-srfi (apart for tests)
   ;; (srfi private aux-keywords)
   ;; (srfi private include)
   )
   (import (chezscheme))

  ;; We declare end export the symbols used as auxiliary identifiers
  ;; in 'syntax-rules' to make them work in Chez Scheme's interactive
  ;; environment. (FBE)

  ;; Also we replaced '_' with ':_' as the special identifier matching
  ;; anything and not binding.  This is because R6RS forbids its use
  ;; as an auxiliary literal in a syntax-rules form.
  (define-syntax define-auxiliary-keyword
    (syntax-rules ()
      [(_ name)
       (define-syntax name 
         (lambda (x)
           (syntax-violation #f "misplaced use of auxiliary keyword" x)))]))

  (define-syntax define-auxiliary-keywords
    (syntax-rules ()
      [(_ name* ...)
       (begin (define-auxiliary-keyword name*) ...)]))

  (define-auxiliary-keywords :_ ___ ..1 *** ? $ struct @ object)

  (define-syntax is-a?
    (syntax-rules ()
      ((_ rec rtn)
       (and (record? rec)
            (eq? (record-type-name (record-rtd rec)) (quote rtn))))))

  (define-syntax slot-ref
    (syntax-rules ()
      ((_ rtn rec n)
       (if (number? n)
           ((record-accessor (record-rtd rec) n) rec)
           ;; If it's not a number, then it should be a symbol with
           ;; the name of a field.
           (let* ((rtd (record-rtd rec))
                  (fields (record-type-field-names rtd))
                  (fields-idxs (map (lambda (f i) (cons f i))
                                    (vector->list fields)
                                    (iota (vector-length fields))))
                  (idx (cdr (assv n fields-idxs))))
             ((record-accessor rtd idx) rec))))))

  (define-syntax slot-set!
    (syntax-rules ()
      ((_ rtn rec n)
       (if (number? n)
           ((record-mutator (record-rtd rec) n) rec)
           ;; If it's not a number, then it should be a symbol with
           ;; the name of a field.
           (let* ((rtd (record-rtd rec))
                  (fields (record-type-field-names rtd))
                  (fields-idxs (map (lambda (f i) (cons f i))
                                    (vector->list fields)
                                    (iota (vector-length fields))))
                  (idx (cdr (assv n fields-idxs))))
             ((record-mutator rtd idx) rec))))))
  
  (include "match.scm")





  )





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|

|
|
|
|
|
|
|

|

|
|
|
|

|

|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>

>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
;;; OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
;;; TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
;;; PERFORMANCE OF THIS SOFTWARE.

;; The reader in #!r6rs mode doesn't allow the '..1' identifier.
#!chezscheme
(library (matchable)
	 (export 
	  match
	  match-lambda 
	  match-lambda* 
	  match-let 
	  match-let* 
	  match-letrec
	  match-named-let
	  :_ ___ ..1 *** ? $ struct @ object)
	 
	 #;(import 
	 (rnrs base)
	 (rnrs lists)
	 (rnrs mutable-pairs)
	 (rnrs records syntactic)
	 (rnrs records procedural)
	 (rnrs records inspection)
	 (rnrs syntax-case)
	 (only (chezscheme) iota include)
	 ;; avoid dependence on chez-srfi (apart for tests)
	 ;; (srfi private aux-keywords)
	 ;; (srfi private include)
	 )
	 (import (chezscheme))

	 ;; We declare end export the symbols used as auxiliary identifiers
	 ;; in 'syntax-rules' to make them work in Chez Scheme's interactive
	 ;; environment. (FBE)

	 ;; Also we replaced '_' with ':_' as the special identifier matching
	 ;; anything and not binding.  This is because R6RS forbids its use
	 ;; as an auxiliary literal in a syntax-rules form.
	 (define-syntax define-auxiliary-keyword
	 (syntax-rules ()
	 [(_ name)
	 (define-syntax name 
         (lambda (x)
	 (syntax-violation #f "misplaced use of auxiliary keyword" x)))]))

	 (define-syntax define-auxiliary-keywords
	 (syntax-rules ()
	 [(_ name* ...)
	 (begin (define-auxiliary-keyword name*) ...)]))

	 (define-auxiliary-keywords :_ ___ ..1 *** ? $ struct @ object)

	 (define-syntax is-a?
	 (syntax-rules ()
	 ((_ rec rtn)
	 (and (record? rec)
	 (eq? (record-type-name (record-rtd rec)) (quote rtn))))))

	 (define-syntax slot-ref
	 (syntax-rules ()
	 ((_ rtn rec n)
	 (if (number? n)
	 ((record-accessor (record-rtd rec) n) rec)
	 ;; If it's not a number, then it should be a symbol with
	 ;; the name of a field.
	 (let* ((rtd (record-rtd rec))
	 (fields (record-type-field-names rtd))
	 (fields-idxs (map (lambda (f i) (cons f i))
	 (vector->list fields)
	 (iota (vector-length fields))))
	 (idx (cdr (assv n fields-idxs))))
	 ((record-accessor rtd idx) rec))))))

	 (define-syntax slot-set!
	 (syntax-rules ()
	 ((_ rtn rec n)
	 (if (number? n)
	 ((record-mutator (record-rtd rec) n) rec)
	 ;; If it's not a number, then it should be a symbol with
	 ;; the name of a field.
	 (let* ((rtd (record-rtd rec))
	 (fields (record-type-field-names rtd))
	 (fields-idxs (map (lambda (f i) (cons f i))
	 (vector->list fields)
	 (iota (vector-length fields))))
	 (idx (cdr (assv n fields-idxs))))
	 ((record-mutator rtd idx) rec))))))
	 
;;;; match.scm -- portable hygienic pattern matcher -*- coding: utf-8 -*-
	 ;;
	 ;; This code is written by Alex Shinn and placed in the
	 ;; Public Domain.  All warranties are disclaimed.

	 ;;> \example-import[(srfi 9)]

	 ;;> A portable hygienic pattern matcher.

	 ;;> This is a full superset of the popular \hyperlink[
	 ;;> "http://www.cs.indiana.edu/scheme-repository/code.match.html"]{match}
	 ;;> package by Andrew Wright, written in fully portable \scheme{syntax-rules}
	 ;;> and thus preserving hygiene.

	 ;;> The most notable extensions are the ability to use \emph{non-linear}
	 ;;> patterns - patterns in which the same identifier occurs multiple
	 ;;> times, tail patterns after ellipsis, and the experimental tree patterns.

	 ;;> \section{Patterns}

	 ;;> Patterns are written to look like the printed representation of
	 ;;> the objects they match.  The basic usage is

	 ;;> \scheme{(match expr (pat body ...) ...)}

	 ;;> where the result of \var{expr} is matched against each pattern in
	 ;;> turn, and the corresponding body is evaluated for the first to
	 ;;> succeed.  Thus, a list of three elements matches a list of three
	 ;;> elements.

	 ;;> \example{(let ((ls (list 1 2 3))) (match ls ((1 2 3) #t)))}

	 ;;> If no patterns match an error is signalled.

	 ;;> Identifiers will match anything, and make the corresponding
	 ;;> binding available in the body.

	 ;;> \example{(match (list 1 2 3) ((a b c) b))}

	 ;;> If the same identifier occurs multiple times, the first instance
	 ;;> will match anything, but subsequent instances must match a value
	 ;;> which is \scheme{equal?} to the first.

	 ;;> \example{(match (list 1 2 1) ((a a b) 1) ((a b a) 2))}

	 ;;> The special identifier \scheme{_} matches anything, no matter how
	 ;;> many times it is used, and does not bind the result in the body.

	 ;;> \example{(match (list 1 2 1) ((_ _ b) 1) ((a b a) 2))}

	 ;;> To match a literal identifier (or list or any other literal), use
	 ;;> \scheme{quote}.

	 ;;> \example{(match 'a ('b 1) ('a 2))}

	 ;;> Analogous to its normal usage in scheme, \scheme{quasiquote} can
	 ;;> be used to quote a mostly literally matching object with selected
	 ;;> parts unquoted.

	 ;;> \example|{(match (list 1 2 3) (`(1 ,b ,c) (list b c)))}|

	 ;;> Often you want to match any number of a repeated pattern.  Inside
	 ;;> a list pattern you can append \scheme{...} after an element to
	 ;;> match zero or more of that pattern (like a regexp Kleene star).

	 ;;> \example{(match (list 1 2) ((1 2 3 ...) #t))}
	 ;;> \example{(match (list 1 2 3) ((1 2 3 ...) #t))}
	 ;;> \example{(match (list 1 2 3 3 3) ((1 2 3 ...) #t))}

	 ;;> Pattern variables matched inside the repeated pattern are bound to
	 ;;> a list of each matching instance in the body.

	 ;;> \example{(match (list 1 2) ((a b c ...) c))}
	 ;;> \example{(match (list 1 2 3) ((a b c ...) c))}
	 ;;> \example{(match (list 1 2 3 4 5) ((a b c ...) c))}

	 ;;> More than one \scheme{...} may not be used in the same list, since
	 ;;> this would require exponential backtracking in the general case.
	 ;;> However, \scheme{...} need not be the final element in the list,
	 ;;> and may be succeeded by a fixed number of patterns.

	 ;;> \example{(match (list 1 2 3 4) ((a b c ... d e) c))}
	 ;;> \example{(match (list 1 2 3 4 5) ((a b c ... d e) c))}
	 ;;> \example{(match (list 1 2 3 4 5 6 7) ((a b c ... d e) c))}

	 ;;> \scheme{___} is provided as an alias for \scheme{...} when it is
	 ;;> inconvenient to use the ellipsis (as in a syntax-rules template).

	 ;;> The \scheme{..1} syntax is exactly like the \scheme{...} except
	 ;;> that it matches one or more repetitions (like a regexp "+").

	 ;;> \example{(match (list 1 2) ((a b c ..1) c))}
	 ;;> \example{(match (list 1 2 3) ((a b c ..1) c))}

	 ;;> The boolean operators \scheme{and}, \scheme{or} and \scheme{not}
	 ;;> can be used to group and negate patterns analogously to their
	 ;;> Scheme counterparts.

	 ;;> The \scheme{and} operator ensures that all subpatterns match.
	 ;;> This operator is often used with the idiom \scheme{(and x pat)} to
	 ;;> bind \var{x} to the entire value that matches \var{pat}
	 ;;> (c.f. "as-patterns" in ML or Haskell).  Another common use is in
	 ;;> conjunction with \scheme{not} patterns to match a general case
	 ;;> with certain exceptions.

	 ;;> \example{(match 1 ((and) #t))}
	 ;;> \example{(match 1 ((and x) x))}
	 ;;> \example{(match 1 ((and x 1) x))}

	 ;;> The \scheme{or} operator ensures that at least one subpattern
	 ;;> matches.  If the same identifier occurs in different subpatterns,
	 ;;> it is matched independently.  All identifiers from all subpatterns
	 ;;> are bound if the \scheme{or} operator matches, but the binding is
	 ;;> only defined for identifiers from the subpattern which matched.

	 ;;> \example{(match 1 ((or) #t) (else #f))}
	 ;;> \example{(match 1 ((or x) x))}
	 ;;> \example{(match 1 ((or x 2) x))}

	 ;;> The \scheme{not} operator succeeds if the given pattern doesn't
	 ;;> match.  None of the identifiers used are available in the body.

	 ;;> \example{(match 1 ((not 2) #t))}

	 ;;> The more general operator \scheme{?} can be used to provide a
	 ;;> predicate.  The usage is \scheme{(? predicate pat ...)} where
	 ;;> \var{predicate} is a Scheme expression evaluating to a predicate
	 ;;> called on the value to match, and any optional patterns after the
	 ;;> predicate are then matched as in an \scheme{and} pattern.

	 ;;> \example{(match 1 ((? odd? x) x))}

	 ;;> The field operator \scheme{=} is used to extract an arbitrary
	 ;;> field and match against it.  It is useful for more complex or
	 ;;> conditional destructuring that can't be more directly expressed in
	 ;;> the pattern syntax.  The usage is \scheme{(= field pat)}, where
	 ;;> \var{field} can be any expression, and should result in a
	 ;;> procedure of one argument, which is applied to the value to match
	 ;;> to generate a new value to match against \var{pat}.

	 ;;> Thus the pattern \scheme{(and (= car x) (= cdr y))} is equivalent
	 ;;> to \scheme{(x . y)}, except it will result in an immediate error
	 ;;> if the value isn't a pair.

	 ;;> \example{(match '(1 . 2) ((= car x) x))}
	 ;;> \example{(match 4 ((= square x) x))}

	 ;;> The record operator \scheme{$} is used as a concise way to match
	 ;;> records defined by SRFI-9 (or SRFI-99).  The usage is
	 ;;> \scheme{($ rtd field ...)}, where \var{rtd} should be the record
	 ;;> type descriptor specified as the first argument to
	 ;;> \scheme{define-record-type}, and each \var{field} is a subpattern
	 ;;> matched against the fields of the record in order.  Not all fields
	 ;;> must be present.

	 ;;> \example{
	 ;;> (let ()
	 ;;>   (define-record-type employee
	 ;;>     (make-employee name title)
	 ;;>     employee?
	 ;;>     (name get-name)
	 ;;>     (title get-title))
	 ;;>   (match (make-employee "Bob" "Doctor")
	 ;;>     (($ employee n t) (list t n))))
	 ;;> }

	 ;;> For records with more fields it can be helpful to match them by
	 ;;> name rather than position.  For this you can use the \scheme{@}
	 ;;> operator, originally a Gauche extension:

	 ;;> \example{
	 ;;> (let ()
	 ;;>   (define-record-type employee
	 ;;>     (make-employee name title)
	 ;;>     employee?
	 ;;>     (name get-name)
	 ;;>     (title get-title))
	 ;;>   (match (make-employee "Bob" "Doctor")
	 ;;>     ((@ employee (title t) (name n)) (list t n))))
	 ;;> }

	 ;;> The \scheme{set!} and \scheme{get!} operators are used to bind an
	 ;;> identifier to the setter and getter of a field, respectively.  The
	 ;;> setter is a procedure of one argument, which mutates the field to
	 ;;> that argument.  The getter is a procedure of no arguments which
	 ;;> returns the current value of the field.

	 ;;> \example{(let ((x (cons 1 2))) (match x ((1 . (set! s)) (s 3) x)))}
	 ;;> \example{(match '(1 . 2) ((1 . (get! g)) (g)))}

	 ;;> The new operator \scheme{***} can be used to search a tree for
	 ;;> subpatterns.  A pattern of the form \scheme{(x *** y)} represents
	 ;;> the subpattern \var{y} located somewhere in a tree where the path
	 ;;> from the current object to \var{y} can be seen as a list of the
	 ;;> form \scheme{(x ...)}.  \var{y} can immediately match the current
	 ;;> object in which case the path is the empty list.  In a sense it's
	 ;;> a 2-dimensional version of the \scheme{...} pattern.

	 ;;> As a common case the pattern \scheme{(_ *** y)} can be used to
	 ;;> search for \var{y} anywhere in a tree, regardless of the path
	 ;;> used.

	 ;;> \example{(match '(a (a (a b))) ((x *** 'b) x))}
	 ;;> \example{(match '(a (b) (c (d e) (f g))) ((x *** 'g) x))}

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	 ;; Notes

	 ;; The implementation is a simple generative pattern matcher - each
	 ;; pattern is expanded into the required tests, calling a failure
	 ;; continuation if the tests fail.  This makes the logic easy to
	 ;; follow and extend, but produces sub-optimal code in cases where you
	 ;; have many similar clauses due to repeating the same tests.
	 ;; Nonetheless a smart compiler should be able to remove the redundant
	 ;; tests.  For MATCH-LET and DESTRUCTURING-BIND type uses there is no
	 ;; performance hit.

	 ;; The original version was written on 2006/11/29 and described in the
	 ;; following Usenet post:
	 ;;   http://groups.google.com/group/comp.lang.scheme/msg/0941234de7112ffd
	 ;; and is still available at
	 ;;   http://synthcode.com/scheme/match-simple.scm
	 ;; It's just 80 lines for the core MATCH, and an extra 40 lines for
	 ;; MATCH-LET, MATCH-LAMBDA and other syntactic sugar.
	 ;;
	 ;; A variant of this file which uses COND-EXPAND in a few places for
	 ;; performance can be found at
	 ;;   http://synthcode.com/scheme/match-cond-expand.scm
	 ;;
	 ;; 2016/03/06 - fixing named match-let (thanks to Stefan Israelsson Tampe)
	 ;; 2015/05/09 - fixing bug in var extraction of quasiquote patterns
	 ;; 2014/11/24 - adding Gauche's `@' pattern for named record field matching
	 ;; 2012/12/26 - wrapping match-let&co body in lexical closure
	 ;; 2012/11/28 - fixing typo s/vetor/vector in largely unused set! code
	 ;; 2012/05/23 - fixing combinatorial explosion of code in certain or patterns
	 ;; 2011/09/25 - fixing bug when directly matching an identifier repeated in
	 ;;              the pattern (thanks to Stefan Israelsson Tampe)
	 ;; 2011/01/27 - fixing bug when matching tail patterns against improper lists
	 ;; 2010/09/26 - adding `..1' patterns (thanks to Ludovic Courtès)
	 ;; 2010/09/07 - fixing identifier extraction in some `...' and `***' patterns
	 ;; 2009/11/25 - adding `***' tree search patterns
	 ;; 2008/03/20 - fixing bug where (a ...) matched non-lists
	 ;; 2008/03/15 - removing redundant check in vector patterns
	 ;; 2008/03/06 - you can use `...' portably now (thanks to Taylor Campbell)
	 ;; 2007/09/04 - fixing quasiquote patterns
	 ;; 2007/07/21 - allowing ellipsis patterns in non-final list positions
	 ;; 2007/04/10 - fixing potential hygiene issue in match-check-ellipsis
	 ;;              (thanks to Taylor Campbell)
	 ;; 2007/04/08 - clean up, commenting
	 ;; 2006/12/24 - bugfixes
	 ;; 2006/12/01 - non-linear patterns, shared variables in OR, get!/set!

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	 ;; force compile-time syntax errors with useful messages

	 (define-syntax match-syntax-error
	 (syntax-rules ()
	 ((_) (match-syntax-error "invalid match-syntax-error usage"))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

	 ;;> \section{Syntax}

	 ;;> \macro{(match expr (pattern . body) ...)\br{}
	 ;;> (match expr (pattern (=> failure) . body) ...)}

	 ;;> The result of \var{expr} is matched against each \var{pattern} in
	 ;;> turn, according to the pattern rules described in the previous
	 ;;> section, until the the first \var{pattern} matches.  When a match is
	 ;;> found, the corresponding \var{body}s are evaluated in order,
	 ;;> and the result of the last expression is returned as the result
	 ;;> of the entire \scheme{match}.  If a \var{failure} is provided,
	 ;;> then it is bound to a procedure of no arguments which continues,
	 ;;> processing at the next \var{pattern}.  If no \var{pattern} matches,
	 ;;> an error is signalled.

	 ;; The basic interface.  MATCH just performs some basic syntax
	 ;; validation, binds the match expression to a temporary variable `v',
	 ;; and passes it on to MATCH-NEXT.  It's a constant throughout the
	 ;; code below that the binding `v' is a direct variable reference, not
	 ;; an expression.

	 (define-syntax match
	 (syntax-rules ()
	 ((match)
	 (match-syntax-error "missing match expression"))
	 ((match atom)
	 (match-syntax-error "no match clauses"))
	 ((match (app ...) (pat . body) ...)
	 (let ((v (app ...)))
	 (match-next v ((app ...) (set! (app ...))) (pat . body) ...)))
	 ((match #(vec ...) (pat . body) ...)
	 (let ((v #(vec ...)))
	 (match-next v (v (set! v)) (pat . body) ...)))
	 ((match atom (pat . body) ...)
	 (let ((v atom))
	 (match-next v (atom (set! atom)) (pat . body) ...)))
	 ))

	 ;; MATCH-NEXT passes each clause to MATCH-ONE in turn with its failure
	 ;; thunk, which is expanded by recursing MATCH-NEXT on the remaining
	 ;; clauses.  `g+s' is a list of two elements, the get! and set!
	 ;; expressions respectively.

	 (define-syntax match-next
	 (syntax-rules (=>)
	 ;; no more clauses, the match failed
	 ((match-next v g+s)
	 (error 'match "no matching pattern"))
	 ;; named failure continuation
	 ((match-next v g+s (pat (=> failure) . body) . rest)
	 (let ((failure (lambda () (match-next v g+s . rest))))
	 ;; match-one analyzes the pattern for us
	 (match-one v pat g+s (match-drop-ids (begin . body)) (failure) ())))
	 ;; anonymous failure continuation, give it a dummy name
	 ((match-next v g+s (pat . body) . rest)
	 (match-next v g+s (pat (=> failure) . body) . rest))))

	 ;; MATCH-ONE first checks for ellipsis patterns, otherwise passes on to
	 ;; MATCH-TWO.

	 (define-syntax match-one
	 (syntax-rules ()
	 ;; If it's a list of two or more values, check to see if the
	 ;; second one is an ellipsis and handle accordingly, otherwise go
	 ;; to MATCH-TWO.
	 ((match-one v (p q . r) g+s sk fk i)
	 (match-check-ellipsis
	 q
	 (match-extract-vars p (match-gen-ellipsis v p r  g+s sk fk i) i ())
	 (match-two v (p q . r) g+s sk fk i)))
	 ;; Go directly to MATCH-TWO.
	 ((match-one . x)
	 (match-two . x))))

	 ;; This is the guts of the pattern matcher.  We are passed a lot of
	 ;; information in the form:
	 ;;
	 ;;   (match-two var pattern getter setter success-k fail-k (ids ...))
	 ;;
	 ;; usually abbreviated
	 ;;
	 ;;   (match-two v p g+s sk fk i)
	 ;;
	 ;; where VAR is the symbol name of the current variable we are
	 ;; matching, PATTERN is the current pattern, getter and setter are the
	 ;; corresponding accessors (e.g. CAR and SET-CAR! of the pair holding
	 ;; VAR), SUCCESS-K is the success continuation, FAIL-K is the failure
	 ;; continuation (which is just a thunk call and is thus safe to expand
	 ;; multiple times) and IDS are the list of identifiers bound in the
	 ;; pattern so far.

	 ;; Replace '_' with ':_' as the former is forbidden as an auxiliariy
	 ;; keyword in R6RS. (FBE)
	 (define-syntax match-two
	 (syntax-rules (:_ ___ ..1 *** quote quasiquote ? $ struct @ object = and or not set! get!)
	 ((match-two v () g+s (sk ...) fk i)
	 (if (null? v) (sk ... i) fk))
	 ((match-two v (quote p) g+s (sk ...) fk i)
	 (if (equal? v 'p) (sk ... i) fk))
	 ((match-two v (quasiquote p) . x)
	 (match-quasiquote v p . x))
	 ((match-two v (and) g+s (sk ...) fk i) (sk ... i))
	 ((match-two v (and p q ...) g+s sk fk i)
	 (match-one v p g+s (match-one v (and q ...) g+s sk fk) fk i))
	 ((match-two v (or) g+s sk fk i) fk)
	 ((match-two v (or p) . x)
	 (match-one v p . x))
	 ((match-two v (or p ...) g+s sk fk i)
	 (match-extract-vars (or p ...) (match-gen-or v (p ...) g+s sk fk i) i ()))
	 ((match-two v (not p) g+s (sk ...) fk i)
	 (match-one v p g+s (match-drop-ids fk) (sk ... i) i))
	 ((match-two v (get! getter) (g s) (sk ...) fk i)
	 (let ((getter (lambda () g))) (sk ... i)))
	 ((match-two v (set! setter) (g (s ...)) (sk ...) fk i)
	 (let ((setter (lambda (x) (s ... x)))) (sk ... i)))
	 ((match-two v (? pred . p) g+s sk fk i)
	 (if (pred v) (match-one v (and . p) g+s sk fk i) fk))
	 ((match-two v (= proc p) . x)
	 (let ((w (proc v))) (match-one w p . x)))
	 ((match-two v (p ___ . r) g+s sk fk i)
	 (match-extract-vars p (match-gen-ellipsis v p r g+s sk fk i) i ()))
	 ((match-two v (p) g+s sk fk i)
	 (if (and (pair? v) (null? (cdr v)))
         (let ((w (car v)))
	 (match-one w p ((car v) (set-car! v)) sk fk i))
         fk))
	 ((match-two v (p *** q) g+s sk fk i)
	 (match-extract-vars p (match-gen-search v p q g+s sk fk i) i ()))
	 ((match-two v (p *** . q) g+s sk fk i)
	 (match-syntax-error "invalid use of ***" (p *** . q)))
	 ((match-two v (p ..1) g+s sk fk i)
	 (if (pair? v)
         (match-one v (p ___) g+s sk fk i)
         fk))
	 ((match-two v ($ rec p ...) g+s sk fk i)
	 (if (is-a? v rec)
         (match-record-refs v rec 0 (p ...) g+s sk fk i)
         fk))
	 ((match-two v (struct rec p ...) g+s sk fk i)
	 (if (is-a? v rec)
         (match-record-refs v rec 0 (p ...) g+s sk fk i)
         fk))
	 ((match-two v (@ rec p ...) g+s sk fk i)
	 (if (is-a? v rec)
         (match-record-named-refs v rec (p ...) g+s sk fk i)
         fk))
	 ((match-two v (object rec p ...) g+s sk fk i)
	 (if (is-a? v rec)
         (match-record-named-refs v rec (p ...) g+s sk fk i)
         fk))
	 ((match-two v (p . q) g+s sk fk i)
	 (if (pair? v)
         (let ((w (car v)) (x (cdr v)))
	 (match-one w p ((car v) (set-car! v))
	 (match-one x q ((cdr v) (set-cdr! v)) sk fk)
	 fk
	 i))
         fk))
	 ((match-two v #(p ...) g+s . x)
	 (match-vector v 0 () (p ...) . x))
	 ;; Next line: replace '_' with ':_'. (FBE)
	 ((match-two v :_ g+s (sk ...) fk i) (sk ... i))
	 ;; Not a pair or vector or special literal, test to see if it's a
	 ;; new symbol, in which case we just bind it, or if it's an
	 ;; already bound symbol or some other literal, in which case we
	 ;; compare it with EQUAL?.
	 ((match-two v x g+s (sk ...) fk (id ...))
	 (let-syntax
         ((new-sym?
	 (syntax-rules (id ...)
	 ((new-sym? x sk2 fk2) sk2)
	 ((new-sym? y sk2 fk2) fk2))))
	 (new-sym? random-sym-to-match
	 (let ((x v)) (sk ... (id ... x)))
	 (if (equal? v x) (sk ... (id ...)) fk))))
	 ))

	 ;; QUASIQUOTE patterns

	 (define-syntax match-quasiquote
	 (syntax-rules (unquote unquote-splicing quasiquote)
	 ((_ v (unquote p) g+s sk fk i)
	 (match-one v p g+s sk fk i))
	 ((_ v ((unquote-splicing p) . rest) g+s sk fk i)
	 (if (pair? v)
	 (match-one v
	 (p . tmp)
	 (match-quasiquote tmp rest g+s sk fk)
	 fk
	 i)
	 fk))
	 ((_ v (quasiquote p) g+s sk fk i . depth)
	 (match-quasiquote v p g+s sk fk i #f . depth))
	 ((_ v (unquote p) g+s sk fk i x . depth)
	 (match-quasiquote v p g+s sk fk i . depth))
	 ((_ v (unquote-splicing p) g+s sk fk i x . depth)
	 (match-quasiquote v p g+s sk fk i . depth))
	 ((_ v (p . q) g+s sk fk i . depth)
	 (if (pair? v)
	 (let ((w (car v)) (x (cdr v)))
         (match-quasiquote
	 w p g+s
	 (match-quasiquote-step x q g+s sk fk depth)
	 fk i . depth))
	 fk))
	 ((_ v #(elt ...) g+s sk fk i . depth)
	 (if (vector? v)
	 (let ((ls (vector->list v)))
         (match-quasiquote ls (elt ...) g+s sk fk i . depth))
	 fk))
	 ((_ v x g+s sk fk i . depth)
	 (match-one v 'x g+s sk fk i))))

	 (define-syntax match-quasiquote-step
	 (syntax-rules ()
	 ((match-quasiquote-step x q g+s sk fk depth i)
	 (match-quasiquote x q g+s sk fk i . depth))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	 ;; Utilities

	 ;; Takes two values and just expands into the first.
	 (define-syntax match-drop-ids
	 (syntax-rules ()
	 ((_ expr ids ...) expr)))

	 (define-syntax match-tuck-ids
	 (syntax-rules ()
	 ((_ (letish args (expr ...)) ids ...)
	 (letish args (expr ... ids ...)))))

	 (define-syntax match-drop-first-arg
	 (syntax-rules ()
	 ((_ arg expr) expr)))

	 ;; To expand an OR group we try each clause in succession, passing the
	 ;; first that succeeds to the success continuation.  On failure for
	 ;; any clause, we just try the next clause, finally resorting to the
	 ;; failure continuation fk if all clauses fail.  The only trick is
	 ;; that we want to unify the identifiers, so that the success
	 ;; continuation can refer to a variable from any of the OR clauses.

	 (define-syntax match-gen-or
	 (syntax-rules ()
	 ((_ v p g+s (sk ...) fk (i ...) ((id id-ls) ...))
	 (let ((sk2 (lambda (id ...) (sk ... (i ... id ...)))))
	 (match-gen-or-step v p g+s (match-drop-ids (sk2 id ...)) fk (i ...))))))

	 (define-syntax match-gen-or-step
	 (syntax-rules ()
	 ((_ v () g+s sk fk . x)
	 ;; no OR clauses, call the failure continuation
	 fk)
	 ((_ v (p) . x)
	 ;; last (or only) OR clause, just expand normally
	 (match-one v p . x))
	 ((_ v (p . q) g+s sk fk i)
	 ;; match one and try the remaining on failure
	 (let ((fk2 (lambda () (match-gen-or-step v q g+s sk fk i))))
	 (match-one v p g+s sk (fk2) i)))
	 ))

	 ;; We match a pattern (p ...) by matching the pattern p in a loop on
	 ;; each element of the variable, accumulating the bound ids into lists.

	 ;; Look at the body of the simple case - it's just a named let loop,
	 ;; matching each element in turn to the same pattern.  The only trick
	 ;; is that we want to keep track of the lists of each extracted id, so
	 ;; when the loop recurses we cons the ids onto their respective list
	 ;; variables, and on success we bind the ids (what the user input and
	 ;; expects to see in the success body) to the reversed accumulated
	 ;; list IDs.

	 (define-syntax match-gen-ellipsis
	 (syntax-rules ()
	 ((_ v p () g+s (sk ...) fk i ((id id-ls) ...))
	 (match-check-identifier p
	 ;; simplest case equivalent to (p ...), just bind the list
	 (let ((p v))
         (if (list? p)
	 (sk ... i)
	 fk))
	 ;; simple case, match all elements of the list
	 (let loop ((ls v) (id-ls '()) ...)
         (cond
	 ((null? ls)
	 (let ((id (reverse id-ls)) ...) (sk ... i)))
	 ((pair? ls)
	 (let ((w (car ls)))
	 (match-one w p ((car ls) (set-car! ls))
	 (match-drop-ids (loop (cdr ls) (cons id id-ls) ...))
	 fk i)))
	 (else
	 fk)))))
	 ((_ v p r g+s (sk ...) fk i ((id id-ls) ...))
	 ;; general case, trailing patterns to match, keep track of the
	 ;; remaining list length so we don't need any backtracking
	 (match-verify-no-ellipsis
	 r
	 (let* ((tail-len (length 'r))
	 (ls v)
	 (len (and (list? ls) (length ls))))
	 (if (or (not len) (< len tail-len))
	 fk
	 (let loop ((ls ls) (n len) (id-ls '()) ...)
	 (cond
	 ((= n tail-len)
	 (let ((id (reverse id-ls)) ...)
	 (match-one ls r (#f #f) (sk ...) fk i)))
	 ((pair? ls)
	 (let ((w (car ls)))
	 (match-one w p ((car ls) (set-car! ls))
	 (match-drop-ids
	 (loop (cdr ls) (- n 1) (cons id id-ls) ...))
	 fk
	 i)))
	 (else
	 fk)))))))))

	 ;; This is just a safety check.  Although unlike syntax-rules we allow
	 ;; trailing patterns after an ellipsis, we explicitly disable multiple
	 ;; ellipsis at the same level.  This is because in the general case
	 ;; such patterns are exponential in the number of ellipsis, and we
	 ;; don't want to make it easy to construct very expensive operations
	 ;; with simple looking patterns.  For example, it would be O(n^2) for
	 ;; patterns like (a ... b ...) because we must consider every trailing
	 ;; element for every possible break for the leading "a ...".

	 (define-syntax match-verify-no-ellipsis
	 (syntax-rules ()
	 ((_ (x . y) sk)
	 (match-check-ellipsis
	 x
	 (match-syntax-error
	 "multiple ellipsis patterns not allowed at same level")
	 (match-verify-no-ellipsis y sk)))
	 ((_ () sk)
	 sk)
	 ((_ x sk)
	 (match-syntax-error "dotted tail not allowed after ellipsis" x))))

	 ;; To implement the tree search, we use two recursive procedures.  TRY
	 ;; attempts to match Y once, and on success it calls the normal SK on
	 ;; the accumulated list ids as in MATCH-GEN-ELLIPSIS.  On failure, we
	 ;; call NEXT which first checks if the current value is a list
	 ;; beginning with X, then calls TRY on each remaining element of the
	 ;; list.  Since TRY will recursively call NEXT again on failure, this
	 ;; effects a full depth-first search.
	 ;;
	 ;; The failure continuation throughout is a jump to the next step in
	 ;; the tree search, initialized with the original failure continuation
	 ;; FK.

	 (define-syntax match-gen-search
	 (syntax-rules ()
	 ((match-gen-search v p q g+s sk fk i ((id id-ls) ...))
	 (letrec ((try (lambda (w fail id-ls ...)
	 (match-one w q g+s
	 (match-tuck-ids
	 (let ((id (reverse id-ls)) ...)
	 sk))
	 (next w fail id-ls ...) i)))
	 (next (lambda (w fail id-ls ...)
	 (if (not (pair? w))
	 (fail)
	 (let ((u (car w)))
	 (match-one
	 u p ((car w) (set-car! w))
	 (match-drop-ids
	 ;; accumulate the head variables from
	 ;; the p pattern, and loop over the tail
	 (let ((id-ls (cons id id-ls)) ...)
	 (let lp ((ls (cdr w)))
	 (if (pair? ls)
	 (try (car ls)
	 (lambda () (lp (cdr ls)))
	 id-ls ...)
	 (fail)))))
	 (fail) i))))))
	 ;; the initial id-ls binding here is a dummy to get the right
	 ;; number of '()s
	 (let ((id-ls '()) ...)
         (try v (lambda () fk) id-ls ...))))))

	 ;; Vector patterns are just more of the same, with the slight
	 ;; exception that we pass around the current vector index being
	 ;; matched.

	 (define-syntax match-vector
	 (syntax-rules (___)
	 ((_ v n pats (p q) . x)
	 (match-check-ellipsis q
	 (match-gen-vector-ellipsis v n pats p . x)
	 (match-vector-two v n pats (p q) . x)))
	 ((_ v n pats (p ___) sk fk i)
	 (match-gen-vector-ellipsis v n pats p sk fk i))
	 ((_ . x)
	 (match-vector-two . x))))

	 ;; Check the exact vector length, then check each element in turn.

	 (define-syntax match-vector-two
	 (syntax-rules ()
	 ((_ v n ((pat index) ...) () sk fk i)
	 (if (vector? v)
         (let ((len (vector-length v)))
	 (if (= len n)
	 (match-vector-step v ((pat index) ...) sk fk i)
	 fk))
         fk))
	 ((_ v n (pats ...) (p . q) . x)
	 (match-vector v (+ n 1) (pats ... (p n)) q . x))))

	 (define-syntax match-vector-step
	 (syntax-rules ()
	 ((_ v () (sk ...) fk i) (sk ... i))
	 ((_ v ((pat index) . rest) sk fk i)
	 (let ((w (vector-ref v index)))
	 (match-one w pat ((vector-ref v index) (vector-set! v index))
	 (match-vector-step v rest sk fk)
	 fk i)))))

	 ;; With a vector ellipsis pattern we first check to see if the vector
	 ;; length is at least the required length.

	 (define-syntax match-gen-vector-ellipsis
	 (syntax-rules ()
	 ((_ v n ((pat index) ...) p sk fk i)
	 (if (vector? v)
	 (let ((len (vector-length v)))
         (if (>= len n)
	 (match-vector-step v ((pat index) ...)
	 (match-vector-tail v p n len sk fk)
	 fk i)
	 fk))
	 fk))))

	 (define-syntax match-vector-tail
	 (syntax-rules ()
	 ((_ v p n len sk fk i)
	 (match-extract-vars p (match-vector-tail-two v p n len sk fk i) i ()))))

	 (define-syntax match-vector-tail-two
	 (syntax-rules ()
	 ((_ v p n len (sk ...) fk i ((id id-ls) ...))
	 (let loop ((j n) (id-ls '()) ...)
	 (if (>= j len)
         (let ((id (reverse id-ls)) ...) (sk ... i))
         (let ((w (vector-ref v j)))
	 (match-one w p ((vector-ref v j) (vector-set! v j))
	 (match-drop-ids (loop (+ j 1) (cons id id-ls) ...))
	 fk i)))))))

	 (define-syntax match-record-refs
	 (syntax-rules ()
	 ((_ v rec n (p . q) g+s sk fk i)
	 (let ((w (slot-ref rec v n)))
	 (match-one w p ((slot-ref rec v n) (slot-set! rec v n))
	 (match-record-refs v rec (+ n 1) q g+s sk fk) fk i)))
	 ((_ v rec n () g+s (sk ...) fk i)
	 (sk ... i))))

	 (define-syntax match-record-named-refs
	 (syntax-rules ()
	 ((_ v rec ((f p) . q) g+s sk fk i)
	 (let ((w (slot-ref rec v 'f)))
	 (match-one w p ((slot-ref rec v 'f) (slot-set! rec v 'f))
	 (match-record-named-refs v rec q g+s sk fk) fk i)))
	 ((_ v rec () g+s (sk ...) fk i)
	 (sk ... i))))

	 ;; Extract all identifiers in a pattern.  A little more complicated
	 ;; than just looking for symbols, we need to ignore special keywords
	 ;; and non-pattern forms (such as the predicate expression in ?
	 ;; patterns), and also ignore previously bound identifiers.
	 ;;
	 ;; Calls the continuation with all new vars as a list of the form
	 ;; ((orig-var tmp-name) ...), where tmp-name can be used to uniquely
	 ;; pair with the original variable (e.g. it's used in the ellipsis
	 ;; generation for list variables).
	 ;;
	 ;; (match-extract-vars pattern continuation (ids ...) (new-vars ...))

	 ;; Replace '_' with ':_' as the former is forbidden as an auxiliariy
	 ;; keyword in R6RS. (FBE)
	 (define-syntax match-extract-vars
	 (syntax-rules (:_ ___ ..1 *** ? $ struct @ object = quote quasiquote and or not get! set!)
	 ((match-extract-vars (? pred . p) . x)
	 (match-extract-vars p . x))
	 ((match-extract-vars ($ rec . p) . x)
	 (match-extract-vars p . x))
	 ((match-extract-vars (struct rec . p) . x)
	 (match-extract-vars p . x))
	 ((match-extract-vars (@ rec (f p) ...) . x)
	 (match-extract-vars (p ...) . x))
	 ((match-extract-vars (object rec (f p) ...) . x)
	 (match-extract-vars (p ...) . x))
	 ((match-extract-vars (= proc p) . x)
	 (match-extract-vars p . x))
	 ((match-extract-vars (quote x) (k ...) i v)
	 (k ... v))
	 ((match-extract-vars (quasiquote x) k i v)
	 (match-extract-quasiquote-vars x k i v (#t)))
	 ((match-extract-vars (and . p) . x)
	 (match-extract-vars p . x))
	 ((match-extract-vars (or . p) . x)
	 (match-extract-vars p . x))
	 ((match-extract-vars (not . p) . x)
	 (match-extract-vars p . x))
	 ;; A non-keyword pair, expand the CAR with a continuation to
	 ;; expand the CDR.
	 ((match-extract-vars (p q . r) k i v)
	 (match-check-ellipsis
	 q
	 (match-extract-vars (p . r) k i v)
	 (match-extract-vars p (match-extract-vars-step (q . r) k i v) i ())))
	 ((match-extract-vars (p . q) k i v)
	 (match-extract-vars p (match-extract-vars-step q k i v) i ()))
	 ((match-extract-vars #(p ...) . x)
	 (match-extract-vars (p ...) . x))
	 ;; Next line: replace '_' with ':_'. (FBE)
	 ((match-extract-vars :_ (k ...) i v)    (k ... v))
	 ((match-extract-vars ___ (k ...) i v)  (k ... v))
	 ((match-extract-vars *** (k ...) i v)  (k ... v))
	 ((match-extract-vars ..1 (k ...) i v)  (k ... v))
	 ;; This is the main part, the only place where we might add a new
	 ;; var if it's an unbound symbol.
	 ((match-extract-vars p (k ...) (i ...) v)
	 (let-syntax
         ((new-sym?
	 (syntax-rules (i ...)
	 ((new-sym? p sk fk) sk)
	 ((new-sym? any sk fk) fk))))
	 (new-sym? random-sym-to-match
	 (k ... ((p p-ls) . v))
	 (k ... v))))
	 ))

	 ;; Stepper used in the above so it can expand the CAR and CDR
	 ;; separately.

	 (define-syntax match-extract-vars-step
	 (syntax-rules ()
	 ((_ p k i v ((v2 v2-ls) ...))
	 (match-extract-vars p k (v2 ... . i) ((v2 v2-ls) ... . v)))
	 ))

	 (define-syntax match-extract-quasiquote-vars
	 (syntax-rules (quasiquote unquote unquote-splicing)
	 ((match-extract-quasiquote-vars (quasiquote x) k i v d)
	 (match-extract-quasiquote-vars x k i v (#t . d)))
	 ((match-extract-quasiquote-vars (unquote-splicing x) k i v d)
	 (match-extract-quasiquote-vars (unquote x) k i v d))
	 ((match-extract-quasiquote-vars (unquote x) k i v (#t))
	 (match-extract-vars x k i v))
	 ((match-extract-quasiquote-vars (unquote x) k i v (#t . d))
	 (match-extract-quasiquote-vars x k i v d))
	 ((match-extract-quasiquote-vars (x . y) k i v d)
	 (match-extract-quasiquote-vars
	 x
	 (match-extract-quasiquote-vars-step y k i v d) i () d))
	 ((match-extract-quasiquote-vars #(x ...) k i v d)
	 (match-extract-quasiquote-vars (x ...) k i v d))
	 ((match-extract-quasiquote-vars x (k ...) i v d)
	 (k ... v))
	 ))

	 (define-syntax match-extract-quasiquote-vars-step
	 (syntax-rules ()
	 ((_ x k i v d ((v2 v2-ls) ...))
	 (match-extract-quasiquote-vars x k (v2 ... . i) ((v2 v2-ls) ... . v) d))
	 ))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	 ;; Gimme some sugar baby.

	 ;;> Shortcut for \scheme{lambda} + \scheme{match}.  Creates a
	 ;;> procedure of one argument, and matches that argument against each
	 ;;> clause.

	 (define-syntax match-lambda
	 (syntax-rules ()
	 ((_ (pattern . body) ...) (lambda (expr) (match expr (pattern . body) ...)))))

	 ;;> Similar to \scheme{match-lambda}.  Creates a procedure of any
	 ;;> number of arguments, and matches the argument list against each
	 ;;> clause.

	 (define-syntax match-lambda*
	 (syntax-rules ()
	 ((_ (pattern . body) ...) (lambda expr (match expr (pattern . body) ...)))))

	 ;;> Matches each var to the corresponding expression, and evaluates
	 ;;> the body with all match variables in scope.  Raises an error if
	 ;;> any of the expressions fail to match.  Syntax analogous to named
	 ;;> let can also be used for recursive functions which match on their
	 ;;> arguments as in \scheme{match-lambda*}.

	 (define-syntax match-let
	 (syntax-rules ()
	 ((_ ((var value) ...) . body)
	 (match-let/helper let () () ((var value) ...) . body))
	 ((_ loop ((var init) ...) . body)
	 (match-named-let loop () ((var init) ...) . body))))

	 ;;> Similar to \scheme{match-let}, but analogously to \scheme{letrec}
	 ;;> matches and binds the variables with all match variables in scope.

	 (define-syntax match-letrec
	 (syntax-rules ()
	 ((_ ((var value) ...) . body)
	 (match-let/helper letrec () () ((var value) ...) . body))))

	 (define-syntax match-let/helper
	 (syntax-rules ()
	 ((_ let ((var expr) ...) () () . body)
	 (let ((var expr) ...) . body))
	 ((_ let ((var expr) ...) ((pat tmp) ...) () . body)
	 (let ((var expr) ...)
	 (match-let* ((pat tmp) ...)
         . body)))
	 ((_ let (v ...) (p ...) (((a . b) expr) . rest) . body)
	 (match-let/helper
	 let (v ... (tmp expr)) (p ... ((a . b) tmp)) rest . body))
	 ((_ let (v ...) (p ...) ((#(a ...) expr) . rest) . body)
	 (match-let/helper
	 let (v ... (tmp expr)) (p ... (#(a ...) tmp)) rest . body))
	 ((_ let (v ...) (p ...) ((a expr) . rest) . body)
	 (match-let/helper let (v ... (a expr)) (p ...) rest . body))))

	 (define-syntax match-named-let
	 (syntax-rules ()
	 ((_ loop ((pat expr var) ...) () . body)
	 (let loop ((var expr) ...)
	 (match-let ((pat var) ...)
         . body)))
	 ((_ loop (v ...) ((pat expr) . rest) . body)
	 (match-named-let loop (v ... (pat expr tmp)) rest . body))))

	 ;;> \macro{(match-let* ((var value) ...) body ...)}

	 ;;> Similar to \scheme{match-let}, but analogously to \scheme{let*}
	 ;;> matches and binds the variables in sequence, with preceding match
	 ;;> variables in scope.

	 (define-syntax match-let*
	 (syntax-rules ()
	 ((_ () . body)
	 (let () . body))
	 ((_ ((pat expr) . rest) . body)
	 (match expr (pat (match-let* rest . body))))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	 ;; Otherwise COND-EXPANDed bits.

	 ;; To avoid depending on srfi-0 we comment the following form and copy
	 ;; the generic version below it. (FBE)

	 ;; (cond-expand
	 ;;  (chibi
	 ;;   (define-syntax match-check-ellipsis
	 ;;     (er-macro-transformer
	 ;;      (lambda (expr rename compare)
	 ;;        (if (compare '... (cadr expr))
	 ;;            (car (cddr expr))
	 ;;            (cadr (cddr expr))))))
	 ;;   (define-syntax match-check-identifier
	 ;;     (er-macro-transformer
	 ;;      (lambda (expr rename compare)
	 ;;        (if (identifier? (cadr expr))
	 ;;            (car (cddr expr))
	 ;;            (cadr (cddr expr)))))))

	 ;;  (else
	 ;;   ;; Portable versions
	 ;;   ;;
	 ;;   ;; This *should* work, but doesn't :(
	 ;;   ;;   (define-syntax match-check-ellipsis
	 ;;   ;;     (syntax-rules (...)
	 ;;   ;;       ((_ ... sk fk) sk)
	 ;;   ;;       ((_ x sk fk) fk)))
	 ;;   ;;
	 ;;   ;; This is a little more complicated, and introduces a new let-syntax,
	 ;;   ;; but should work portably in any R[56]RS Scheme.  Taylor Campbell
	 ;;   ;; originally came up with the idea.
	 ;;   (define-syntax match-check-ellipsis
	 ;;     (syntax-rules ()
	 ;;       ;; these two aren't necessary but provide fast-case failures
	 ;;       ((match-check-ellipsis (a . b) success-k failure-k) failure-k)
	 ;;       ((match-check-ellipsis #(a ...) success-k failure-k) failure-k)
	 ;;       ;; matching an atom
	 ;;       ((match-check-ellipsis id success-k failure-k)
	 ;;        (let-syntax ((ellipsis? (syntax-rules ()
	 ;;                                  ;; iff `id' is `...' here then this will
	 ;;                                  ;; match a list of any length
	 ;;                                  ((ellipsis? (foo id) sk fk) sk)
	 ;;                                  ((ellipsis? other sk fk) fk))))
	 ;;          ;; this list of three elements will only match the (foo id) list
	 ;;          ;; above if `id' is `...'
	 ;;          (ellipsis? (a b c) success-k failure-k)))))

	 ;;   ;; This is portable but can be more efficient with non-portable
	 ;;   ;; extensions.  This trick was originally discovered by Oleg Kiselyov.
	 ;;   (define-syntax match-check-identifier
	 ;;     (syntax-rules ()
	 ;;       ;; fast-case failures, lists and vectors are not identifiers
	 ;;       ((_ (x . y) success-k failure-k) failure-k)
	 ;;       ((_ #(x ...) success-k failure-k) failure-k)
	 ;;       ;; x is an atom
	 ;;       ((_ x success-k failure-k)
	 ;;        (let-syntax
	 ;;            ((sym?
	 ;;              (syntax-rules ()
	 ;;                ;; if the symbol `abracadabra' matches x, then x is a
	 ;;                ;; symbol
	 ;;                ((sym? x sk fk) sk)
	 ;;                ;; otherwise x is a non-symbol datum
	 ;;                ((sym? y sk fk) fk))))
	 ;;          (sym? abracadabra success-k failure-k)))))))

	 ;; Portable versions
	 ;;
	 ;; This *should* work, but doesn't :(
	 ;;   (define-syntax match-check-ellipsis
	 ;;     (syntax-rules (...)
	 ;;       ((_ ... sk fk) sk)
	 ;;       ((_ x sk fk) fk)))
	 ;;
	 ;; This is a little more complicated, and introduces a new let-syntax,
	 ;; but should work portably in any R[56]RS Scheme.  Taylor Campbell
	 ;; originally came up with the idea.
	 (define-syntax match-check-ellipsis
	 (syntax-rules ()
	 ;; these two aren't necessary but provide fast-case failures
	 ((match-check-ellipsis (a . b) success-k failure-k) failure-k)
	 ((match-check-ellipsis #(a ...) success-k failure-k) failure-k)
	 ;; matching an atom
	 ((match-check-ellipsis id success-k failure-k)
	 (let-syntax ((ellipsis? (syntax-rules ()
	 ;; iff `id' is `...' here then this will
	 ;; match a list of any length
	 ((ellipsis? (foo id) sk fk) sk)
	 ((ellipsis? other sk fk) fk))))
	 ;; this list of three elements will only match the (foo id) list
	 ;; above if `id' is `...'
	 (ellipsis? (a b c) success-k failure-k)))))

	 ;; This is portable but can be more efficient with non-portable
	 ;; extensions.  This trick was originally discovered by Oleg Kiselyov.
	 (define-syntax match-check-identifier
	 (syntax-rules ()
	 ;; fast-case failures, lists and vectors are not identifiers
	 ((_ (x . y) success-k failure-k) failure-k)
	 ((_ #(x ...) success-k failure-k) failure-k)
	 ;; x is an atom
	 ((_ x success-k failure-k)
	 (let-syntax
         ((sym?
	 (syntax-rules ()
	 ;; if the symbol `abracadabra' matches x, then x is a
	 ;; symbol
	 ((sym? x sk fk) sk)
	 ;; otherwise x is a non-symbol datum
	 ((sym? y sk fk) fk))))
	 (sym? abracadabra success-k failure-k)))))
	 )

Added sdl2.sls.

















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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

(library 
 (sdl2)
 (export sdl-init)
 (import (chezscheme))
 
 (define library-init (load-shared-object "libSDL2.so"))
 
 (define sdl-init-flags%  '((timer           . #x00000001)
			    (audio           . #x00000010)
			    (video           . #x00000020)
			    (joystick        . #x00000200)
			    (haptic          . #x00001000)
			    (game-controller . #x00002000)
			    (events          . #x00004000)
			    (no-parachute    . #x00100000)))
 
 ; calculates 'everything flag
 (define sdl-init-flags 
   (append sdl-init-flags% (list (cons 'everything (fold (lambda (x acc) (logor (cdr x) acc) ) 0 sdl-init-flags)))))

 (define (sdl-init-flag-value x)
   (assert (and  sdl-init-flag-value (symbol? x)))
   (let ([v (assq x sdl-init-flags)])
     (assert (and sdl-init-flag-value (pair? v)))
     (cdr v)))

 (define (sdl-init-flags-or l)
   (assert (and sdl-init-flags-or (list? l)))
   (fold (lambda (x acc) (logor (sdl-init-flag-value x) acc)) 0 l))

 (define (sdl-init-flags-list flags)
   (assert (and sdl-init-flags-list (number? flags)))
   (fold (lambda (x acc) 
	   	   (if (not (zero? (logand flags (cdr x)))) 
		       (cons (car x) acc)
		       acc)) 
	 '() sdl-init-flags%))


 (define (sdl-main-ready)
    (let ([f (foreign-procedure "SDL_MainReady" () void)])
     (f)))

 (define (sdl-init sub-systems)
   (assert (and sdl-init (list? sub-systems)))
   (let ([f (foreign-procedure "SDL_Init" (unsigned-32) int)]
	 [x (sdl-init-flags-or sub-systems)])
     (f x)))

 (define (sdl-init-sub-system sub-system)
   (assert (and sdl-init-sub-system (symbol? sub-system)))
   (let ([f (foreign-procedure "SDL_InitSubSystem" (unsigned-32) int)]
	 [x (sdl-init-flag-value sub-system)])
     (f x)))

 (define (sdl-quit-sub-system sub-system)
   (assert (and sdl-quit-sub-system (symbol? sub-system)))
   (let ([f (foreign-procedure "SDL_QuitSubSystem" (unsigned-32) void)]
	 [x (sdl-init-flag-value sub-system)])
     (f x)))

 (define (sdl-was-init sub-systems)
   (assert (and sdl-init (list? sub-systems)))
   (let ([f (foreign-procedure "SDL_WasInit" (unsigned-32) unsigned-32)]
	 [x (sdl-init-flags-or sub-systems)])
     (sdl-init-flags-list (f x))))
   
 (define (sdl-quit)
   (let ([f (foreign-procedure "SDL_Quit" () void)])
     (f)))
 ) ; library sdl2