1 /* kwset.c - search for any of a set of keywords.
2 Copyright 1989 Free Software Foundation
3 Written August 1989 by Mike Haertel.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 1, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 The author may be reached (Email) at the address mike@ai.mit.edu,
20 or (US mail) as Mike Haertel c/o Free Software Foundation. */
24 /* The algorithm implemented by these routines bears a startling resemblence
25 to one discovered by Beate Commentz-Walter, although it is not identical.
26 See "A String Matching Algorithm Fast on the Average," Technical Report,
27 IBM-Germany, Scientific Center Heidelberg, Tiergartenstrasse 15, D-6900
28 Heidelberg, Germany. See also Aho, A.V., and M. Corasick, "Efficient
29 String Matching: An Aid to Bibliographic Search," CACM June 1975,
30 Vol. 18, No. 6, which describes the failure function used below. */
35 #define NCHAR (UCHAR_MAX + 1)
36 #define obstack_chunk_alloc malloc
37 #define obstack_chunk_free free
39 /* Balanced tree of edges and labels leaving a given trie node. */
42 struct tree
*llink
; /* Left link; MUST be first field. */
43 struct tree
*rlink
; /* Right link (to larger labels). */
44 struct trie
*trie
; /* Trie node pointed to by this edge. */
45 unsigned char label
; /* Label on this edge. */
46 char balance
; /* Difference in depths of subtrees. */
49 /* Node of a trie representing a set of reversed keywords. */
52 unsigned int accepting
; /* Word index of accepted word, or zero. */
53 struct tree
*links
; /* Tree of edges leaving this node. */
54 struct trie
*parent
; /* Parent of this node. */
55 struct trie
*next
; /* List of all trie nodes in level order. */
56 struct trie
*fail
; /* Aho-Corasick failure function. */
57 int depth
; /* Depth of this node from the root. */
58 int shift
; /* Shift function for search failures. */
59 int maxshift
; /* Max shift of self and descendents. */
62 /* Structure returned opaquely to the caller, containing everything. */
65 struct obstack obstack
; /* Obstack for node allocation. */
66 int words
; /* Number of words in the trie. */
67 struct trie
*trie
; /* The trie itself. */
68 int mind
; /* Minimum depth of an accepting node. */
69 int maxd
; /* Maximum depth of any node. */
70 int delta
[NCHAR
]; /* Delta table for rapid search. */
71 struct trie
*next
[NCHAR
]; /* Table of children of the root. */
72 const char *trans
; /* Character translation table. */
75 /* Allocate and initialize a keyword set object, returning an opaque
76 pointer to it. Return NULL if memory is not available. */
78 DEFUN(kwsalloc
, (trans
), const char *trans
)
82 kwset
= (struct kwset
*) malloc(sizeof (struct kwset
));
86 obstack_init(&kwset
->obstack
);
89 = (struct trie
*) obstack_alloc(&kwset
->obstack
, sizeof (struct trie
));
92 kwsfree((kwset_t
) kwset
);
95 kwset
->trie
->accepting
= 0;
96 kwset
->trie
->links
= NULL
;
97 kwset
->trie
->parent
= NULL
;
98 kwset
->trie
->next
= NULL
;
99 kwset
->trie
->fail
= NULL
;
100 kwset
->trie
->depth
= 0;
101 kwset
->trie
->shift
= 0;
102 kwset
->mind
= INT_MAX
;
104 kwset
->trans
= trans
;
106 return (kwset_t
) kwset
;
109 /* Add the given string to the contents of the keyword set. Return NULL
110 for success, an error message otherwise. */
112 DEFUN(kwsincr
, (kws
, text
, len
),
113 kwset_t kws AND
const char *text AND
size_t len
)
116 register struct trie
*trie
;
117 register unsigned char label
;
118 register struct tree
*link
;
120 struct tree
*links
[12];
121 enum { L
, R
} dirs
[12];
122 struct tree
*t
, *r
, *l
, *rl
, *lr
;
124 kwset
= (struct kwset
*) kws
;
128 /* Descend the trie (built of reversed keywords) character-by-character,
129 installing new nodes when necessary. */
132 label
= kwset
->trans
? kwset
->trans
[(unsigned char) *--text
] : *--text
;
134 /* Descend the tree of outgoing links for this trie node,
135 looking for the current character and keeping track
136 of the path followed. */
138 links
[0] = (struct tree
*) &trie
->links
;
142 while (link
&& label
!= link
->label
)
145 if (label
< link
->label
)
146 dirs
[depth
++] = L
, link
= link
->llink
;
148 dirs
[depth
++] = R
, link
= link
->rlink
;
151 /* The current character doesn't have an outgoing link at
152 this trie node, so build a new trie node and install
153 a link in the current trie node's tree. */
156 link
= (struct tree
*) obstack_alloc(&kwset
->obstack
,
157 sizeof (struct tree
));
159 return "memory exhausted";
162 link
->trie
= (struct trie
*) obstack_alloc(&kwset
->obstack
,
163 sizeof (struct trie
));
165 return "memory exhausted";
166 link
->trie
->accepting
= 0;
167 link
->trie
->links
= NULL
;
168 link
->trie
->parent
= trie
;
169 link
->trie
->next
= NULL
;
170 link
->trie
->fail
= NULL
;
171 link
->trie
->depth
= trie
->depth
+ 1;
172 link
->trie
->shift
= 0;
176 /* Install the new tree node in its parent. */
177 if (dirs
[--depth
] == L
)
178 links
[depth
]->llink
= link
;
180 links
[depth
]->rlink
= link
;
182 /* Back up the tree fixing the balance flags. */
183 while (depth
&& !links
[depth
]->balance
)
185 if (dirs
[depth
] == L
)
186 --links
[depth
]->balance
;
188 ++links
[depth
]->balance
;
192 /* Rebalance the tree by pointer rotations if necessary. */
193 if (depth
&& (dirs
[depth
] == L
&& --links
[depth
]->balance
194 || dirs
[depth
] == R
&& ++links
[depth
]->balance
))
196 switch (links
[depth
]->balance
)
199 switch (dirs
[depth
+ 1])
202 r
= links
[depth
], t
= r
->llink
, rl
= t
->rlink
;
203 t
->rlink
= r
, r
->llink
= rl
;
204 t
->balance
= r
->balance
= 0;
207 r
= links
[depth
], l
= r
->llink
, t
= l
->rlink
;
208 rl
= t
->rlink
, lr
= t
->llink
;
209 t
->llink
= l
, l
->rlink
= lr
, t
->rlink
= r
, r
->llink
= rl
;
210 l
->balance
= t
->balance
!= 1 ? 0 : -1;
211 r
->balance
= t
->balance
!= (char) -1 ? 0 : 1;
217 switch (dirs
[depth
+ 1])
220 l
= links
[depth
], t
= l
->rlink
, lr
= t
->llink
;
221 t
->llink
= l
, l
->rlink
= lr
;
222 t
->balance
= l
->balance
= 0;
225 l
= links
[depth
], r
= l
->rlink
, t
= r
->llink
;
226 lr
= t
->llink
, rl
= t
->rlink
;
227 t
->llink
= l
, l
->rlink
= lr
, t
->rlink
= r
, r
->llink
= rl
;
228 l
->balance
= t
->balance
!= 1 ? 0 : -1;
229 r
->balance
= t
->balance
!= (char) -1 ? 0 : 1;
236 if (dirs
[depth
- 1] == L
)
237 links
[depth
- 1]->llink
= t
;
239 links
[depth
- 1]->rlink
= t
;
246 /* Mark the node we finally reached as accepting, encoding the
247 index number of this word in the keyword set so far. */
248 if (!trie
->accepting
)
249 trie
->accepting
= 1 + 2 * kwset
->words
;
252 /* Keep track of the longest and shortest string of the keyword set. */
253 if (trie
->depth
< kwset
->mind
)
254 kwset
->mind
= trie
->depth
;
255 if (trie
->depth
> kwset
->maxd
)
256 kwset
->maxd
= trie
->depth
;
261 /* Enqueue the trie nodes referenced from the given tree in the
264 DEFUN(enqueue
, (tree
, last
), struct tree
*tree AND
struct trie
**last
)
268 enqueue(tree
->llink
, last
);
269 enqueue(tree
->rlink
, last
);
270 (*last
) = (*last
)->next
= tree
->trie
;
273 /* Compute the Aho-Corasick failure function for the trie nodes referenced
274 from the given tree, given the failure function for their parent as
275 well as a last resort failure node. */
277 DEFUN(treefails
, (tree
, fail
, recourse
),
278 register struct tree
*tree
279 AND
struct trie
*fail AND
struct trie
*recourse
)
281 register struct tree
*link
;
286 treefails(tree
->llink
, fail
, recourse
);
287 treefails(tree
->rlink
, fail
, recourse
);
289 /* Find, in the chain of fails going back to the root, the first
290 node that has a descendent on the current label. */
294 while (link
&& tree
->label
!= link
->label
)
295 if (tree
->label
< link
->label
)
301 tree
->trie
->fail
= link
->trie
;
307 tree
->trie
->fail
= recourse
;
310 /* Set delta entries for the links of the given tree such that
311 the preexisting delta value is larger than the current depth. */
313 DEFUN(treedelta
, (tree
, depth
, delta
),
314 register struct tree
*tree AND
register int depth AND
int delta
[])
318 treedelta(tree
->llink
, depth
, delta
);
319 treedelta(tree
->rlink
, depth
, delta
);
320 if (depth
< delta
[tree
->label
])
321 delta
[tree
->label
] = depth
;
324 /* Return true if A has every label in B. */
326 DEFUN(hasevery
, (a
, b
), register struct tree
*a AND
register struct tree
*b
)
330 if (!hasevery(a
, b
->llink
))
332 if (!hasevery(a
, b
->rlink
))
334 while (a
&& b
->label
!= a
->label
)
335 if (b
->label
< a
->label
)
342 /* Compute a vector, indexed by character code, of the trie nodes
343 referenced from the given tree. */
345 DEFUN(treenext
, (tree
, next
), struct tree
*tree AND
struct trie
*next
[])
349 treenext(tree
->llink
, next
);
350 treenext(tree
->rlink
, next
);
351 next
[tree
->label
] = tree
->trie
;
354 /* Compute the shift for each trie node, as well as the delta
355 table and next cache for the given keyword set. */
357 DEFUN(kwsprep
, (kws
), kwset_t kws
)
359 register struct kwset
*kwset
;
361 register struct trie
*curr
, *fail
;
362 register const char *trans
;
364 struct trie
*last
, *next
[NCHAR
];
366 kwset
= (struct kwset
*) kws
;
368 /* Initial values for the delta table; will be changed later. The
369 delta entry for a given character is the smallest depth of any
370 node at which an outgoing edge is labeled by that character. */
371 for (i
= 0; i
< NCHAR
; ++i
)
372 delta
[i
] = kwset
->mind
;
374 /* Traverse the nodes of the trie in level order, simultaneously
375 computing the delta table, failure function, and shift function. */
376 for (curr
= last
= kwset
->trie
; curr
; curr
= curr
->next
)
378 /* Enqueue the immediate descendents in the level order queue. */
379 enqueue(curr
->links
, &last
);
381 curr
->shift
= kwset
->mind
;
382 curr
->maxshift
= kwset
->mind
;
384 /* Update the delta table for the descendents of this node. */
385 treedelta(curr
->links
, curr
->depth
, delta
);
387 /* Compute the failure function for the decendents of this node. */
388 treefails(curr
->links
, curr
->fail
, kwset
->trie
);
390 /* Update the shifts at each node in the current node's chain
391 of fails back to the root. */
392 for (fail
= curr
->fail
; fail
; fail
= fail
->fail
)
394 /* If the current node has some outgoing edge that the fail
395 doesn't, then the shift at the fail should be no larger
396 than the difference of their depths. */
397 if (!hasevery(fail
->links
, curr
->links
))
398 if (curr
->depth
- fail
->depth
< fail
->shift
)
399 fail
->shift
= curr
->depth
- fail
->depth
;
401 /* If the current node is accepting then the shift at the
402 fail and its descendents should be no larger than the
403 difference of their depths. */
404 if (curr
->accepting
&& fail
->maxshift
> curr
->depth
- fail
->depth
)
405 fail
->maxshift
= curr
->depth
- fail
->depth
;
409 /* Traverse the trie in level order again, fixing up all nodes whose
410 shift exceeds their inherited maxshift. */
411 for (curr
= kwset
->trie
->next
; curr
; curr
= curr
->next
)
413 if (curr
->maxshift
> curr
->parent
->maxshift
)
414 curr
->maxshift
= curr
->parent
->maxshift
;
415 if (curr
->shift
> curr
->maxshift
)
416 curr
->shift
= curr
->maxshift
;
419 /* Create a vector, indexed by character code, of the outgoing links
420 from the root node. */
421 for (i
= 0; i
< NCHAR
; ++i
)
423 treenext(kwset
->trie
->links
, next
);
425 /* Fix things up for any translation table. */
426 if (trans
= kwset
->trans
)
427 for (i
= 0; i
< NCHAR
; ++i
)
429 kwset
->delta
[i
] = delta
[(unsigned char) trans
[i
]];
430 kwset
->next
[i
] = next
[(unsigned char) trans
[i
]];
433 for (i
= 0; i
< NCHAR
; ++i
)
435 kwset
->delta
[i
] = delta
[i
];
436 kwset
->next
[i
] = next
[i
];
442 /* Search through the given text for a match of any member of the
443 given keyword set. Return a pointer to the first character of
444 the matching substring, or NULL if no match is found. If FOUNDLEN
445 is non-NULL store in the referenced location the length of the
446 matching substring. Similarly, if FOUNDIDX is non-NULL, store
447 in the referenced location the index number of the particular
450 DEFUN(kwsexec
, (kws
, text
, len
, kwsmatch
),
451 kwset_t kws AND
char *text AND
size_t len AND
struct kwsmatch
*kwsmatch
)
454 struct trie
**next
, *trie
, *accept
;
455 char *beg
, *lim
, *mch
, *lmch
;
456 register unsigned char c
;
457 register int *delta
, d
;
458 register char *end
, *qlim
;
459 register struct tree
*tree
;
460 register const char *trans
;
462 /* Initialize register copies and look for easy ways out. */
463 kwset
= (struct kwset
*) kws
;
464 if (len
< kwset
->mind
)
467 delta
= kwset
->delta
;
468 trans
= kwset
->trans
;
475 mch
= text
, accept
= kwset
->trie
;
479 if (len
>= 4 * kwset
->mind
)
480 qlim
= lim
- 4 * kwset
->mind
;
484 while (lim
- end
>= d
)
486 if (qlim
&& end
<= qlim
)
489 while ((d
= delta
[c
= *end
]) && end
< qlim
)
492 end
+= delta
[(unsigned char) *end
];
493 end
+= delta
[(unsigned char) *end
];
498 d
= delta
[c
= (end
+= d
)[-1]];
511 c
= trans
? trans
[(unsigned char) *--beg
] : *--beg
;
513 while (tree
&& c
!= tree
->label
)
537 /* Given a known match, find the longest possible match anchored
538 at or before its starting point. This is nearly a verbatim
539 copy of the preceding main search loops. */
540 if (lim
- mch
> kwset
->maxd
)
541 lim
= mch
+ kwset
->maxd
;
544 while (lim
- end
>= d
)
546 if (d
= delta
[c
= (end
+= d
)[-1]])
549 if (!(trie
= next
[c
]))
554 if (trie
->accepting
&& beg
<= mch
)
562 c
= trans
? trans
[(unsigned char) *--beg
] : *--beg
;
564 while (tree
&& c
!= tree
->label
)
572 if (trie
->accepting
&& beg
<= mch
)
593 kwsmatch
->index
= accept
->accepting
/ 2;
594 kwsmatch
->beg
[0] = mch
;
595 kwsmatch
->size
[0] = accept
->depth
;
600 /* Free the components of the given keyword set. */
602 DEFUN(kwsfree
, (kws
), kwset_t kws
)
606 kwset
= (struct kwset
*) kws
;
607 obstack_free(&kwset
->obstack
, (PTR
) NULL
);