-
Notifications
You must be signed in to change notification settings - Fork 0
/
aho_corasick.c
576 lines (455 loc) · 12.8 KB
/
aho_corasick.c
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
/*
Copyright (C) 2010-2011, Bruce Ediger
This file is part of acl.
acl is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
acl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with acl; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* $Id: aho_corasick.c,v 1.12 2011/07/09 14:22:59 bediger Exp $ */
/*
* This code based on:
* Pattern Matching in Trees
* Christoph M. Hoffmann and Michael J. O'Donnell
* Journal of the Association for Computing Machinery
* Vol 29, No 1, January 1982
* pp 68-95
* http://ftp.cs.purdue.edu/research/technical_reports/1973/TR%2073-091.pdf
* and on
* Efficient string matching: an aid to bibliographic search
* Alfred V. Aho, Margaret J. Corasick
* Communications of the ACM
* Volume 18, Issue 6 (June 1975)
* Pages: 333 - 340
*
* I can't say that I truly understood the latter paper, except during
* the throes of development, so commentary on the Aho-Corasick part of
* the code is sparse.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <node.h>
#include <aho_corasick.h>
#include <cb.h>
#include <hashtable.h>
#include <atom.h>
#include <buffer.h>
#include <graph.h>
/* From "Pattern Matching in Trees". */
struct stack_elem {
struct node *n; /* 1 */
int state_at_n; /* 2 */
int visited; /* 3 */
int node_number;
};
void set_output_length(struct gto *p, int state, int node_cnt);
int tabulate(struct gto *g, struct stack_elem *stk, int top, int state, int pat_leaf_count, int *count);
const char *abstr_meta_var;
struct gto *
init_goto()
{
int i;
struct gto *g = NULL;
abstr_meta_var = Atom_string("_");
g = malloc(sizeof(*g));
g->ary = malloc(sizeof(int *));
g->ary[0] = malloc(128*sizeof(int));
g->ary_len = 1;
for (i = 0; i < 128; ++i)
g->ary[0][i] = FAIL;
g->output = malloc(sizeof(*g->output));
g->output_len = 1;
g->output->len = g->output->max = 0;
g->output->out = NULL;
g->max_node_count = 0;
return g;
}
void
construct_goto(const char *keywords[], int k, struct gto *g)
{
int newstate = 0;
int i;
for (i = 0; i < k; ++i)
{
int state, j, p;
/* procedure enter() */
state = 0;
j = 0;
while (
FAIL != (
(state<g->ary_len) ?
g->ary[state][(int)keywords[i][j]] :
(assert(state>=g->ary_len),FAIL)
)
)
{
state = ((state<g->ary_len) ?
g->ary[state][(int)keywords[i][j]] :
(assert(state>=g->ary_len),FAIL)
);
++j;
}
for (p = j; '\0' != keywords[i][p]; ++p)
{
++newstate;
add_state(g, state, keywords[i][p], newstate);
state = newstate;
}
/* end procedure enter() */
set_output(g, state, keywords[i]);
}
for (i = 0; i < 128; ++i)
{
if (FAIL == g->ary[0][i])
g->ary[0][i] = 0;
}
}
void
set_output(struct gto *p, int state, const char *keyword)
{
size_t kwl = strlen(keyword);
int i;
int output_node_count = 0;
/* Slightly weird: count the number of nodes in
* the "keyword", which is actually a string, from
* root to leaf of a path through a pattern tree. */
for (i = 0; i < kwl; ++i)
{
/* Skip the characters '1' and '2': they're
* the characters in the string indicating left
* or right branch at an application node. */
if ('1' != keyword[i] && '2' != keyword[i])
{
++output_node_count;
/* If you hit a keyword that doesn't begin
* with '@', you've hit a leaf node. We've
* counted it, so now we break out of the loop. */
if (keyword[i] != '@')
break;
}
}
set_output_length(p, state, output_node_count);
}
void
set_output_length(struct gto *p, int state, int node_cnt)
{
struct output_extent *oxt;
/* value of node_cnt stored against the match */
if (state >= p->output_len)
{
int n = state - p->output_len + 1; /* how many more to add */
int l = p->output_len + n; /* how many total after add */
int i;
p->output = realloc(p->output, l*sizeof(struct output_extent));
/* init only the new structs output_extent, leave previous ones alone */
for (i = p->output_len; i < l; ++i)
{
p->output[i].len = 0;
p->output[i].max = 0;
p->output[i].out = NULL;
}
p->output_len += n; /* bumped up the number of structs output_extent */
}
/* oxt comprises the lengths of paths in pattern matched in subject */
oxt = &(p->output[state]);
if (oxt->len >= oxt->max)
{
oxt->max += 4;
if (oxt->out)
oxt->out = realloc(oxt->out, oxt->max * sizeof(int));
else
oxt->out = malloc(oxt->max * sizeof(int));
}
oxt->out[oxt->len++] = node_cnt;
/* state has oxt->len matches now */
if (node_cnt > p->max_node_count)
p->max_node_count = node_cnt;
}
void
add_state(struct gto *p, int state, char input, int new_state)
{
if (state >= p->ary_len || new_state >= p->ary_len)
{
int i, n;
/* by using something other than 1, would it jack up array length
* more than a single entry at a time? */
n = 1 + ((new_state > state? new_state: state) - p->ary_len);
p->ary = realloc(p->ary, sizeof(int *)*(p->ary_len + n));
for (i = p->ary_len; i < p->ary_len + n; ++i)
{
int j;
/* if this ends up being too costly, could increase array size
* by more than one each time, and malloc loads of rows at once */
p->ary[i] = malloc(sizeof(int)*128);
for (j = 0; j < 128; ++j)
p->ary[i][j] = FAIL;
}
p->ary_len += n;
}
p->ary[state][(int)input] = new_state;
}
void
construct_failure(struct gto *g)
{
int i;
struct queue *q;
g->failure = malloc(g->ary_len * sizeof(int));
for (i = 0; i < g->ary_len; ++i)
g->failure[i] = 0;
q = queueinit();
for (i = 0; i < 128; ++i)
{
int s = g->ary[0][i];
if (0 != s)
{
enqueue(q, s);
g->failure[s] = 0;
}
}
while (!queueempty(q))
{
int a;
int r = dequeue(q);
for (a = 0; a < 128; ++a)
{
int s = g->ary[r][a];
if (FAIL != s)
{
int state;
struct output_extent *p;
enqueue(q, s);
state = g->failure[r];
while (FAIL == g->ary[state][a])
state = g->failure[state];
g->failure[s] = g->ary[state][a];
/* output(s) <- output(s) U output(f(s)) */
p = &g->output[g->failure[s]];
for (i = 0; i < p->len; ++i)
set_output_length(g, s, p->out[i]);
}
}
}
queuedestroy(q);
}
void
destroy_goto(struct gto *p)
{
int i;
for (i = 0; i < p->ary_len; ++i)
free(p->ary[i]);
free(p->ary);
for (i = 0; i < p->output_len; ++i)
free(p->output[i].out);
if (NULL != p->output) free(p->output);
if (NULL != p->failure) free(p->failure);
if (NULL != p->delta[0]) free(p->delta[0]);
if (NULL != p->delta) free(p->delta);
free(p);
}
void
construct_delta(struct gto *g)
{
struct queue *q;
int i, a;
g->delta = malloc(sizeof(int *)*g->ary_len);
g->delta[0] = malloc(sizeof(int)*g->ary_len*128);
memset(g->delta[0], 0, sizeof(int)*g->ary_len*128);
for (i = 0; i < g->ary_len; ++i)
g->delta[i] = g->delta[0] + i*128;
q = queueinit();
for (a = 0; a < 128; ++a)
{
g->delta[0][a] = g->ary[0][a];
if (0 != g->ary[0][a])
enqueue(q, g->ary[0][a]);
}
while (!queueempty(q))
{
int r = dequeue(q);
for (a = 0; a < 128; ++a)
{
int s = g->ary[r][a];
if (FAIL != s)
{
enqueue(q, s);
g->delta[r][a] = s;
} else
g->delta[r][a] = g->delta[g->failure[r]][a];
}
}
queuedestroy(q);
}
/* This function implemented from: "Pattern Matching in Trees".
* Each "pattern" (LHS of an abstraction rule input) gets converted
* into strings. Each string represents one root-to-leaf path
* through the pattern. The strings get put into a "goto" table
* as per Aho & Corasick. Hoffmann & O'Donnel's Algorithm D does a
* breadth-first traverse of the graph of the expresson subject to
* bracket abstraction, trying pattern at each node of the
* subject. If all the paths-through-a-pattern get found at a given
* subject node, do the RHS, perform the replacement specified by the
* RHS of the abstraction rule at that node.
*/
static int *count = NULL;
static struct stack_elem *stack = NULL;
static unsigned int stack_sz = 0;
int
algorithm_d(struct gto *g, struct node *t, int subject_node_count, int pat_path_cnt, const char *abstr_var_name)
{
int top = 1;
int matched = 0;
int breadth_counter = 0;
int next_state;
const char *p;
struct node *exact_match_node = NULL;
++subject_node_count; /* 0-indexed arrays, first element at index 1 */
if (subject_node_count > stack_sz)
{
if (subject_node_count < 100)
stack_sz = 100;
else
stack_sz = subject_node_count;
if (count) free(count);
count = malloc(stack_sz * sizeof(int));
if (stack) free(stack);
stack = malloc(stack_sz * sizeof(struct stack_elem));
}
memset(count, 0, stack_sz * sizeof(int));
next_state = 0;
p = (t->name != abstr_var_name)? t->name: abstr_meta_var;
while (*p)
next_state = g->delta[next_state][(int)*p++];
stack[top].n = t;
stack[top].state_at_n = next_state;
stack[top].visited = 0;
stack[top].node_number = breadth_counter++;
matched += tabulate(g, stack, top, next_state, pat_path_cnt, count);
if (!matched)
{
if (any_var_in_tree(t))
{
if (var_in_tree(t, abstr_var_name))
next_state = g->delta[0][(int)'+'];
else
next_state = g->delta[0][(int)'-'];
matched += tabulate(g, stack, top, next_state, pat_path_cnt, count);
} else {
next_state = g->delta[0][(int)'!'];
matched += tabulate(g, stack, top, next_state, pat_path_cnt, count);
if (!matched)
{
next_state = g->delta[0][(int)'-'];
matched += tabulate(g, stack, top, next_state, pat_path_cnt, count);
}
}
}
while (!matched && top > 0)
{
struct node *next_node, *this_node = stack[top].n;
int intstate, nxt_st, this_state = stack[top].state_at_n;
int visited = stack[top].visited;
if (visited == 2 || this_node->typ == ATOM || top > g->max_node_count)
--top;
else {
++visited;
stack[top].visited = visited;
intstate = g->delta[this_state][visited == 1?'1':'2'];
matched += tabulate(g, stack, top, intstate, pat_path_cnt, count);
next_node = (visited == 1)? this_node->left: this_node->right;
nxt_st = intstate;
p = (next_node->name != abstr_var_name)? next_node->name: abstr_meta_var;
while (*p)
nxt_st = g->delta[nxt_st][(int)*p++];
++top;
stack[top].n = next_node;
stack[top].state_at_n = nxt_st;
stack[top].visited = 0;
stack[top].node_number = breadth_counter++;
if (top <= g->max_node_count)
{
matched += tabulate(g, stack, top, nxt_st, pat_path_cnt, count);
if (!matched)
{
nxt_st = g->delta[intstate][(int)'^'];
if (nxt_st)
{
if (exact_match_node)
{
if (equivalent_graphs(exact_match_node, next_node))
matched += tabulate(g, stack, top, nxt_st, pat_path_cnt, count);
} else {
/* XXX - what about a 3-way match?
* should increment count[something] here, as we found it. */
exact_match_node = next_node;
matched += tabulate(g, stack, top, nxt_st, pat_path_cnt, count);
}
}
}
if (!matched)
{
if (any_var_in_tree(next_node))
{
if (var_in_tree(next_node, abstr_var_name))
nxt_st = g->delta[intstate][(int)'+'];
else
nxt_st = g->delta[intstate][(int)'-'];
} else {
nxt_st = g->delta[intstate][(int)'!'];
if (0 == nxt_st)
nxt_st = g->delta[intstate][(int)'-'];
}
matched += tabulate(g, stack, top, nxt_st, pat_path_cnt, count);
}
}
}
}
exact_match_node = NULL;
return matched;
}
/* Again, from "Pattern Matching in Trees".
* If the branches under a given node match all the pattern's
* paths from that node to leaves, then the node and its sub-tree
* match the pattern.
*/
int
tabulate(struct gto *g, struct stack_elem *stk, int top, int state, int pat_leaf_count, int *cnt)
{
int i;
int r = 0;
struct output_extent *oxt;
if (state < 0)
return 0;
oxt = &(g->output[state]);
for (i = 0; r == 0 && i < oxt->len; ++i)
{
int idx = top - oxt->out[i] + 1;
int nn = stk[idx].node_number;
++cnt[nn];
if (cnt[nn] == pat_leaf_count)
r = 1;
}
return r;
}
void
cleanup_abstraction(void)
{
if ((stack || count) && stack_sz == 0)
fprintf(stderr, "Problem: bracket abstraction stack (%p) or count (%p) non-NULL but stack size wrong (%d)\n",
stack, count, stack_sz);
if ((stack == NULL || count == NULL) && stack_sz != 0)
fprintf(stderr, "Problem: bracket abstraction stack (%p) or count (%p) NULL but stack size non-zero (%d)\n",
stack, count, stack_sz);
if (stack) free(stack);
stack = NULL;
if (count) free(count);
count = NULL;
}