1 /* kwset.c - search for any of a set of keywords.
2 Copyright (C) 1989, 1998 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 extern char *xmalloc();
42 # define malloc xmalloc
45 #define NCHAR (UCHAR_MAX + 1)
46 #define obstack_chunk_alloc malloc
47 #define obstack_chunk_free free
49 /* Balanced tree of edges and labels leaving a given trie node. */
52 struct tree
*llink
; /* Left link; MUST be first field. */
53 struct tree
*rlink
; /* Right link (to larger labels). */
54 struct trie
*trie
; /* Trie node pointed to by this edge. */
55 unsigned char label
; /* Label on this edge. */
56 char balance
; /* Difference in depths of subtrees. */
59 /* Node of a trie representing a set of reversed keywords. */
62 unsigned int accepting
; /* Word index of accepted word, or zero. */
63 struct tree
*links
; /* Tree of edges leaving this node. */
64 struct trie
*parent
; /* Parent of this node. */
65 struct trie
*next
; /* List of all trie nodes in level order. */
66 struct trie
*fail
; /* Aho-Corasick failure function. */
67 int depth
; /* Depth of this node from the root. */
68 int shift
; /* Shift function for search failures. */
69 int maxshift
; /* Max shift of self and descendents. */
72 /* Structure returned opaquely to the caller, containing everything. */
75 struct obstack obstack
; /* Obstack for node allocation. */
76 int words
; /* Number of words in the trie. */
77 struct trie
*trie
; /* The trie itself. */
78 int mind
; /* Minimum depth of an accepting node. */
79 int maxd
; /* Maximum depth of any node. */
80 unsigned char delta
[NCHAR
]; /* Delta table for rapid search. */
81 struct trie
*next
[NCHAR
]; /* Table of children of the root. */
82 char *target
; /* Target string if there's only one. */
83 int mind2
; /* Used in Boyer-Moore search for one string. */
84 char *trans
; /* Character translation table. */
88 static void enqueue
PARAMS((struct tree
*, struct trie
**));
89 static void treefails
PARAMS((register struct tree
*, struct trie
*, struct trie
*));
90 static void treedelta
PARAMS((register struct tree
*,register unsigned int, unsigned char *));
91 static int hasevery
PARAMS((register struct tree
*, register struct tree
*));
92 static void treenext
PARAMS((struct tree
*, struct trie
**));
93 static char * bmexec
PARAMS((kwset_t
, char *, size_t));
94 static char * cwexec
PARAMS((kwset_t
, char *, size_t, struct kwsmatch
*));
96 /* Allocate and initialize a keyword set object, returning an opaque
97 pointer to it. Return NULL if memory is not available. */
99 kwsalloc (char *trans
)
103 kwset
= (struct kwset
*) malloc(sizeof (struct kwset
));
107 obstack_init(&kwset
->obstack
);
110 = (struct trie
*) obstack_alloc(&kwset
->obstack
, sizeof (struct trie
));
113 kwsfree((kwset_t
) kwset
);
116 kwset
->trie
->accepting
= 0;
117 kwset
->trie
->links
= 0;
118 kwset
->trie
->parent
= 0;
119 kwset
->trie
->next
= 0;
120 kwset
->trie
->fail
= 0;
121 kwset
->trie
->depth
= 0;
122 kwset
->trie
->shift
= 0;
123 kwset
->mind
= INT_MAX
;
126 kwset
->trans
= trans
;
128 return (kwset_t
) kwset
;
131 /* Add the given string to the contents of the keyword set. Return NULL
132 for success, an error message otherwise. */
134 kwsincr (kwset_t kws
, char *text
, size_t len
)
137 register struct trie
*trie
;
138 register unsigned char label
;
139 register struct tree
*link
;
141 struct tree
*links
[12];
142 enum { L
, R
} dirs
[12];
143 struct tree
*t
, *r
, *l
, *rl
, *lr
;
145 kwset
= (struct kwset
*) kws
;
149 /* Descend the trie (built of reversed keywords) character-by-character,
150 installing new nodes when necessary. */
153 label
= kwset
->trans
? kwset
->trans
[(unsigned char) *--text
] : *--text
;
155 /* Descend the tree of outgoing links for this trie node,
156 looking for the current character and keeping track
157 of the path followed. */
159 links
[0] = (struct tree
*) &trie
->links
;
163 while (link
&& label
!= link
->label
)
166 if (label
< link
->label
)
167 dirs
[depth
++] = L
, link
= link
->llink
;
169 dirs
[depth
++] = R
, link
= link
->rlink
;
172 /* The current character doesn't have an outgoing link at
173 this trie node, so build a new trie node and install
174 a link in the current trie node's tree. */
177 link
= (struct tree
*) obstack_alloc(&kwset
->obstack
,
178 sizeof (struct tree
));
180 return _("memory exhausted");
183 link
->trie
= (struct trie
*) obstack_alloc(&kwset
->obstack
,
184 sizeof (struct trie
));
186 return _("memory exhausted");
187 link
->trie
->accepting
= 0;
188 link
->trie
->links
= 0;
189 link
->trie
->parent
= trie
;
190 link
->trie
->next
= 0;
191 link
->trie
->fail
= 0;
192 link
->trie
->depth
= trie
->depth
+ 1;
193 link
->trie
->shift
= 0;
197 /* Install the new tree node in its parent. */
198 if (dirs
[--depth
] == L
)
199 links
[depth
]->llink
= link
;
201 links
[depth
]->rlink
= link
;
203 /* Back up the tree fixing the balance flags. */
204 while (depth
&& !links
[depth
]->balance
)
206 if (dirs
[depth
] == L
)
207 --links
[depth
]->balance
;
209 ++links
[depth
]->balance
;
213 /* Rebalance the tree by pointer rotations if necessary. */
214 if (depth
&& ((dirs
[depth
] == L
&& --links
[depth
]->balance
)
215 || (dirs
[depth
] == R
&& ++links
[depth
]->balance
)))
217 switch (links
[depth
]->balance
)
220 switch (dirs
[depth
+ 1])
223 r
= links
[depth
], t
= r
->llink
, rl
= t
->rlink
;
224 t
->rlink
= r
, r
->llink
= rl
;
225 t
->balance
= r
->balance
= 0;
228 r
= links
[depth
], l
= r
->llink
, t
= l
->rlink
;
229 rl
= t
->rlink
, lr
= t
->llink
;
230 t
->llink
= l
, l
->rlink
= lr
, t
->rlink
= r
, r
->llink
= rl
;
231 l
->balance
= t
->balance
!= 1 ? 0 : -1;
232 r
->balance
= t
->balance
!= (char) -1 ? 0 : 1;
240 switch (dirs
[depth
+ 1])
243 l
= links
[depth
], t
= l
->rlink
, lr
= t
->llink
;
244 t
->llink
= l
, l
->rlink
= lr
;
245 t
->balance
= l
->balance
= 0;
248 l
= links
[depth
], r
= l
->rlink
, t
= r
->llink
;
249 lr
= t
->llink
, rl
= t
->rlink
;
250 t
->llink
= l
, l
->rlink
= lr
, t
->rlink
= r
, r
->llink
= rl
;
251 l
->balance
= t
->balance
!= 1 ? 0 : -1;
252 r
->balance
= t
->balance
!= (char) -1 ? 0 : 1;
263 if (dirs
[depth
- 1] == L
)
264 links
[depth
- 1]->llink
= t
;
266 links
[depth
- 1]->rlink
= t
;
273 /* Mark the node we finally reached as accepting, encoding the
274 index number of this word in the keyword set so far. */
275 if (!trie
->accepting
)
276 trie
->accepting
= 1 + 2 * kwset
->words
;
279 /* Keep track of the longest and shortest string of the keyword set. */
280 if (trie
->depth
< kwset
->mind
)
281 kwset
->mind
= trie
->depth
;
282 if (trie
->depth
> kwset
->maxd
)
283 kwset
->maxd
= trie
->depth
;
288 /* Enqueue the trie nodes referenced from the given tree in the
291 enqueue (struct tree
*tree
, struct trie
**last
)
295 enqueue(tree
->llink
, last
);
296 enqueue(tree
->rlink
, last
);
297 (*last
) = (*last
)->next
= tree
->trie
;
300 /* Compute the Aho-Corasick failure function for the trie nodes referenced
301 from the given tree, given the failure function for their parent as
302 well as a last resort failure node. */
304 treefails (register struct tree
*tree
, struct trie
*fail
, struct trie
*recourse
)
306 register struct tree
*link
;
311 treefails(tree
->llink
, fail
, recourse
);
312 treefails(tree
->rlink
, fail
, recourse
);
314 /* Find, in the chain of fails going back to the root, the first
315 node that has a descendent on the current label. */
319 while (link
&& tree
->label
!= link
->label
)
320 if (tree
->label
< link
->label
)
326 tree
->trie
->fail
= link
->trie
;
332 tree
->trie
->fail
= recourse
;
335 /* Set delta entries for the links of the given tree such that
336 the preexisting delta value is larger than the current depth. */
338 treedelta (register struct tree
*tree
,
339 register unsigned int depth
,
340 unsigned char delta
[])
344 treedelta(tree
->llink
, depth
, delta
);
345 treedelta(tree
->rlink
, depth
, delta
);
346 if (depth
< delta
[tree
->label
])
347 delta
[tree
->label
] = depth
;
350 /* Return true if A has every label in B. */
352 hasevery (register struct tree
*a
, register struct tree
*b
)
356 if (!hasevery(a
, b
->llink
))
358 if (!hasevery(a
, b
->rlink
))
360 while (a
&& b
->label
!= a
->label
)
361 if (b
->label
< a
->label
)
368 /* Compute a vector, indexed by character code, of the trie nodes
369 referenced from the given tree. */
371 treenext (struct tree
*tree
, struct trie
*next
[])
375 treenext(tree
->llink
, next
);
376 treenext(tree
->rlink
, next
);
377 next
[tree
->label
] = tree
->trie
;
380 /* Compute the shift for each trie node, as well as the delta
381 table and next cache for the given keyword set. */
383 kwsprep (kwset_t kws
)
385 register struct kwset
*kwset
;
387 register struct trie
*curr
, *fail
;
388 register char *trans
;
389 unsigned char delta
[NCHAR
];
390 struct trie
*last
, *next
[NCHAR
];
392 kwset
= (struct kwset
*) kws
;
394 /* Initial values for the delta table; will be changed later. The
395 delta entry for a given character is the smallest depth of any
396 node at which an outgoing edge is labeled by that character. */
397 if (kwset
->mind
< 256)
398 for (i
= 0; i
< NCHAR
; ++i
)
399 delta
[i
] = kwset
->mind
;
401 for (i
= 0; i
< NCHAR
; ++i
)
404 /* Check if we can use the simple boyer-moore algorithm, instead
405 of the hairy commentz-walter algorithm. */
406 if (kwset
->words
== 1 && kwset
->trans
== 0)
408 /* Looking for just one string. Extract it from the trie. */
409 kwset
->target
= obstack_alloc(&kwset
->obstack
, kwset
->mind
);
410 for (i
= kwset
->mind
- 1, curr
= kwset
->trie
; i
>= 0; --i
)
412 kwset
->target
[i
] = curr
->links
->label
;
413 curr
= curr
->links
->trie
;
415 /* Build the Boyer Moore delta. Boy that's easy compared to CW. */
416 for (i
= 0; i
< kwset
->mind
; ++i
)
417 delta
[(unsigned char) kwset
->target
[i
]] = kwset
->mind
- (i
+ 1);
418 kwset
->mind2
= kwset
->mind
;
419 /* Find the minimal delta2 shift that we might make after
420 a backwards match has failed. */
421 for (i
= 0; i
< kwset
->mind
- 1; ++i
)
422 if (kwset
->target
[i
] == kwset
->target
[kwset
->mind
- 1])
423 kwset
->mind2
= kwset
->mind
- (i
+ 1);
427 /* Traverse the nodes of the trie in level order, simultaneously
428 computing the delta table, failure function, and shift function. */
429 for (curr
= last
= kwset
->trie
; curr
; curr
= curr
->next
)
431 /* Enqueue the immediate descendents in the level order queue. */
432 enqueue(curr
->links
, &last
);
434 curr
->shift
= kwset
->mind
;
435 curr
->maxshift
= kwset
->mind
;
437 /* Update the delta table for the descendents of this node. */
438 treedelta(curr
->links
, curr
->depth
, delta
);
440 /* Compute the failure function for the decendents of this node. */
441 treefails(curr
->links
, curr
->fail
, kwset
->trie
);
443 /* Update the shifts at each node in the current node's chain
444 of fails back to the root. */
445 for (fail
= curr
->fail
; fail
; fail
= fail
->fail
)
447 /* If the current node has some outgoing edge that the fail
448 doesn't, then the shift at the fail should be no larger
449 than the difference of their depths. */
450 if (!hasevery(fail
->links
, curr
->links
))
451 if (curr
->depth
- fail
->depth
< fail
->shift
)
452 fail
->shift
= curr
->depth
- fail
->depth
;
454 /* If the current node is accepting then the shift at the
455 fail and its descendents should be no larger than the
456 difference of their depths. */
457 if (curr
->accepting
&& fail
->maxshift
> curr
->depth
- fail
->depth
)
458 fail
->maxshift
= curr
->depth
- fail
->depth
;
462 /* Traverse the trie in level order again, fixing up all nodes whose
463 shift exceeds their inherited maxshift. */
464 for (curr
= kwset
->trie
->next
; curr
; curr
= curr
->next
)
466 if (curr
->maxshift
> curr
->parent
->maxshift
)
467 curr
->maxshift
= curr
->parent
->maxshift
;
468 if (curr
->shift
> curr
->maxshift
)
469 curr
->shift
= curr
->maxshift
;
472 /* Create a vector, indexed by character code, of the outgoing links
473 from the root node. */
474 for (i
= 0; i
< NCHAR
; ++i
)
476 treenext(kwset
->trie
->links
, next
);
478 if ((trans
= kwset
->trans
) != 0)
479 for (i
= 0; i
< NCHAR
; ++i
)
480 kwset
->next
[i
] = next
[(unsigned char) trans
[i
]];
482 for (i
= 0; i
< NCHAR
; ++i
)
483 kwset
->next
[i
] = next
[i
];
486 /* Fix things up for any translation table. */
487 if ((trans
= kwset
->trans
) != 0)
488 for (i
= 0; i
< NCHAR
; ++i
)
489 kwset
->delta
[i
] = delta
[(unsigned char) trans
[i
]];
491 for (i
= 0; i
< NCHAR
; ++i
)
492 kwset
->delta
[i
] = delta
[i
];
497 #define U(C) ((unsigned char) (C))
499 /* Fast boyer-moore search. */
501 bmexec (kwset_t kws
, char *text
, size_t size
)
504 register unsigned char *d1
;
505 register char *ep
, *sp
, *tp
;
506 register int d
, gc
, i
, len
, md2
;
508 kwset
= (struct kwset
*) kws
;
516 return memchr(text
, kwset
->target
[0], size
);
519 sp
= kwset
->target
+ len
;
524 /* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */
526 /* 11 is not a bug, the initial offset happens only once. */
527 for (ep
= text
+ size
- 11 * len
;;)
531 d
= d1
[U(tp
[-1])], tp
+= d
;
532 d
= d1
[U(tp
[-1])], tp
+= d
;
535 d
= d1
[U(tp
[-1])], tp
+= d
;
536 d
= d1
[U(tp
[-1])], tp
+= d
;
537 d
= d1
[U(tp
[-1])], tp
+= d
;
540 d
= d1
[U(tp
[-1])], tp
+= d
;
541 d
= d1
[U(tp
[-1])], tp
+= d
;
542 d
= d1
[U(tp
[-1])], tp
+= d
;
545 d
= d1
[U(tp
[-1])], tp
+= d
;
546 d
= d1
[U(tp
[-1])], tp
+= d
;
552 for (i
= 3; i
<= len
&& U(tp
[-i
]) == U(sp
[-i
]); ++i
)
560 /* Now we have only a few characters left to search. We
561 carefully avoid ever producing an out-of-bounds pointer. */
566 d
= d1
[U((tp
+= d
)[-1])];
571 for (i
= 3; i
<= len
&& U(tp
[-i
]) == U(sp
[-i
]); ++i
)
582 /* Hairy multiple string search. */
584 cwexec (kwset_t kws
, char *text
, size_t len
, struct kwsmatch
*kwsmatch
)
587 struct trie
**next
, *trie
, *accept
;
588 char *beg
, *lim
, *mch
, *lmch
;
589 register unsigned char c
, *delta
;
591 register char *end
, *qlim
;
592 register struct tree
*tree
;
593 register char *trans
;
599 /* Initialize register copies and look for easy ways out. */
600 kwset
= (struct kwset
*) kws
;
601 if (len
< kwset
->mind
)
604 delta
= kwset
->delta
;
605 trans
= kwset
->trans
;
608 if ((d
= kwset
->mind
) != 0)
612 mch
= text
, accept
= kwset
->trie
;
616 if (len
>= 4 * kwset
->mind
)
617 qlim
= lim
- 4 * kwset
->mind
;
621 while (lim
- end
>= d
)
623 if (qlim
&& end
<= qlim
)
626 while ((d
= delta
[c
= *end
]) && end
< qlim
)
629 end
+= delta
[(unsigned char) *end
];
630 end
+= delta
[(unsigned char) *end
];
635 d
= delta
[c
= (end
+= d
)[-1]];
648 c
= trans
? trans
[(unsigned char) *--beg
] : *--beg
;
650 while (tree
&& c
!= tree
->label
)
674 /* Given a known match, find the longest possible match anchored
675 at or before its starting point. This is nearly a verbatim
676 copy of the preceding main search loops. */
677 if (lim
- mch
> kwset
->maxd
)
678 lim
= mch
+ kwset
->maxd
;
681 while (lim
- end
>= d
)
683 if ((d
= delta
[c
= (end
+= d
)[-1]]) != 0)
686 if (!(trie
= next
[c
]))
691 if (trie
->accepting
&& beg
<= mch
)
699 c
= trans
? trans
[(unsigned char) *--beg
] : *--beg
;
701 while (tree
&& c
!= tree
->label
)
709 if (trie
->accepting
&& beg
<= mch
)
730 kwsmatch
->index
= accept
->accepting
/ 2;
731 kwsmatch
->beg
[0] = mch
;
732 kwsmatch
->size
[0] = accept
->depth
;
737 /* Search through the given text for a match of any member of the
738 given keyword set. Return a pointer to the first character of
739 the matching substring, or NULL if no match is found. If FOUNDLEN
740 is non-NULL store in the referenced location the length of the
741 matching substring. Similarly, if FOUNDIDX is non-NULL, store
742 in the referenced location the index number of the particular
745 kwsexec (kwset_t kws
, char *text
, size_t size
, struct kwsmatch
*kwsmatch
)
750 kwset
= (struct kwset
*) kws
;
751 if (kwset
->words
== 1 && kwset
->trans
== 0)
753 ret
= bmexec(kws
, text
, size
);
754 if (kwsmatch
!= 0 && ret
!= 0)
757 kwsmatch
->beg
[0] = ret
;
758 kwsmatch
->size
[0] = kwset
->mind
;
763 return cwexec(kws
, text
, size
, kwsmatch
);
766 /* Free the components of the given keyword set. */
768 kwsfree (kwset_t kws
)
772 kwset
= (struct kwset
*) kws
;
773 obstack_free(&kwset
->obstack
, 0);