pax_global_header00006660000000000000000000000064137167573600014531gustar00rootroot0000000000000052 comment=15b437cda5406f6854d7a39605f4562a195575cf esmre-0.5.2/000077500000000000000000000000001371675736000126505ustar00rootroot00000000000000esmre-0.5.2/.gitignore000066400000000000000000000000711371675736000146360ustar00rootroot00000000000000build dist *.egg-info *.pyc *.so .venv/ .eggs/ src/esm.c esmre-0.5.2/AUTHORS000066400000000000000000000000451371675736000137170ustar00rootroot00000000000000Will Harris esmre-0.5.2/COPYING000066400000000000000000000635041371675736000137130ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! esmre-0.5.2/INSTALL000066400000000000000000000005201371675736000136760ustar00rootroot00000000000000Installing esmre ================ To install esmre, type the following: python setup.py install This will install the esm and esmre modules in the site-packages for the Python interpreter you used to run the command. You can test the installation by typing the following: python test/esm_tests.py && python test/esmre_tests.py esmre-0.5.2/MANIFEST.in000066400000000000000000000002211371675736000144010ustar00rootroot00000000000000include AUTHORS include COPYING include INSTALL include MANIFEST.in include src/esm.pyx include src/aho_corasick.pxd recursive-include src/esm * esmre-0.5.2/README.md000066400000000000000000000032751371675736000141360ustar00rootroot00000000000000esmre - Efficient String Matching Regular Expressions ===================================================== esmre is a Python module that can be used to speed up the execution of a large collection of regular expressions. It works by building a index of compulsory substrings from a collection of regular expressions, which it uses to quickly exclude those expressions which trivially do not match each input. Here is some example code that uses esmre: ```pycon >>> import esmre >>> index = esmre.Index() >>> index.enter(r"Major-General\W*$", "savoy opera") >>> index.enter(r"\bway\W+haye?\b", "sea shanty") >>> index.query("I am the very model of a modern Major-General.") ['savoy opera'] >>> index.query("Way, hay up she rises,") ['sea shanty'] >>> ``` The esmre module builds on the simpler string matching facilities of the esm module, which wraps a C implementation some of the algorithms described in Aho's and Corasick's paper on efficient string matching [Aho, A.V, and Corasick, M. J. Efficient String Matching: An Aid to Bibliographic Search. Comm. ACM 18:6 (June 1975), 333-340]. Some minor modifications have been made to the algorithms in the paper and one algorithm is missing (for now), but there is enough to implement a quick string matching index. Here is some example code that uses esm directly: ```pycon >>> import esm >>> index = esm.Index() >>> index.enter("he") >>> index.enter("she") >>> index.enter("his") >>> index.enter("hers") >>> index.fix() >>> index.query("this here is history") [((1, 4), 'his'), ((5, 7), 'he'), ((13, 16), 'his')] >>> index.query("Those are his sheep!") [((10, 13), 'his'), ((14, 17), 'she'), ((15, 17), 'he')] >>> ``` You can see more usage examples in the tests. esmre-0.5.2/pyproject.toml000066400000000000000000000000741371675736000155650ustar00rootroot00000000000000[build-system] requires = ["setuptools", "wheel", "Cython"] esmre-0.5.2/setup.py000066400000000000000000000040351371675736000143640ustar00rootroot00000000000000# setup.py - distutils configuration for esm and esmre modules # Copyright (C) 2007 Tideway Systems Limited. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 # USA from setuptools import setup, Extension from Cython.Build import cythonize module1 = Extension( "esm", ["src/esm.pyx", "src/esm/aho_corasick.c", "src/esm/ac_list.c"] ) with open("README.md", "r") as readme: long_description = readme.read() setup( name="esmre", version="0.5.2", description="Regular expression accelerator", long_description=long_description, long_description_content_type="text/markdown", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: " "GNU Library or Lesser General Public License (LGPL)", "Operating System :: POSIX", "Programming Language :: C", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Indexing", ], install_requires=["setuptools"], author="Will Harris", author_email="esmre@greatlibrary.net", url="http://code.google.com/p/esmre/", license="GNU LGPL", platforms=["POSIX"], ext_modules=cythonize([module1]), package_dir={"": "src"}, py_modules=["esmre"], test_suite="nose.collector", tests_require="nose", ) esmre-0.5.2/src/000077500000000000000000000000001371675736000134375ustar00rootroot00000000000000esmre-0.5.2/src/aho_corasick.pxd000066400000000000000000000024311371675736000166010ustar00rootroot00000000000000cdef extern from "esm/aho_corasick.h": ctypedef enum ac_error_code: AC_SUCCESS = 0 AC_FAILURE = 1 ctypedef ac_error_code (*ac_free_function)(void *item, void *data) ctypedef int ac_offset ctypedef struct ac_result: ac_offset start ac_offset end void *object ctypedef ac_error_code (*ac_result_callback)(void* result_cb_data, ac_result* result) ctypedef struct ac_index_s: pass ctypedef ac_index_s* ac_index ac_index ac_index_new() ac_error_code ac_index_free(ac_index self, ac_free_function object_free) ac_error_code ac_index_enter(ac_index self, char* keyword, ac_offset size, void* object) ac_error_code ac_index_fix(ac_index self) bint ac_index_fixed(ac_index self) ac_error_code ac_index_query_cb(ac_index self, char* phrase, ac_offset size, ac_result_callback result_cb, void* result_cb_data) cdef extern from "Python.h": void Py_IncRef(obj) void Py_DecRef(obj) esmre-0.5.2/src/esm.pyx000066400000000000000000000043171371675736000147720ustar00rootroot00000000000000cimport aho_corasick cdef aho_corasick.ac_error_code decref_result_object(void *item, void* data): aho_corasick.Py_DecRef(item) return aho_corasick.AC_SUCCESS cdef aho_corasick.ac_error_code append_result(void* data, aho_corasick.ac_result* result): result_list = data result_tuple = ((result.start, result.end), result.object) result_list.append(result_tuple) return aho_corasick.AC_SUCCESS cdef text_as_bytes(text): if type(text) is unicode: return text.encode('utf8') else: return text cdef class Index: cdef aho_corasick.ac_index _index def __cinit__(self): self._index = aho_corasick.ac_index_new() if self._index is NULL: raise MemoryError() def __dealloc__(self): aho_corasick.ac_index_free(self._index, decref_result_object) def enter(self, keyword, obj=None): if obj is None: obj = keyword keyword = text_as_bytes(keyword) if aho_corasick.ac_index_fixed(self._index): raise TypeError("Can't call enter after fix") if aho_corasick.ac_index_enter(self._index, keyword, len(keyword), obj) != aho_corasick.AC_SUCCESS: raise MemoryError() aho_corasick.Py_IncRef(obj) def fix(self): if aho_corasick.ac_index_fixed(self._index): raise TypeError("Can't call fix repeatedly") if aho_corasick.ac_index_fix(self._index) != aho_corasick.AC_SUCCESS: raise MemoryError() def query(self, phrase): if not aho_corasick.ac_index_fixed(self._index): raise TypeError("Can't call query before fix") phrase = text_as_bytes(phrase) result_list = [] status = aho_corasick.ac_index_query_cb(self._index, phrase, len(phrase), append_result, result_list) if status != aho_corasick.AC_SUCCESS: raise MemoryError() return result_list esmre-0.5.2/src/esm/000077500000000000000000000000001371675736000142235ustar00rootroot00000000000000esmre-0.5.2/src/esm/ac_list.c000066400000000000000000000065251371675736000160150ustar00rootroot00000000000000/* ac_list.c - functions for linked lists Copyright (C) 2007 Tideway Systems Limited. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "ac_list.h" #include /** * Make a new, empty linked list. Returns a pointer to a list or NULL if an * error was encountered allocating heap space for the structure. */ ac_list *ac_list_new(void) { ac_list *self = NULL; if ((self = malloc(sizeof(ac_list)))) { self->first = NULL; self->last = NULL; } return self; } /** * Free a list item. Pass a pointer to this function to ac_list_free when you * want only the heap space for the list items themselves will be freed. * Always returns AC_SUCCESS. */ ac_error_code ac_list_free_simple_item(void *item, void *data) { free(item); return AC_SUCCESS; } /** * NOP list item free function. Pass a pointer to this function to * ac_list_free when you don't want the heap space for the list items to be * freed. */ ac_error_code ac_list_free_keep_item(void *item, void *data) { return AC_SUCCESS; } /** * Free the ac_list at self. Heap space allocated for the list will be freed. * A function pointer should be provided in free_item for freeing resources * allocated for the items themselves. The function at free_item is called * once for each item added to the list. It is passed a pointer to the item * and workspace data pointer (given to ac_list_free in free_data). * passed to ac_list_free in free_data. The free_item function should return * AC_SUCCESS if it succeeds or AC_FAILURE if it fails. * * Returns AC_SUCCESS if all the free_item calls succeed of AC_FAILURE if self * is NULL, or if any of the free_item calls fail. */ ac_error_code ac_list_free(ac_list *self, ac_free_function free_item, void *free_data) { ac_list_item *list_item = NULL; ac_list_item *tmp = NULL; ac_error_code result = AC_SUCCESS; if (!self) { return AC_FAILURE; } list_item = self->first; while (list_item) { tmp = list_item->next; if (free_item(list_item->item, free_data) != AC_SUCCESS) { result = AC_FAILURE; } free(list_item); list_item = tmp; } free(self); return result; } /** * Add an item to a list. The item at item is appended to the list at self. * Returns AC_SUCCESS if successful or AC_FAILURE if an error is encountered * allocating heap space for the internal list item structure. */ ac_error_code ac_list_add(ac_list *self, void *item) { ac_list_item *new_list_item; if (!(new_list_item = malloc(sizeof(ac_list_item)))) { return AC_FAILURE; } new_list_item->item = item; new_list_item->next = NULL; if (!self->first) { self->first = new_list_item; } if (self->last) { self->last->next = new_list_item; } self->last = new_list_item; return AC_SUCCESS; } esmre-0.5.2/src/esm/ac_list.h000066400000000000000000000031661371675736000160200ustar00rootroot00000000000000/* ac_list.h - declarations for linked list functions Copyright (C) 2007 Tideway Systems Limited. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * Header for linked list implementation. */ #include "aho_corasick.h" #ifndef AC_LIST_H #define AC_LIST_H /** Structure for internal list items. */ typedef struct ac_list_item { /** Pointer to the item itself. */ void *item; /** Pointer to the next ac_list_item or NULL of this is the last item. */ struct ac_list_item *next; } ac_list_item; /** Structure for linked list. */ typedef struct { /** Pointer to first list item. */ ac_list_item *first; /** Pointer to last list item. */ ac_list_item *last; } ac_list; ac_list *ac_list_new(void); ac_error_code ac_list_free(ac_list *, ac_free_function, void *); ac_error_code ac_list_add(ac_list *, void *); /* Simple item freeing methods. */ ac_error_code ac_list_free_simple_item(void *, void *); ac_error_code ac_list_free_keep_item(void *, void *); #endif /* AC_LIST_H */ esmre-0.5.2/src/esm/aho_corasick.c000066400000000000000000000512711371675736000170220ustar00rootroot00000000000000/* aho_corasick.c - Aho Corasick implementations Copyright (C) 2007 Tideway Systems Limited. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* This file contains implementations of some of the algorithms for efficient * string matching described in the paper, 'Aho, A.V, and Corasick, M. J. * Efficient String Matching: An Aid to Bibliographic Search. Comm. ACM 18:6 * (June 1975), 333-340', hereafter referred to as 'the paper.' * * The paper describes algorithms (Algorithm 2 and Algorithm 3) for * contructing the functions of a finite state machine from a set of keywords * and an algorithm (Algorithm 1) for running that machine against an input * string to output the occurences of the keywords in the input string. * * The paper also describes an algorithm (Algorithm 4) for eliminating the * failure function to create a deterministic finite automaton that makes * exactly one state transition per input symbol, but I have chosen not to * implement that algorithm. * * I have moved the code that implements the last part of Algorithm 2 (the * part that completes the goto function for the root state) into the function * that implements Algorithm 3. I have also made the loop over the set of * keywords the responsibilty of the user, leaving only Algorithm 2's 'enter' * procedure. These changes allow for a simple API where the user can create * an index with ac_index_new, add keywords with associated object to the * index with ac_index_enter (Algorithm 2's 'enter' procedure), then fix the * index with ac_index_fix (Algorithm 3 prefixed with the end of Algorithm 2) * before querying it with ac_index_query (Algorithm 1) and freeing it with * ac_index_free (not covered in the paper). */ #include "aho_corasick.h" #include "ac_list.h" #include #include #include /** * Interface states for an index objects. */ typedef enum ac_index_state { /** * The index is 'unfixed'. New keywords can be entered but the index * cannot be queried. */ AC_INDEX_UNFIXED, /** * The index in 'fixed'. The index can be queried but new keywords * cannot be entered. */ AC_INDEX_FIXED } ac_index_state; /** * Structure for index objects. */ struct ac_index_s { /** The interface state of the index. */ ac_index_state index_state; /** The top state node of the index's patten matching machine. */ struct ac_state *state_0; }; /** * Structure for a state in an Aho-Corasick pattern matching machine. The * structure holds the data for the the goto, failure and output functions for * a single state. In the paper, states are identified by a sequential integer * but this implementation uses the pointer to an ac_state structure. * * The data for the output function is split into two lists. One (outputs) is * built when keywords are entered into the index. The other (extra_outputs) * is built when the index is fixed. */ typedef struct ac_state { /** * List of ac_goto structures used to evaluate the goto function for * this state. */ ac_list *gotos; /** * List of ac_output structures that are part of the result of the * output function for this state. Items are added to these lists when * keywords are entered. */ ac_list *outputs; /** * List of ac_output structures that are part of the result of the * output function for this state. Items are added to this list when * the index is fixed. */ ac_list *extra_outputs; /** * Result of failure function for this state. */ struct ac_state *failure; } ac_state; // -------------------------------------------------------------------------- // Goto list /** * Structure mapping a symbol to a state, forming part of the goto function * data for a state. */ typedef struct ac_goto { char symbol; ac_state *state; } ac_goto; /** * Shared workspace used by ac_goto_list_free_item. */ typedef struct ac_goto_list_free_data { /** * List of states to free. When the index is freed, as we iterate over * the goto lists to free them, we add to a list of of state objects * that will need to be freed later. */ ac_list *states; /** * State that should not be added to the list above. When a goto item * is encountered that points to this state it is not added to the * list. This lets us cover the special case goto function of the root * state, which can goto itself. */ ac_state *state; } ac_goto_list_free_data; /** * List free function for goto list items. This will be called once per * ac_goto in the list. The data should be an ac_goto_list_free_data as * explained above. The states in the list are added to the list in data * except where the state matches the state in data. * * Returns AC_SUCCESS if successful or AC_FAILURE if a failure is encountered * when adding a state to the list. */ ac_error_code ac_goto_list_free_item(void *item, void *data) { ac_goto *goto_item = (ac_goto *) item; ac_goto_list_free_data *free_data = (ac_goto_list_free_data *) data; /* Add the state from the goto item to the list unless it is excluded. */ if (goto_item->state != free_data->state && ac_list_add(free_data->states, goto_item->state) != AC_SUCCESS) { return AC_FAILURE; } free(item); return AC_SUCCESS; } /** * Free a goto list, appending the states that do not match the state argument * to the list at states. Returns AC_SUCCESS if successful or AC_FAILURE * otherwise. */ ac_error_code ac_goto_list_free(ac_list *self, ac_list *states, ac_state *state) { ac_goto_list_free_data free_data = {states, state}; return ac_list_free(self, ac_goto_list_free_item, &free_data); } /** * Search a goto list for the state associated with the given symbol. Return * a pointer to the state if it is found or NULL if not. */ ac_state *ac_goto_list_get(ac_list *self, char symbol) { ac_list_item *list_item = self->first; ac_goto *item = NULL; while (list_item) { item = (ac_goto *) list_item->item; if (item->symbol == symbol) { return item->state; } list_item = list_item->next; } return NULL; } /** * Determine whether a goto list has an association for the given symbol. */ bool ac_goto_list_has(ac_list *self, char symbol) { return ac_goto_list_get(self, symbol) != NULL; } /** * Associates the given symbol with the given state in a goto list. Returns * AC_SUCCESS if successful or AC_FAILURE if an error was encountered. */ ac_error_code ac_goto_list_add(ac_list *self, char symbol, ac_state *state) { ac_goto *new_item; if (!(new_item = malloc(sizeof(ac_goto)))) { return AC_FAILURE; } new_item->symbol = symbol; new_item->state = state; if (ac_list_add(self, new_item) != AC_SUCCESS) { free(new_item); return AC_FAILURE; } return AC_SUCCESS; } // -------------------------------------------------------------------------- // Output list /** * Structure holding the data for one item in the output function for a state. */ typedef struct ac_output { /** * The length of the keyword that matches at the state. We use this to * generate the index span of the query string that contains the * keyword. */ ac_offset offset; /** An object assocated with the state. */ void *object; } ac_output; /** * Structure holding the function pointer needed to free the the object * associated with an ac_output. */ struct ac_output_list_free_item_data { ac_free_function free_fn; }; /** * List item free function for ac_output items. This funciton will be called * once for each item in each output list. The item argument points to the * ac_output being freed. The data argument points to a struct * ac_output_list_free_item_data holding a function for freeing the associated * object. * * Returns the result of the function for freeing the associated object. */ ac_error_code ac_output_list_free_item(void *item, void *data) { ac_output *output = (ac_output *) item; ac_error_code result; struct ac_output_list_free_item_data *item_data = data; result = item_data->free_fn(output->object, NULL); // TODO: let user pass data to free function free(output); return result; } /** * Free the output list, calling object_free on the associated object of * each output item. */ void ac_output_list_free(ac_list *self, ac_free_function object_free) { struct ac_output_list_free_item_data data = {.free_fn = object_free}; (void) ac_list_free(self, ac_output_list_free_item, &data); } /** * Add an offset and an associated object to the output list. Returns * AC_SUCCESS if successful, or AC_FAILURE if the there was an error was * encountered. */ ac_error_code ac_output_list_add(ac_list *self, ac_offset offset, void *object) { ac_output *new_item; if (!(new_item = malloc(sizeof(ac_output)))) { return AC_FAILURE; } new_item->offset = offset; new_item->object = object; if (ac_list_add(self, new_item) != AC_SUCCESS) { free(new_item); return AC_FAILURE; } return AC_SUCCESS; } /** * Add the contents of the output list in other to the output list in self. * Returns AC_SUCCESS if successful or AC_FAILURE if an error was encountered. */ ac_error_code ac_output_list_add_list(ac_list *self, ac_list *other) { ac_list_item *list_item = other->first; ac_output *item = NULL; while (list_item) { item = (ac_output *) list_item->item; if (ac_output_list_add(self, item->offset, item->object) != AC_SUCCESS) { return AC_FAILURE; } list_item = list_item->next; } return AC_SUCCESS; } // -------------------------------------------------------------------------- // Callbacks /** * Call the callback with an single result. Returns AC_SUCCESS if successful, * or AC_FAILURE if the there was an error was encountered. */ ac_error_code ac_cb_output(ac_result_callback result_cb, void *result_cb_data, ac_offset start, ac_offset end, void *object) { ac_result new_item = {.start = start, .end = end, .object = object}; return result_cb(result_cb_data, &new_item); } /** * Send each item in the output list to the callback. * Returns AC_SUCCESS if successful or AC_FAILURE if an error was encountered. */ ac_error_code ac_cb_outputs(ac_result_callback result_cb, void *result_cb_data, ac_list *outputs, ac_offset end) { ac_list_item *list_item = NULL; ac_output *item = NULL; list_item = outputs->first; while (list_item) { item = (ac_output *) list_item->item; if (ac_cb_output(result_cb, result_cb_data, end - item->offset + 1, end + 1, item->object) != AC_SUCCESS) { return AC_FAILURE; } list_item = list_item->next; } return AC_SUCCESS; } // -------------------------------------------------------------------------- // State object /** * Construct a new state object. The goto list and the both output lists are * initially empty, and the failure state is initially NULL. Returns a pointer * to the new state object if successful or NULL if an error was encountered * while trying to allocate heap space for the object or while constructing * one of its lists. */ ac_state *ac_state_new(void) { ac_state *self; if (!(self = malloc(sizeof(ac_state)))) { return NULL; } if (!(self->gotos = ac_list_new())) { return NULL; } if (!(self->outputs = ac_list_new())) { return NULL; } if (!(self->extra_outputs = ac_list_new())) { return NULL; } self->failure = NULL; return self; } /** * Free the state object. Any states in the goto list will be added to the * state queue in the children argument. Relavent associated objects from the * output list will be freed by calling the object_free argument. Returns * AC_SUCCESS if sucessful, or AC_FAILURE if an error was encountered. */ ac_error_code ac_state_free(ac_state *self, ac_list *children, ac_free_function object_free) { if (!self) { return AC_FAILURE; } if (ac_goto_list_free(self->gotos, children, self) != AC_SUCCESS) { return AC_FAILURE; } // We need to call object_free for the associated objects in outputs, // but must not call object_free for the extra_outputs. ac_output_list_free(self->outputs, object_free); ac_output_list_free(self->extra_outputs, ac_list_free_keep_item); free(self); return AC_SUCCESS; } // -------------------------------------------------------------------------- // State queue /** * Free the state queue. */ void ac_state_queue_free(ac_list *self) { (void) ac_list_free(self, ac_list_free_keep_item, NULL); } /** * Pop the next item from the state queue. Returns a pointer to the popped * item if successful or NULL if the queue was empty. */ ac_state *ac_state_queue_get(ac_list *self) { ac_state *result = NULL; ac_list_item *next = NULL; if (self && self->first) { result = (ac_state *) self->first->item; next = self->first->next; free(self->first); self->first = next; } if (self->first == NULL) { self->last = NULL; } return result; } // -------------------------------------------------------------------------- // Index object ac_index ac_index_new(void) { ac_index self; if (!(self = malloc(sizeof(struct ac_index_s)))) { return NULL; } if (!(self->state_0 = ac_state_new())) { return NULL; } self->index_state = AC_INDEX_UNFIXED; return self; } ac_error_code ac_index_free(ac_index self, ac_free_function object_free) { ac_list *queue = NULL; ac_state *state = NULL; ac_error_code result = AC_SUCCESS; if (!self) { return AC_FAILURE; } if (!(queue = ac_list_new())) { return AC_FAILURE; } // Free all the state nodes by following the goto function tree breadth // first, starting with state_0. state = self->state_0; while (state) { // Free the state and enqueue the states from the goto list. if (ac_state_free(state, queue, object_free) != AC_SUCCESS) { result = AC_FAILURE; } state = ac_state_queue_get(queue); } ac_state_queue_free(queue); // The queue should be empty. self->state_0 = NULL; free(self); return result; } ac_error_code ac_index_enter(ac_index self, char *keyword, ac_offset size, void *object) { // This is an implementation of the enter procedure of 'Algorithm 2. // Construction of the goto function.' from the paper. ac_state *state = self->state_0; ac_offset j = 0; ac_state *new_state = NULL; // You can't enter strings into a fixed index. if (self->index_state != AC_INDEX_UNFIXED) { return AC_FAILURE; } // Make sure that the goto tree has a path that spells out the keyword. // First skip the front of the the keyword if a matching path already // exists... while (j < size && (new_state = ac_goto_list_get(state->gotos, keyword[j]))) { state = new_state; ++j; } // ... then build the nodes for the rest of the keyword, if any. while (j < size) { if (!(new_state = ac_state_new())) { return AC_FAILURE; } if (ac_goto_list_add(state->gotos, keyword[j], new_state) != AC_SUCCESS) { return AC_FAILURE; } state = new_state; ++j; } // Now add an output for the keyword and associated object. if (ac_output_list_add(state->outputs, size, object) != AC_SUCCESS) { return AC_FAILURE; } return AC_SUCCESS; } /** * Fix the index, making it ready to be queried. This is an implementation of * the last part of Algorithm 2 from the paper combined with an implementation * of 'Algorithm 3. Construction of the failure function.' from the paper. * Returns AC_SUCCESS if the index was successfully fixed or AC_FAILURE if an * error was encountered or if the index was not 'unfixed'. */ ac_error_code ac_index_fix(ac_index self) { // This is an implementation of the last part of Algorithm 2 from the // paper combined with an implementation of 'Algorithm 3. Construction // of the failure function.' from the paper. int symbol; ac_state *state = NULL; ac_state *r = NULL; ac_list *queue = NULL; ac_list_item *list_item = NULL; ac_goto *item = NULL; // You can't fix an index that is already fixed. if (self->index_state != AC_INDEX_UNFIXED) { return AC_FAILURE; } // Mark the index as being fixed. self->index_state = AC_INDEX_FIXED; // Make a temporary queue of states. if (!(queue = ac_list_new())) { return AC_FAILURE; } // Look at all the symbols. If state_0 has a goto for a symbol, add the // state to the queue and point the failure state back to state_0 - the // first part of Algorithm 3. Otherwise make state_0 goto itself for // that symbol - the last part of Algorithm 2. // TODO: Improve efficiency of state_0 to state_0 gotos. // NOTE: ac_goto_list_get is a linear scan, so we want to have symbols // that occur frequently in the query phrase to be near the start of // the list. By iterating from 0 instead of CHAR_MIN (-127), we put the // common 7-bit ASCII codes near the start of the list. for (symbol = 0; symbol <= CHAR_MAX - CHAR_MIN; symbol++) { // Passing int symbol as a char is a deliberate overflow here. if ((state = ac_goto_list_get(self->state_0->gotos, symbol))) { if (ac_list_add(queue, state) != AC_SUCCESS) { return AC_FAILURE; } state->failure = self->state_0; } else { if (ac_goto_list_add(self->state_0->gotos, symbol, self->state_0) != AC_SUCCESS) { return AC_FAILURE; } } } // Do the second part of Algorithm 3. Burn through the queue, enqueing // states from goto list in order to traverse the goto tree // breadth-first. // ... while ((r = ac_state_queue_get(queue))) { list_item = r->gotos->first; while (list_item) { item = (ac_goto *) list_item->item; symbol = item->symbol; if (ac_list_add(queue, item->state) != AC_SUCCESS) { return AC_FAILURE; } // ... For each goto state, find the failure function // by following the failure function back until there // is a goto defined. We will always find a defined // goto because state_0 has a goto defined for every // symbol (by now). ... state = r->failure; while (!ac_goto_list_has(state->gotos, symbol)) { state = state->failure; } item->state->failure = ac_goto_list_get(state->gotos, symbol); // ... Add the outputs for the failure state to the // outputs. We use the extra_outputs list because the // outputs are already referenced. if (ac_output_list_add_list( item->state->extra_outputs, item->state->failure->outputs)) { return AC_FAILURE; }; if (ac_output_list_add_list( item->state->extra_outputs, item->state->failure->extra_outputs)) { return AC_FAILURE; }; list_item = list_item->next; } } // Free the temporary queue. ac_state_queue_free(queue); return AC_SUCCESS; } bool ac_index_fixed(ac_index self) { return self->index_state == AC_INDEX_FIXED; } ac_error_code ac_index_query_cb(ac_index self, char *phrase, ac_offset size, ac_result_callback result_cb, void *result_cb_data) { // This function is an implementation of 'Algorithm 1. Pattern matching // machine.' from the paper. ac_state *state = self->state_0; ac_state *next = NULL; ac_offset j = 0; // You can't query an index that isn't fixed. if (self->index_state != AC_INDEX_FIXED) { return AC_FAILURE; } // You must not provide a NULL callback. if (!result_cb) { return AC_FAILURE; } // Run the pattern matching machine. Iterate over the symbols in the // phrase. ... for (; j < size; ++j) { // ... If there is no goto for the symbol. Follow the failure // functions until there is. We will always find our way to a // state with a goto defined for the symbol because, once the // index is fixed, state_0 has gotos defined for every symbol. // ... while (!(next = ac_goto_list_get(state->gotos, phrase[j]))) { state = state->failure; } state = next; // ... Add the outputs for the state. If there is no match, the // state will be state_0 which always has no outputs. ... if (ac_cb_outputs( result_cb, result_cb_data, state->outputs, j) != AC_SUCCESS) { return AC_FAILURE; }; if (ac_cb_outputs( result_cb, result_cb_data, state->extra_outputs, j) != AC_SUCCESS) { return AC_FAILURE; }; } return AC_SUCCESS; } // TODO: Add ac_index_unfix method to unfix the index. esmre-0.5.2/src/esm/aho_corasick.h000066400000000000000000000116131371675736000170230ustar00rootroot00000000000000/* aho_corasick.h - declarations for Aho Corasick implementations Copyright (C) 2007 Tideway Systems Limited. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AHO_CORASICK_H #define AHO_CORASICK_H #include typedef enum { AC_SUCCESS = 0, AC_FAILURE = 1 } ac_error_code; /** * Type for function pointers used for freeing complex item types. */ typedef ac_error_code (*ac_free_function)(void *item, void *data); /** * Type for the index into a string of symbols or the length of a string of * symbols. We use 0-based indexing. */ typedef int ac_offset; /** * Structure for a single query match, containing the span of the query phrase * that matched the keyword and a pointer associated with the keyword. */ typedef struct ac_result { /** * The offset of the first symbol in the matching substring of the * query phrase. */ ac_offset start; /** The offset of the symbol after the last symbol in the matching * substring of the query phrase. */ ac_offset end; /** Pointer associated with the keyword. */ void *object; } ac_result; /** * Type for result callback functions. */ typedef ac_error_code (*ac_result_callback)(void *result_cb_data, ac_result *result); // Operations for index objects. typedef struct ac_index_s *ac_index; /** * Construct a new index. The state is initially 'unfixed', meaning that the * user can enter new keywords but can not query the index. * * @return a pointer to the ac_index or NULL if an error was encountered. */ ac_index ac_index_new(void); /** * Free the index and all its subordinate objects. The provided object_free * function should do whatever necessary to free each associated object. It is * called once for each associated object that was given to ac_index_enter. * * @param self the index * @param object_free function that frees associated objects. * @return AC_SUCCESS if successful of AC_FAILURE is an error was encountered. */ ac_error_code ac_index_free(ac_index self, ac_free_function object_free); /** * Add a keyword and an associated object to the index. * * @param self the index * @param keyword pointer to an array of symbols that comprise the keyword * @param size the number of symbols in the keyword * @param object pointer to an associated object that is passed to the result * callback when the keyword is matched. * @return AC_SUCCESS if the keyword and object were added successfully or * AC_FAILURE if an error was encountered or if the index has already * been fixed. */ ac_error_code ac_index_enter(ac_index self, char *keyword, ac_offset size, void *object); /** * Fix the index, making it ready to be queried. * * @param self the index * @return AC_SUCCESS if the index was successfully fixed or AC_FAILURE if an * error was encountered or if the index has already been fixed. */ ac_error_code ac_index_fix(ac_index self); /** * Check if the index is fixed and ready to be queried. The index is initially * unfixed, meaning new keywords may be entered, but the index cannot be * queried. When an index is fixed (using ac_index_fix) it is ready to be * queried, but new keywords may not be entered. * * @param self the index * @return true if the index state is fixed, or false if the index is unfixed. */ bool ac_index_fixed(ac_index self); /** * Query the index with the given phrase of the given size. Matching keyword * spans and associated objects are sent with result_cb_data to result_cb. * * @param self the index * @param phrase pointer to an array of symbols that will be searched * @param size the number of symbols in the the array * @param result_cb function that will be called whenever a match is found * @param result_cb_data pointer to a context object that will be passed to the * callback whenever a keyword is matched * @return AC_SUCCESS if the query was successful (even if there were no * matches) or AC_FAILURE if an error was encountered */ ac_error_code ac_index_query_cb(ac_index self, char *phrase, ac_offset size, ac_result_callback result_cb, void *result_cb_data); #endif // AHO_CORASICK_H esmre-0.5.2/src/esmre.py000066400000000000000000000156771371675736000151440ustar00rootroot00000000000000#!/usr/bin/env python # encoding: utf-8 # esmre.py - clue-indexed regular expressions module # Copyright (C) 2007-2008 Tideway Systems Limited. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 # USA import esm import threading class InBackslashState(object): def __init__(self, parent_state): self.parent_state = parent_state def process_byte(self, ch): return self.parent_state class InClassState(object): def __init__(self, parent_state): self.parent_state = parent_state def process_byte(self, ch): if ch == "]": return self.parent_state elif ch == "\\": return InBackslashState(self) else: return self class InBracesState(object): def __init__(self, parent_state): self.parent_state = parent_state def process_byte(self, ch): if ch == "}": return self.parent_state else: return self class CollectingState(object): def __init__(self): self.hints = [""] def process_byte(self, ch): self.update_hints(ch) return self.next_state(ch) def bank_current_hint_with_last_byte(self): self.hints.append("") def bank_current_hint_and_forget_last_byte(self): if isinstance(self.hints[-1], list): del self.hints[-1] else: self.hints[-1] = self.hints[-1][:-1] self.hints.append("") def forget_all_hints(self): self.hints = [""] def append_to_current_hint(self, ch): self.hints[-1] += ch def update_hints(self, ch): if ch in "?*{": self.bank_current_hint_and_forget_last_byte() elif ch in "+.^$([\\": self.bank_current_hint_with_last_byte() elif ch == "|": self.forget_all_hints() else: self.append_to_current_hint(ch) def next_state(self, ch): if ch == "(": return StartOfGroupState(self) elif ch == "[": return InClassState(self) elif ch == "{": return InBracesState(self) elif ch == "\\": return InBackslashState(self) elif ch == "|": return self.alternation_state() else: return self def alternation_state(self): raise NotImplementedError class RootState(CollectingState): def alternation_state(self): raise StopIteration class StartOfGroupState(object): def __init__(self, parent_state): self.parent_state = parent_state def process_byte(self, ch): if ch == "?": return StartOfExtensionGroupState(self.parent_state) else: return InGroupState(self.parent_state).process_byte(ch) class InGroupState(CollectingState): def __init__(self, parent_state): CollectingState.__init__(self) self.parent_state = parent_state self.had_alternation = False def update_hints(self, ch): if ch == ")": if not self.had_alternation: self.parent_state.hints.append(self.hints) else: CollectingState.update_hints(self, ch) def next_state(self, ch): if ch == ")": return self.close_group_state() else: return CollectingState.next_state(self, ch) def close_group_state(self): return self.parent_state def alternation_state(self): self.had_alternation = True return self class StartOfExtensionGroupState(object): def __init__(self, parent_state): self.parent_state = parent_state def process_byte(self, ch): if ch == "P": return MaybeStartOfNamedGroupState(self.parent_state) else: return IgnoredGroupState(self.parent_state).process_byte(ch) class MaybeStartOfNamedGroupState(object): def __init__(self, parent_state): self.parent_state = parent_state def process_byte(self, ch): if ch == "<": return InNamedGroupNameState(self.parent_state) else: return IgnoredGroupState(self.parent_state) class InNamedGroupNameState(object): def __init__(self, parent_state): self.parent_state = parent_state def process_byte(self, ch): if ch == ">": return InGroupState(self.parent_state) else: return self class IgnoredGroupState(InGroupState): def update_hints(self, ch): pass def hints(regex): state = RootState() try: for ch in regex: state = state.process_byte(ch) except StopIteration: pass def flattened(l): for item in l: if isinstance(item, list): for i in flattened(item): yield i else: yield item return [hint for hint in flattened(state.hints) if hint] def shortlist(hints): if not hints: return [] best = "" for hint in hints: if len(hint) > len(best): best = hint return [best] class Index(object): def __init__(self): self.esm = esm.Index() self.hintless_objects = list() self.fixed = False self.lock = threading.Lock() def enter(self, regex, obj): self.lock.acquire() try: if self.fixed: raise TypeError("enter() cannot be called after query()") keywords = shortlist(hints(regex)) if not keywords: self.hintless_objects.append(obj) for hint in shortlist(hints(regex)): self.esm.enter(hint.lower(), obj) finally: self.lock.release() def query(self, string): self.lock.acquire() try: if not self.fixed: self.esm.fix() self.fixed = True finally: self.lock.release() return self.hintless_objects + \ [obj for (_, obj) in self.esm.query(string.lower())] esmre-0.5.2/test/000077500000000000000000000000001371675736000136275ustar00rootroot00000000000000esmre-0.5.2/test/test_esm.py000066400000000000000000000064471371675736000160370ustar00rootroot00000000000000#!/usr/bin/env python # encoding: utf-8 # esm_tests.py - tests for esm extension module # Copyright (C) 2007 Tideway Systems Limited. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 # USA import unittest import esm import esmre class IndexTests(unittest.TestCase): def testHasConstructor(self): self.assertTrue(esm.Index()) def testIndexHasEnterMethod(self): esm.Index().enter("keyword") def testIndexMustHaveStringForFirstArgument(self): self.assertRaises(TypeError, esm.Index().enter, 0) self.assertRaises(TypeError, esm.Index().enter, []) self.assertRaises(TypeError, esm.Index().enter) def testIndexFix(self): index = esm.Index() index.fix() def testQuery(self): index = esm.Index() index.enter("he") index.enter("she") index.enter("his") index.enter("hers") index.fix() self.assertEqual([((1, 4), "his"), ((5, 7), "he"), ((13, 16), "his")], index.query("this here is history")) # 0123456789.123456789 def testEnterObject(self): index = esm.Index() mint_object = dict() index.enter("mint", mint_object) pepper_object = dict() index.enter("pepper", pepper_object) index.fix() results = index.query("mint sauce") self.assertEqual(1, len(results)) self.assertTrue(isinstance(results[0], tuple)) slice_indices, associated_object = results[0] self.assertEqual((0,4), slice_indices) self.assertTrue(associated_object is mint_object) def testCantFixIndexWhenAlreadyFixed(self): index = esm.Index() index.fix() self.assertRaises(TypeError, index.fix) def testCantEnterWhenAlreadyFixed(self): index = esm.Index() index.fix() self.assertRaises(TypeError, index.enter, "foo") def testQueryUntilFixed(self): index = esm.Index() self.assertRaises(TypeError, index.query, "foo") def testObjectsForCommonEndingsAreDecrefedCorrectly(self): o = "Owt" import sys initial_ref_count = sys.getrefcount(o) index = esm.Index() index.enter("food", o) index.enter("ood", o) index.fix() index.query("blah") index = None del index self.assertEqual(initial_ref_count, sys.getrefcount(o)) if __name__ == '__main__': unittest.main()esmre-0.5.2/test/test_esmre.py000066400000000000000000000153631371675736000163630ustar00rootroot00000000000000#!/usr/bin/env python # encoding: utf-8 # esmre_tests.py - tests for esmre module # Copyright (C) 2007-2008 Tideway Systems Limited. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 # USA import unittest import esmre class HintExtractionTests(unittest.TestCase): def checkHints(self, expected_hints, regex): self.assertEqual(set(expected_hints), set(esmre.hints(regex))) def testSimpleString(self): self.checkHints(["yarr"], r"yarr") def testSkipsOptionalCharacter(self): self.checkHints(["dubloon"], r"dubloons?") def testStartsNewStringAfterOptionalCharacter(self): self.checkHints(["ship", "shape"], r"ship ?shape") def testSkipsOptionalRepeatedCharacter(self): self.checkHints(["bristol", "fasion"], r"bristol *fasion") def testIncludesRepeatedCharacterButStartsNewHint(self): self.checkHints(["ava", "st me harties"], r"ava+st me harties") def testSkipsGroupsWithAlternation(self): self.checkHints(["Hoist the ", ", ye ", "!"], r"Hoist the (mizzen mast|main brace), " r"ye (landlubbers|scurvy dogs)!") def testSkipsAny(self): self.checkHints(["After 10 paces, ", " marks the spot"], r"After 10 paces, . marks the spot") def testSkipsOneOrMoreAny(self): self.checkHints(["Hard to ", "!"], r"Hard to .+!") def testSkipsNestedGroups(self): self.checkHints(["Squark!", " Pieces of ", "!"], r"Squark!( Pieces of (.+)!)") def testSkipsCharacterClass(self): self.checkHints(["r"], r"[ya]a*r+") def testRightBracketDoesNotCloseGroupIfInClass(self): self.checkHints([":=", "X"], r":=([)D])X") def testSkipsBackslashMetacharacters(self): self.checkHints(["Cap'n", " ", " Beard"], r"Cap'n\b ([\S] Beard)") def testBackslashBracketDoesNotCloseGroup(self): self.checkHints([":=", "X"], r":=(\)|D)X") def testBackslashSquareBracketDoesNotCloseClass(self): self.checkHints([":=", "X"], r":=[)D\]]X") def testSkipsMetacharactersAfterGroups(self): self.checkHints(["Yo ", "ho ", " and a bottle of rum"], r"Yo (ho )+ and a bottle of rum") def testSkipsRepetionBraces(self): self.checkHints(["A", ", me harties"], r"Ar{2-10}, me harties") def testAlternationCausesEmptyResult(self): self.checkHints([], r"rum|grog") def testSkipMatchBeginning(self): self.checkHints(["The black perl"], r"^The black perl") def testSkipMatchEnd(self): self.checkHints(["Davey Jones' Locker"], r"Davey Jones' Locker$") def testOnlyGroupGivesEmptyResult(self): self.checkHints([], r"(rum|grog)") def testGetsHintsFromGroups(self): self.checkHints(["/"], r"([0-3][0-9]/[0-1][0-9]/[1-2][0-9]{3})") def testSkipsOptionalGroups(self): self.checkHints(["Shiver me timbers!"], r"Shiver me timbers!( Arrr!)?") def testSkipsMostExtensionGroups(self): for regex in [ # set flag r"(?i)(?L)(?m)(?s)(?u)(?x)", # non-grouping paren r"(?:foo)", # previous named group r"(?P=foo)", # comment r"(?#foo)", # lookahead r"(?=foo)", # negative lookahead r"(?!foo)", # lookbehind r"(?<=foo)", # negative lookbehind r"(?[0-3][0-9]/[0-1][0-9]/[1-2][0-9]{3})") class ShortlistTests(unittest.TestCase): def checkShortlist(self, expected_shortlist, hints): self.assertEqual(expected_shortlist, esmre.shortlist(hints)) def testShortlistIsEmptyForEmptyCandidates(self): self.checkShortlist([], []) def testShortlistIsOnlyCandidate(self): self.checkShortlist(["Blue Beard"], ["Blue Beard"]) def testShorlistSelectsLongestCandidate(self): self.checkShortlist(["Black Beard"], ["Black Beard", "Blue Beard"]) def testShorlistSelectsLongestCandidateAtEnd(self): self.checkShortlist(["Yellow Beard"], ["Black Beard", "Blue Beard", "Yellow Beard"]) class IndexTests(unittest.TestCase): def setUp(self): self.index = esmre.Index() self.index.enter(r"Major-General\W*$", "savoy opera") self.index.enter(r"\bway\W+haye?\b", "sea shanty") def testSingleQuery(self): self.assertEqual(["savoy opera"], self.index.query( "I am the very model of a modern Major-General.")) def testCannotEnterAfterQuery(self): self.index.query("blah") self.assertRaises(TypeError, self.index.enter, "foo", "bar") def testCaseInsensitive(self): self.assertEqual(["sea shanty"], self.index.query( "Way, hay up she rises,")) self.assertEqual(["sea shanty"], self.index.query( "To my way haye, blow the man down,")) def testAlwaysReportsOpjectForHintlessExpressions(self): self.index.enter(r"(\d+\s)*(paces|yards)", "distance") self.assertTrue("distance" in self.index.query("'til morning")) if __name__ == '__main__': unittest.main()