1 /* kwset.c - search for any of a set of keywords.
2 Copyright 1989, 1998, 2000, 2005 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
19 /* Written August 1989 by Mike Haertel.
20 The author may be reached (Email) at the address mike@ai.mit.edu,
21 or (US mail) as Mike Haertel c/o Free Software Foundation. */
23 /* The algorithm implemented by these routines bears a startling resemblence
24 to one discovered by Beate Commentz-Walter, although it is not identical.
25 See "A String Matching Algorithm Fast on the Average," Technical Report,
26 IBM-Germany, Scientific Center Heidelberg, Tiergartenstrasse 15, D-6900
27 Heidelberg, Germany. See also Aho, A.V., and M. Corasick, "Efficient
28 String Matching: An Aid to Bibliographic Search," CACM June 1975,
29 Vol. 18, No. 6, which describes the failure function used below. */
34 #include <sys/types.h>
40 #define _(str) gettext (str)
43 extern char *xmalloc();
45 # define malloc xmalloc
48 #define NCHAR (UCHAR_MAX + 1)
49 #define obstack_chunk_alloc malloc
50 #define obstack_chunk_free free
52 /* Balanced tree of edges and labels leaving a given trie node. */
55 struct tree
*llink
; /* Left link; MUST be first field. */
56 struct tree
*rlink
; /* Right link (to larger labels). */
57 struct trie
*trie
; /* Trie node pointed to by this edge. */
58 unsigned char label
; /* Label on this edge. */
59 char balance
; /* Difference in depths of subtrees. */
62 /* Node of a trie representing a set of reversed keywords. */
65 unsigned int accepting
; /* Word index of accepted word, or zero. */
66 struct tree
*links
; /* Tree of edges leaving this node. */
67 struct trie
*parent
; /* Parent of this node. */
68 struct trie
*next
; /* List of all trie nodes in level order. */
69 struct trie
*fail
; /* Aho-Corasick failure function. */
70 int depth
; /* Depth of this node from the root. */
71 int shift
; /* Shift function for search failures. */
72 int maxshift
; /* Max shift of self and descendents. */
75 /* Structure returned opaquely to the caller, containing everything. */
78 struct obstack obstack
; /* Obstack for node allocation. */
79 int words
; /* Number of words in the trie. */
80 struct trie
*trie
; /* The trie itself. */
81 int mind
; /* Minimum depth of an accepting node. */
82 int maxd
; /* Maximum depth of any node. */
83 unsigned char delta
[NCHAR
]; /* Delta table for rapid search. */
84 struct trie
*next
[NCHAR
]; /* Table of children of the root. */
85 char *target
; /* Target string if there's only one. */
86 int mind2
; /* Used in Boyer-Moore search for one string. */
87 char const *trans
; /* Character translation table. */
90 /* Allocate and initialize a keyword set object, returning an opaque
91 pointer to it. Return NULL if memory is not available. */
93 kwsalloc (char const *trans
)
97 kwset
= (struct kwset
*) malloc(sizeof (struct kwset
));
101 obstack_init(&kwset
->obstack
);
104 = (struct trie
*) obstack_alloc(&kwset
->obstack
, sizeof (struct trie
));
107 kwsfree((kwset_t
) kwset
);
110 kwset
->trie
->accepting
= 0;
111 kwset
->trie
->links
= 0;
112 kwset
->trie
->parent
= 0;
113 kwset
->trie
->next
= 0;
114 kwset
->trie
->fail
= 0;
115 kwset
->trie
->depth
= 0;
116 kwset
->trie
->shift
= 0;
117 kwset
->mind
= INT_MAX
;
120 kwset
->trans
= trans
;
122 return (kwset_t
) kwset
;
125 /* Add the given string to the contents of the keyword set. Return NULL
126 for success, an error message otherwise. */
128 kwsincr (kwset_t kws
, char const *text
, size_t len
)
131 register struct trie
*trie
;
132 register unsigned char label
;
133 register struct tree
*link
;
135 struct tree
*links
[12];
136 enum { L
, R
} dirs
[12];
137 struct tree
*t
, *r
, *l
, *rl
, *lr
;
139 kwset
= (struct kwset
*) kws
;
143 /* Descend the trie (built of reversed keywords) character-by-character,
144 installing new nodes when necessary. */
147 label
= kwset
->trans
? kwset
->trans
[(unsigned char) *--text
] : *--text
;
149 /* Descend the tree of outgoing links for this trie node,
150 looking for the current character and keeping track
151 of the path followed. */
153 links
[0] = (struct tree
*) &trie
->links
;
157 while (link
&& label
!= link
->label
)
160 if (label
< link
->label
)
161 dirs
[depth
++] = L
, link
= link
->llink
;
163 dirs
[depth
++] = R
, link
= link
->rlink
;
166 /* The current character doesn't have an outgoing link at
167 this trie node, so build a new trie node and install
168 a link in the current trie node's tree. */
171 link
= (struct tree
*) obstack_alloc(&kwset
->obstack
,
172 sizeof (struct tree
));
174 return _("memory exhausted");
177 link
->trie
= (struct trie
*) obstack_alloc(&kwset
->obstack
,
178 sizeof (struct trie
));
180 return _("memory exhausted");
181 link
->trie
->accepting
= 0;
182 link
->trie
->links
= 0;
183 link
->trie
->parent
= trie
;
184 link
->trie
->next
= 0;
185 link
->trie
->fail
= 0;
186 link
->trie
->depth
= trie
->depth
+ 1;
187 link
->trie
->shift
= 0;
191 /* Install the new tree node in its parent. */
192 if (dirs
[--depth
] == L
)
193 links
[depth
]->llink
= link
;
195 links
[depth
]->rlink
= link
;
197 /* Back up the tree fixing the balance flags. */
198 while (depth
&& !links
[depth
]->balance
)
200 if (dirs
[depth
] == L
)
201 --links
[depth
]->balance
;
203 ++links
[depth
]->balance
;
207 /* Rebalance the tree by pointer rotations if necessary. */
208 if (depth
&& ((dirs
[depth
] == L
&& --links
[depth
]->balance
)
209 || (dirs
[depth
] == R
&& ++links
[depth
]->balance
)))
211 switch (links
[depth
]->balance
)
214 switch (dirs
[depth
+ 1])
217 r
= links
[depth
], t
= r
->llink
, rl
= t
->rlink
;
218 t
->rlink
= r
, r
->llink
= rl
;
219 t
->balance
= r
->balance
= 0;
222 r
= links
[depth
], l
= r
->llink
, t
= l
->rlink
;
223 rl
= t
->rlink
, lr
= t
->llink
;
224 t
->llink
= l
, l
->rlink
= lr
, t
->rlink
= r
, r
->llink
= rl
;
225 l
->balance
= t
->balance
!= 1 ? 0 : -1;
226 r
->balance
= t
->balance
!= (char) -1 ? 0 : 1;
234 switch (dirs
[depth
+ 1])
237 l
= links
[depth
], t
= l
->rlink
, lr
= t
->llink
;
238 t
->llink
= l
, l
->rlink
= lr
;
239 t
->balance
= l
->balance
= 0;
242 l
= links
[depth
], r
= l
->rlink
, t
= r
->llink
;
243 lr
= t
->llink
, rl
= t
->rlink
;
244 t
->llink
= l
, l
->rlink
= lr
, t
->rlink
= r
, r
->llink
= rl
;
245 l
->balance
= t
->balance
!= 1 ? 0 : -1;
246 r
->balance
= t
->balance
!= (char) -1 ? 0 : 1;
257 if (dirs
[depth
- 1] == L
)
258 links
[depth
- 1]->llink
= t
;
260 links
[depth
- 1]->rlink
= t
;
267 /* Mark the node we finally reached as accepting, encoding the
268 index number of this word in the keyword set so far. */
269 if (!trie
->accepting
)
270 trie
->accepting
= 1 + 2 * kwset
->words
;
273 /* Keep track of the longest and shortest string of the keyword set. */
274 if (trie
->depth
< kwset
->mind
)
275 kwset
->mind
= trie
->depth
;
276 if (trie
->depth
> kwset
->maxd
)
277 kwset
->maxd
= trie
->depth
;
282 /* Enqueue the trie nodes referenced from the given tree in the
285 enqueue (struct tree
*tree
, struct trie
**last
)
289 enqueue(tree
->llink
, last
);
290 enqueue(tree
->rlink
, last
);
291 (*last
) = (*last
)->next
= tree
->trie
;
294 /* Compute the Aho-Corasick failure function for the trie nodes referenced
295 from the given tree, given the failure function for their parent as
296 well as a last resort failure node. */
298 treefails (register struct tree
const *tree
, struct trie
const *fail
,
299 struct trie
*recourse
)
301 register struct tree
*link
;
306 treefails(tree
->llink
, fail
, recourse
);
307 treefails(tree
->rlink
, fail
, recourse
);
309 /* Find, in the chain of fails going back to the root, the first
310 node that has a descendent on the current label. */
314 while (link
&& tree
->label
!= link
->label
)
315 if (tree
->label
< link
->label
)
321 tree
->trie
->fail
= link
->trie
;
327 tree
->trie
->fail
= recourse
;
330 /* Set delta entries for the links of the given tree such that
331 the preexisting delta value is larger than the current depth. */
333 treedelta (register struct tree
const *tree
,
334 register unsigned int depth
,
335 unsigned char delta
[])
339 treedelta(tree
->llink
, depth
, delta
);
340 treedelta(tree
->rlink
, depth
, delta
);
341 if (depth
< delta
[tree
->label
])
342 delta
[tree
->label
] = depth
;
345 /* Return true if A has every label in B. */
347 hasevery (register struct tree
const *a
, register struct tree
const *b
)
351 if (!hasevery(a
, b
->llink
))
353 if (!hasevery(a
, b
->rlink
))
355 while (a
&& b
->label
!= a
->label
)
356 if (b
->label
< a
->label
)
363 /* Compute a vector, indexed by character code, of the trie nodes
364 referenced from the given tree. */
366 treenext (struct tree
const *tree
, struct trie
*next
[])
370 treenext(tree
->llink
, next
);
371 treenext(tree
->rlink
, next
);
372 next
[tree
->label
] = tree
->trie
;
375 /* Compute the shift for each trie node, as well as the delta
376 table and next cache for the given keyword set. */
378 kwsprep (kwset_t kws
)
380 register struct kwset
*kwset
;
382 register struct trie
*curr
, *fail
;
383 register char const *trans
;
384 unsigned char delta
[NCHAR
];
385 struct trie
*last
, *next
[NCHAR
];
387 kwset
= (struct kwset
*) kws
;
389 /* Initial values for the delta table; will be changed later. The
390 delta entry for a given character is the smallest depth of any
391 node at which an outgoing edge is labeled by that character. */
392 if (kwset
->mind
< 256)
393 for (i
= 0; i
< NCHAR
; ++i
)
394 delta
[i
] = kwset
->mind
;
396 for (i
= 0; i
< NCHAR
; ++i
)
399 /* Check if we can use the simple boyer-moore algorithm, instead
400 of the hairy commentz-walter algorithm. */
401 if (kwset
->words
== 1 && kwset
->trans
== 0)
403 /* Looking for just one string. Extract it from the trie. */
404 kwset
->target
= obstack_alloc(&kwset
->obstack
, kwset
->mind
);
405 for (i
= kwset
->mind
- 1, curr
= kwset
->trie
; i
>= 0; --i
)
407 kwset
->target
[i
] = curr
->links
->label
;
408 curr
= curr
->links
->trie
;
410 /* Build the Boyer Moore delta. Boy that's easy compared to CW. */
411 for (i
= 0; i
< kwset
->mind
; ++i
)
412 delta
[(unsigned char) kwset
->target
[i
]] = kwset
->mind
- (i
+ 1);
413 kwset
->mind2
= kwset
->mind
;
414 /* Find the minimal delta2 shift that we might make after
415 a backwards match has failed. */
416 for (i
= 0; i
< kwset
->mind
- 1; ++i
)
417 if (kwset
->target
[i
] == kwset
->target
[kwset
->mind
- 1])
418 kwset
->mind2
= kwset
->mind
- (i
+ 1);
422 /* Traverse the nodes of the trie in level order, simultaneously
423 computing the delta table, failure function, and shift function. */
424 for (curr
= last
= kwset
->trie
; curr
; curr
= curr
->next
)
426 /* Enqueue the immediate descendents in the level order queue. */
427 enqueue(curr
->links
, &last
);
429 curr
->shift
= kwset
->mind
;
430 curr
->maxshift
= kwset
->mind
;
432 /* Update the delta table for the descendents of this node. */
433 treedelta(curr
->links
, curr
->depth
, delta
);
435 /* Compute the failure function for the decendents of this node. */
436 treefails(curr
->links
, curr
->fail
, kwset
->trie
);
438 /* Update the shifts at each node in the current node's chain
439 of fails back to the root. */
440 for (fail
= curr
->fail
; fail
; fail
= fail
->fail
)
442 /* If the current node has some outgoing edge that the fail
443 doesn't, then the shift at the fail should be no larger
444 than the difference of their depths. */
445 if (!hasevery(fail
->links
, curr
->links
))
446 if (curr
->depth
- fail
->depth
< fail
->shift
)
447 fail
->shift
= curr
->depth
- fail
->depth
;
449 /* If the current node is accepting then the shift at the
450 fail and its descendents should be no larger than the
451 difference of their depths. */
452 if (curr
->accepting
&& fail
->maxshift
> curr
->depth
- fail
->depth
)
453 fail
->maxshift
= curr
->depth
- fail
->depth
;
457 /* Traverse the trie in level order again, fixing up all nodes whose
458 shift exceeds their inherited maxshift. */
459 for (curr
= kwset
->trie
->next
; curr
; curr
= curr
->next
)
461 if (curr
->maxshift
> curr
->parent
->maxshift
)
462 curr
->maxshift
= curr
->parent
->maxshift
;
463 if (curr
->shift
> curr
->maxshift
)
464 curr
->shift
= curr
->maxshift
;
467 /* Create a vector, indexed by character code, of the outgoing links
468 from the root node. */
469 for (i
= 0; i
< NCHAR
; ++i
)
471 treenext(kwset
->trie
->links
, next
);
473 if ((trans
= kwset
->trans
) != 0)
474 for (i
= 0; i
< NCHAR
; ++i
)
475 kwset
->next
[i
] = next
[(unsigned char) trans
[i
]];
477 for (i
= 0; i
< NCHAR
; ++i
)
478 kwset
->next
[i
] = next
[i
];
481 /* Fix things up for any translation table. */
482 if ((trans
= kwset
->trans
) != 0)
483 for (i
= 0; i
< NCHAR
; ++i
)
484 kwset
->delta
[i
] = delta
[(unsigned char) trans
[i
]];
486 for (i
= 0; i
< NCHAR
; ++i
)
487 kwset
->delta
[i
] = delta
[i
];
492 #define U(C) ((unsigned char) (C))
494 /* Fast boyer-moore search. */
496 bmexec (kwset_t kws
, char const *text
, size_t size
)
498 struct kwset
const *kwset
;
499 register unsigned char const *d1
;
500 register char const *ep
, *sp
, *tp
;
501 register int d
, gc
, i
, len
, md2
;
503 kwset
= (struct kwset
const *) kws
;
512 tp
= memchr (text
, kwset
->target
[0], size
);
513 return tp
? tp
- text
: -1;
517 sp
= kwset
->target
+ len
;
522 /* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */
524 /* 11 is not a bug, the initial offset happens only once. */
525 for (ep
= text
+ size
- 11 * len
;;)
529 d
= d1
[U(tp
[-1])], tp
+= d
;
530 d
= d1
[U(tp
[-1])], tp
+= d
;
533 d
= d1
[U(tp
[-1])], tp
+= d
;
534 d
= d1
[U(tp
[-1])], tp
+= d
;
535 d
= d1
[U(tp
[-1])], tp
+= d
;
538 d
= d1
[U(tp
[-1])], tp
+= d
;
539 d
= d1
[U(tp
[-1])], tp
+= d
;
540 d
= d1
[U(tp
[-1])], tp
+= d
;
543 d
= d1
[U(tp
[-1])], tp
+= d
;
544 d
= d1
[U(tp
[-1])], tp
+= d
;
550 for (i
= 3; i
<= len
&& U(tp
[-i
]) == U(sp
[-i
]); ++i
)
553 return tp
- len
- text
;
558 /* Now we have only a few characters left to search. We
559 carefully avoid ever producing an out-of-bounds pointer. */
564 d
= d1
[U((tp
+= d
)[-1])];
569 for (i
= 3; i
<= len
&& U(tp
[-i
]) == U(sp
[-i
]); ++i
)
572 return tp
- len
- text
;
580 /* Hairy multiple string search. */
582 cwexec (kwset_t kws
, char const *text
, size_t len
, struct kwsmatch
*kwsmatch
)
584 struct kwset
const *kwset
;
585 struct trie
* const *next
;
586 struct trie
const *trie
;
587 struct trie
const *accept
;
588 char const *beg
, *lim
, *mch
, *lmch
;
589 register unsigned char c
;
590 register unsigned char const *delta
;
592 register char const *end
, *qlim
;
593 register struct tree
const *tree
;
594 register char const *trans
;
598 /* Initialize register copies and look for easy ways out. */
599 kwset
= (struct kwset
*) kws
;
600 if (len
< kwset
->mind
)
603 delta
= kwset
->delta
;
604 trans
= kwset
->trans
;
607 if ((d
= kwset
->mind
) != 0)
611 mch
= text
, accept
= kwset
->trie
;
615 if (len
>= 4 * kwset
->mind
)
616 qlim
= lim
- 4 * kwset
->mind
;
620 while (lim
- end
>= d
)
622 if (qlim
&& end
<= qlim
)
625 while ((d
= delta
[c
= *end
]) && end
< qlim
)
628 end
+= delta
[(unsigned char) *end
];
629 end
+= delta
[(unsigned char) *end
];
634 d
= delta
[c
= (end
+= d
)[-1]];
647 c
= trans
? trans
[(unsigned char) *--beg
] : *--beg
;
649 while (tree
&& c
!= tree
->label
)
673 /* Given a known match, find the longest possible match anchored
674 at or before its starting point. This is nearly a verbatim
675 copy of the preceding main search loops. */
676 if (lim
- mch
> kwset
->maxd
)
677 lim
= mch
+ kwset
->maxd
;
680 while (lim
- end
>= d
)
682 if ((d
= delta
[c
= (end
+= d
)[-1]]) != 0)
685 if (!(trie
= next
[c
]))
690 if (trie
->accepting
&& beg
<= mch
)
698 c
= trans
? trans
[(unsigned char) *--beg
] : *--beg
;
700 while (tree
&& c
!= tree
->label
)
708 if (trie
->accepting
&& beg
<= mch
)
729 kwsmatch
->index
= accept
->accepting
/ 2;
730 kwsmatch
->offset
[0] = mch
- text
;
731 kwsmatch
->size
[0] = accept
->depth
;
736 /* Search through the given text for a match of any member of the
737 given keyword set. Return a pointer to the first character of
738 the matching substring, or NULL if no match is found. If FOUNDLEN
739 is non-NULL store in the referenced location the length of the
740 matching substring. Similarly, if FOUNDIDX is non-NULL, store
741 in the referenced location the index number of the particular
744 kwsexec (kwset_t kws
, char const *text
, size_t size
,
745 struct kwsmatch
*kwsmatch
)
747 struct kwset
const *kwset
= (struct kwset
*) kws
;
748 if (kwset
->words
== 1 && kwset
->trans
== 0)
750 size_t ret
= bmexec (kws
, text
, size
);
751 if (kwsmatch
!= 0 && ret
!= (size_t) -1)
754 kwsmatch
->offset
[0] = ret
;
755 kwsmatch
->size
[0] = kwset
->mind
;
760 return cwexec(kws
, text
, size
, kwsmatch
);
763 /* Free the components of the given keyword set. */
765 kwsfree (kwset_t kws
)
769 kwset
= (struct kwset
*) kws
;
770 obstack_free(&kwset
->obstack
, 0);