diff --git a/.gitignore b/.gitignore
index 935d8ad..fea32c6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,9 +1,6 @@
.DS_Store
-Main
-Main.dSYM/Contents/Info.plist
-Main.dSYM/Contents/Resources/Relocations/aarch64/Main.yml
-.vscode/*
-.vscode/settings.json
-.vscode/launch.json
-.vscode/tasks.json
-.vscode/settings.json
\ No newline at end of file
+.vscode
+build
+test/*.test
+test/misc
+test/ihct
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, 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
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If 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 convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state 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 program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/Main.c b/Main.c
deleted file mode 100644
index 103faa0..0000000
--- a/Main.c
+++ /dev/null
@@ -1,21 +0,0 @@
-#include
-#include
-#include
-#include
-
-int main(int argc, char** args) {
- char* regex = "(limb)|(and)|(ing)";
- // char* regex = ".[a-z]*";
- // char* testex = "However, this implementation seeks to allow for the minimum that any user familiar with RegEx would appreciate. There are few special features and even fewer guarantees of efficiency or function. Yet, it's a little novelty project that I hope to incorporate into a larger Language Parser and, eventually, compiler.";
- char* testex = "a limbless cold-blooded vertebrate animal with gills and fins and living wholly in water: the sea is thick with fish.";
-
- RE** parseStack = parse(regex, strlen(regex));
- debug(parseStack, 0);
-
- BoolState stateTest = test(parseStack, testex, strlen(testex));
- printf("Truth: %d\n", stateTest.match);
- printf("Consumed: %d\n", stateTest.consumed);
- match(parseStack, testex, strlen(testex));
-
- return 0;
-}
\ No newline at end of file
diff --git a/Makefile b/Makefile
index aeb5848..5e232c3 100644
--- a/Makefile
+++ b/Makefile
@@ -1,23 +1,35 @@
# the compiler to use
CC = clang
+ifeq ($(VERBOSE), YES)
+ V_CC = $(CC)
+else
+ V_CC = @$(CC)
+endif
+
# compiler flags:
# -g adds debugging information to the executable file
# -Wall turns on most, but not all, compiler warnings
CFLAGS = -g -Wall
-
+
#files to link:
INCLUDE = include
SRC = src
# the name to use for both the target source file, and the output file:
TARGET = Main
-OBJECTS = ($(SRC).c:=.o)
-
+BUILD = build
+
+SRCS = $(shell find $(SRC) -name '*.c')
+
all: $(TARGET)
-$(TARGET): $(TARGET).c $(SRC)/*.c
- $(CC) $(CFLAGS) -I $(INCLUDE) $(TARGET).c $(SRC)/*.c -o Main
+$(TARGET): $(SRCS)
+ mkdir -p $(BUILD)
+ $(CC) $(CFLAGS) -I $(INCLUDE) $(SRCS) -o $(BUILD)/Main
clean:
- rm -rf *.o
\ No newline at end of file
+ -rm -rf $(BUILD)/*
+
+run: $(TARGET)
+ $(BUILD)/$(TARGET)
\ No newline at end of file
diff --git a/include/Backtracking.h b/include/Backtracking.h
deleted file mode 100644
index b3e48e3..0000000
--- a/include/Backtracking.h
+++ /dev/null
@@ -1,27 +0,0 @@
-#include
-
-#if !defined(BACKTRACK)
-#define BACKTRACK
-
-#define BOOLSTACK_SIZE 512
-
-typedef struct BackState {
- unsigned int index;
- unsigned int consumed;
- unsigned int stateIndex;
- unsigned short backTrackState;
-} BackState;
-
-typedef struct BackStack {
- unsigned int index;
- unsigned int max;
- struct BackState** states;
-} BackStack;
-
-BackStack* createBackStack();
-void resetBackStack(BackStack* stack);
-BackStack* pushBackStack(BackStack* back_stack, BoolState state, unsigned short backTrackState, unsigned int stateIndex);
-BackState* popBackStack(BackStack* back_stack);
-BackState* backtrack(BackStack* back_stack);
-
-#endif
\ No newline at end of file
diff --git a/include/Error.h b/include/Error.h
new file mode 100644
index 0000000..c54286e
--- /dev/null
+++ b/include/Error.h
@@ -0,0 +1,11 @@
+#if !defined(ERROR)
+#define ERROR
+
+#define UNDEFINED 0x000
+#define GENERIC 0x001
+#define FATAL 0x002
+
+void error(char *message, unsigned int type);
+void warn(char *message);
+
+#endif
\ No newline at end of file
diff --git a/include/HashTable.h b/include/HashTable.h
new file mode 100644
index 0000000..e3e75a9
--- /dev/null
+++ b/include/HashTable.h
@@ -0,0 +1,45 @@
+#include
+#include
+
+#if !defined(HASHTABLE)
+#define HASHTABLE
+
+#define DEFAULT_HTABLE_BUCKETS 64
+#define DEFAULT_BUCKET_SLOTS 4
+
+#define HASH_BITS uint32_t
+
+struct bch_llist_slot
+{
+ void *data;
+ const char *key;
+ struct bch_llist_slot *next;
+};
+
+struct bch_llist_bucket
+{
+ size_t slots_used;
+ struct bch_llist_slot *slot;
+};
+
+struct bch_buckets
+{
+ struct bch_llist_bucket *bucket;
+ HASH_BITS (*hash_f)(const char *key);
+};
+
+struct bch_table_info
+{
+ size_t used;
+ size_t buckets;
+ size_t bucket_slots;
+};
+
+struct bch_table
+{
+ size_t table_count;
+ struct bch_buckets *tables;
+ struct bch_table_info info;
+};
+
+#endif
\ No newline at end of file
diff --git a/include/Interface.h b/include/Interface.h
new file mode 100644
index 0000000..7f06e94
--- /dev/null
+++ b/include/Interface.h
@@ -0,0 +1,15 @@
+#if !defined(INTERFACE)
+#define INTERFACE
+
+#define INTERFACE_BUFFER_SIZE 256
+
+int shell_is_interactive;
+
+void initInterface();
+void welcomeScreen();
+void prompt();
+
+char *processTerminal(char *input_buffer, int actual_buffer_size);
+char *processFile(char *input_buffer, int actual_buffer_size);
+
+#endif
\ No newline at end of file
diff --git a/include/RegExp.h b/include/RegExp.h
index 79d2570..180d943 100644
--- a/include/RegExp.h
+++ b/include/RegExp.h
@@ -1,65 +1,93 @@
#if !defined(REGEXP)
#define REGEXP
-#define NONE 0x000
-
-#define WILDCARD 0x001
-#define LITERAL 0x002
-#define GROUP 0x003
-#define LITERAL_GROUP 0x004
-#define OR_GROUP 0x005
-#define PORTAL 0x006
-
-#define EXACTLY_ONE 0x001
-#define ZERO_OR_ONE 0x002
-#define ZERO_OR_MORE 0x003
-#define RANGE 0x004
-
-#define GREEDY 0x000
-#define POSSESSIVE 0x001
-#define LAZY 0x002
-
-#define ASCII_9 58
-#define ASCII_0 48
-#define ASCII_COMMA 44
-#define ASCII_FSLASH 92
-#define ASCII_DASH 45
-#define ASCII_CARET 94
-
-#define DEFAULT_STACK_SIZE 64
-#define MATCHES_ARRAY 512
-#define ASCII_TABLE 256
-
-typedef struct Quantifier {
+#define NONE 0x000
+
+#define WILDCARD 0x001
+#define LITERAL 0x002
+#define GROUP 0x003
+#define LITERAL_GROUP 0x004
+#define OR_GROUP 0x005
+#define PORTAL 0x006
+
+#define EXACTLY_ONE 0x001
+#define ZERO_OR_ONE 0x002
+#define ZERO_OR_MORE 0x003
+#define RANGE 0x004
+
+#define GREEDY 0x000
+#define POSSESSIVE 0x001
+#define LAZY 0x002
+
+#define DEFAULT_STACK_SIZE 64
+#define ASCII_TABLE 256
+#define MATCHES_ARRAY 512
+#define BOOLSTACK_SIZE 512
+
+// Sigh... Nobody told me about enums
+
+struct Quantifier
+{
unsigned short type;
unsigned short modifier;
unsigned short min;
unsigned short max;
-} Quantifier;
+};
-typedef struct RE {
- unsigned char type;
- unsigned char data;
- unsigned short matches;
+// Here, it does not matter if type or data is char and matches is short
+// It will still be aligned by 8 and make 32 bytes
+// So, might as well short and int it up
+struct RE
+{
+ unsigned short type;
+ unsigned short data;
+ unsigned int matches;
struct Quantifier quantifier;
- struct RE** child_stack;
- char* table;
-} RE;
+ struct RE **child_stack;
+ char *table;
+};
-typedef struct BoolState {
+// So, structs addressed (what the struct address refers to) by its first element
+// and are aligned according to the largest member; here, we read 12 bytes since 4 by 3
+// is 12
+struct BoolState
+{
unsigned int consumed;
unsigned int match;
unsigned int end;
-} BoolState;
+};
+
+struct RE **parse(char *re, size_t len);
+struct BoolState test(struct RE **stack, char *string, size_t len);
+struct BoolState *match(struct RE **stack, char *string, size_t len);
+
+void debug(struct RE **parseStack, int level);
+
+int feedQuantifier(struct RE *regular_expression, size_t i, char *re, size_t len);
+int feedLiteral(struct RE *regular_expression, size_t i, char *re, size_t len);
-int error(char* message, int type);
+// Formerly Backtracking.h
-RE** parse(char* re, size_t len);
-BoolState test(RE** stack, char* string, size_t len);
-BoolState* match(RE** stack, char* string, size_t len);
+struct BackState
+{
+ unsigned int index;
+ unsigned int stateIndex;
+ unsigned short consumed;
+ unsigned short backTrackState;
+};
+// I leave some structures with shorts since the struct stays the same size anyways
+// http://www.catb.org/esr/structure-packing/
-void debug(RE** parseStack, int level);
+struct BackStack
+{
+ unsigned int index;
+ unsigned int max;
+ struct BackState **states;
+};
-int feedQuantifier(RE* regular_expression, size_t i, char* re, size_t len);
-int feedLiteral(RE* regular_expression, size_t i, char* re, size_t len);
+struct BackStack *createBackStack();
+void resetBackStack(struct BackStack *stack);
+struct BackStack *pushBackStack(struct BackStack *back_stack, struct BoolState state, unsigned short backTrackState, unsigned int stateIndex);
+struct BackState *popBackStack(struct BackStack *back_stack);
+struct BackState *backtrack(struct BackStack *back_stack);
#endif
\ No newline at end of file
diff --git a/include/Token.h b/include/Token.h
new file mode 100644
index 0000000..f5f0dbd
--- /dev/null
+++ b/include/Token.h
@@ -0,0 +1,56 @@
+#if !defined(PARSING)
+#define PARSING
+
+#define CHAR_BUFFER_SIZE 16
+
+typedef enum
+{
+ WORD,
+ ASSIGNMENT_WORD,
+ NAME,
+ NEWLINE,
+ IO_NUMBER,
+ AND_IF,
+ OR_IF,
+ DSEMI,
+ DLESS,
+ DGREAT,
+ LESSAND,
+ GREATAND,
+ LESSGREAT,
+ DLESSDASH,
+ CLOBBER,
+ If,
+ Then,
+ Else,
+ Elif,
+ Fi,
+ Do,
+ Done,
+ Case,
+ Esac,
+ While,
+ Until,
+ For,
+ Lbrace,
+ Rbrace,
+ Bang,
+ In
+} TokenType;
+
+struct Token *lex(char *input);
+
+// Recently just discovered that the Linux kernel style guide
+// disallows typedef'ing structs and unions
+// To an extent, I see the error of my ways
+// On the other hand, >:(
+
+struct __attribute__((__packed__)) Token
+{
+ struct Token *next;
+ unsigned int span;
+ char *begin;
+ TokenType id;
+};
+
+#endif
\ No newline at end of file
diff --git a/src/Backtracking.c b/src/Backtracking.c
deleted file mode 100644
index 186e7db..0000000
--- a/src/Backtracking.c
+++ /dev/null
@@ -1,59 +0,0 @@
-#include
-#include
-#include
-#include
-
-BackStack* createBackStack() {
- BackStack* back_stack = (BackStack*) malloc(sizeof(BackStack));
- if (back_stack == (BackStack*) NULL) { return back_stack; }
-
- back_stack->index = 0;
- back_stack->max = BOOLSTACK_SIZE;
- back_stack->states = (BackState**) malloc(sizeof(BackState*) * BOOLSTACK_SIZE);
-
- return back_stack;
-};
-
-void resetBackStack(BackStack* stack) {
- if (stack == (BackStack*) NULL) {
- return;
- }
- for (int i = 0; i < stack->max; i++) {
- free(stack->states[i]);
- }
- free(stack);
- return;
-}
-
-BackStack* pushBackStack(BackStack* back_stack, BoolState state, unsigned short backTrackState, unsigned int stateIndex) {
- if (back_stack->index < back_stack->max) {
-
- BackState* newState = (BackState*) malloc(sizeof(BackState));
- newState->backTrackState = backTrackState;
- newState->consumed = state.consumed;
- newState->index = state.end;
- newState->stateIndex = stateIndex;
- back_stack->states[back_stack->index] = newState;
-
- back_stack->index++;
-
- return back_stack;
- }
-
- error("Bool stack overflow!", 2);
- return (BackStack*) NULL;
-};
-
-BackState* popBackStack(BackStack* back_stack) {
- if (back_stack->index > 0) {
- back_stack->index--;
- }
- BackState* poppedState = back_stack->states[back_stack->index];
- back_stack->states[back_stack->index] = (BackState*) NULL;
- return poppedState;
-}
-
-BackState* backtrack(BackStack* back_stack) {
- BackState* poppedState = popBackStack(back_stack);
- return poppedState;
-}
\ No newline at end of file
diff --git a/src/Error.c b/src/Error.c
deleted file mode 100644
index 90a209b..0000000
--- a/src/Error.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include
-#include
-
-void error(char* message, int type) {
- fprintf(stderr, "ERROR: %s :::: Type %d\n", message, type);
- exit(EXIT_FAILURE);
-}
\ No newline at end of file
diff --git a/src/LiteralGroup.c b/src/LiteralGroup.c
deleted file mode 100644
index 7b983b8..0000000
--- a/src/LiteralGroup.c
+++ /dev/null
@@ -1,58 +0,0 @@
-#include
-#include
-#include
-#include
-
-void activateLiteral(char* table, char literal, char last, int* addr_active_ranging) {
- int index = (int) literal;
- if ((*addr_active_ranging) == 1) {
- for (int i = last + 1; i <= literal; i++) {
- table[i] = 1 - table[i];
- }
- (*addr_active_ranging) = 0;
- return;
- }
- table[index] = 1 - table[index];
-}
-
-int feedLiteral(RE* regular_expression, size_t i, char* re, size_t len) {
-
- char* table = (char*) calloc(ASCII_TABLE, sizeof(char));
- if (table == (char*) NULL) { return 0; }
-
- if (re[i] == '^') {
- memset(table, 1, sizeof(char) * ASCII_TABLE);
- }
-
- char last = '\0';
- int active_ranging = 0;
-
- while (i < len) {
- if (re[i] == ']') { break; }
-
- if (i + 1 < len - 1) {
- switch (re[i]) {
- case ASCII_FSLASH:
- activateLiteral(table, re[++i], last, &active_ranging);
- last = re[i];
- i++;
- continue;
- case ASCII_DASH:
- active_ranging = 1;
- i++;
- continue;
- default:
- break;
- }
- }
-
- activateLiteral(table, re[i], last, &active_ranging);
- last = re[i];
- i++;
- }
-
- table[0] = 0;
- regular_expression->table = table;
-
- return i;
-}
\ No newline at end of file
diff --git a/src/Main.c b/src/Main.c
new file mode 100644
index 0000000..569ecdd
--- /dev/null
+++ b/src/Main.c
@@ -0,0 +1,64 @@
+#include
+#include
+#include
+#include
+#include
+
+// int main(int argc, char** args) {
+// char* regex = "(er.e){1,}";
+// // char* regex = ".[a-z]*";
+// // char* testex = "However, this implementation seeks to allow for the minimum that any user familiar with RegEx would appreciate. There are few special features and even fewer guarantees of efficiency or function. Yet, it's a little novelty project that I hope to incorporate into a larger Language Parser and, eventually, compiler.";
+// char* testex = "a limbless cold-blooded vertebrate animal with gills and fins and living wholly in water: the sea is thick with fish.";
+
+// struct RE** parseStack = parse(regex, strlen(regex));
+// debug(parseStack, 0);
+
+// struct BoolState stateTest = test(parseStack, testex, strlen(testex));
+// printf("Truth: %d\n", stateTest.match);
+// printf("Consumed: %d\n", stateTest.consumed);
+// match(parseStack, testex, strlen(testex));
+
+// return 0;
+// }
+
+// we shall invoke the interface to provide an easy manner of testing and utilizing the engine
+// all of this will be handled here in Main
+int main(int argc, char **argv)
+{
+ if (argc > 1)
+ {
+
+
+ return 0;
+ }
+
+ initInterface();
+
+ if (shell_is_interactive)
+ {
+ int exit_shell = 0;
+ int echo_back = 1;
+ int actual_buffer_size = INTERFACE_BUFFER_SIZE;
+
+ char *input = (char *)malloc(sizeof(char) * actual_buffer_size);
+ // memset(input, '\0', actual_buffer_size);
+
+ welcomeScreen();
+
+ while (!exit_shell)
+ {
+ prompt();
+ processTerminal(input, actual_buffer_size);
+
+ if (echo_back)
+ {
+ // printf("%lu\n", sizeof(struct Token));
+ printf("%s\n", input);
+ }
+ }
+
+ free(input);
+ }
+
+ return 0;
+}
\ No newline at end of file
diff --git a/src/Quantifier.c b/src/Quantifier.c
deleted file mode 100644
index 9aae47a..0000000
--- a/src/Quantifier.c
+++ /dev/null
@@ -1,38 +0,0 @@
-#include
-#include
-#include
-
-int feedQuantifier(RE* regular_expression, size_t i, char* re, size_t len) {
- unsigned int max = 0;
- unsigned int min = 0;
-
- unsigned int* place = &min;
-
- short accessedMin = 0;
- short accessedMax = 0;
-
- while (i < len) {
- if (re[i] <= ASCII_9 && re[i] >= ASCII_0) {
- (*place) = ((*place)*10) + (re[i] - 48);
- if (place == &min) {
- accessedMin = 1;
- } else {
- accessedMax = 1;
- }
- } else if (re[i] == ASCII_COMMA) {
- place = &max;
- } else if (re[i] == '}') { break; }
- i++;
- }
-
- if (accessedMin == 0 && accessedMax == 0) { max = INT32_MAX; }
- if (accessedMax == 0 && place == &max) { max = INT32_MAX; }
- if (max < min) { max = min; }
-
- regular_expression->quantifier.type = RANGE;
- regular_expression->quantifier.max = max;
- regular_expression->quantifier.min = min;
- regular_expression->quantifier.modifier = GREEDY;
-
- return i;
-}
\ No newline at end of file
diff --git a/src/RegExp.c b/src/RegExp.c
deleted file mode 100644
index 8ed8cf2..0000000
--- a/src/RegExp.c
+++ /dev/null
@@ -1,257 +0,0 @@
-#include
-#include
-#include
-
-RE* createRegularExpression(int type, int quantifier, char data) {
- RE* regular_expression = (RE*) malloc(sizeof(RE));
- if (regular_expression == (RE*) NULL) { return (RE*) NULL; }
-
- regular_expression->type = type;
- regular_expression->data = data;
- regular_expression->matches = 0;
-
- regular_expression->quantifier.type = quantifier;
- regular_expression->quantifier.max = 1;
- regular_expression->quantifier.min = 1;
- regular_expression->quantifier.modifier = GREEDY;
-
- regular_expression->child_stack = (RE**) NULL;
- regular_expression->table = (char*) NULL;
-
- return regular_expression;
-}
-
-RE** createParseStack(int size) {
- RE** parse_stack = (RE**) malloc(sizeof(RE*) * size);
- if (parse_stack == (RE**) NULL || size < 1) { return (RE**) NULL; }
-
- RE* first_regexp = createRegularExpression(NONE, NONE, size);
- parse_stack[0] = first_regexp;
-
- return parse_stack;
-}
-
-RE* pushStack(RE** stack, RE* regular_expression) {
- if (regular_expression == (RE*) NULL) { return (RE*) NULL; }
-
- stack[0]->type++;
-
- int index = stack[0]->type;
-
- if (index >= stack[0]->data) { error("Stack overflow!", 2); }
-
- stack[index] = regular_expression;
-
- return regular_expression;
-}
-
-RE* peekStack(RE** stack) {
- int index = stack[0]->type;
- if (index < 0 || stack[index] == (RE*) NULL) { return (RE*) NULL; }
-
- if (stack[index]->type == PORTAL) {
- RE** address = stack[index]->child_stack;
- free(stack[index]);
- stack[0]->type--;
- return peekStack(address);
- }
-
- return stack[index];
-}
-
-RE* popStack(RE** stack) {
- int index = stack[0]->type;
- if (index < 1) { return (RE*) NULL; }
-
- RE* regular_expression = peekStack(stack);
- stack[0]->type--;
- return regular_expression;
-}
-
-void debug(RE** parseStack, int level) {
- if (parseStack[0] != (RE*) NULL) {
- for (int i = 0; i <= parseStack[0]->type; i++) {
- printf("LEVEL: %d\n", level);
- printf("--TYPE: %d\n", parseStack[i]->type);
- printf("--QUANTIFIER: %d\n", parseStack[i]->quantifier.type);
- printf("----MODIFIER: %d\n", parseStack[i]->quantifier.modifier);
- printf("--DATA: %d\n", parseStack[i]->data);
- printf("--CHILDSTACK: %p\n", parseStack[i]->child_stack);
- if (parseStack[i]->child_stack != (RE**) NULL) {
- debug(parseStack[i]->child_stack, level + 1);
- }
- }
- }
-}
-
-RE** parse(char* re, size_t len) {
-
- RE** parse_stack = createParseStack(DEFAULT_STACK_SIZE);
- if (parse_stack == (RE**) NULL) { return (RE**) NULL; }
-
- RE** child_stack = createParseStack(DEFAULT_STACK_SIZE);
- parse_stack[0]->child_stack = child_stack;
-
- size_t i = 0;
- while (i < len) {
- RE* regular_expression = (RE*) NULL;
- RE* lastRE;
- switch (re[i]) {
- case '.':
- regular_expression = createRegularExpression(WILDCARD, EXACTLY_ONE, re[i]);
- pushStack(peekStack(parse_stack)->child_stack, regular_expression);
- break;
- case '?':
- lastRE = peekStack(peekStack(parse_stack)->child_stack);
- if (lastRE == (RE*) NULL || lastRE->quantifier.type == NONE) {
- error("? Quantifier has to follow something", 2);
- }
- lastRE->quantifier.modifier = LAZY;
- if (lastRE->quantifier.type == EXACTLY_ONE) {
- lastRE->quantifier.type = RANGE;
- lastRE->quantifier.modifier = GREEDY;
- lastRE->quantifier.max = 1;
- lastRE->quantifier.min = 0;
- }
- break;
- case '+':
- lastRE = peekStack(peekStack(parse_stack)->child_stack);
- if (lastRE == (RE*) NULL || lastRE->quantifier.type == NONE) {
- error("+ Quantifier has to follow something", 2);
- }
- lastRE->quantifier.modifier = POSSESSIVE;
- if (lastRE->quantifier.type == EXACTLY_ONE) {
- lastRE->quantifier.type = RANGE;
- lastRE->quantifier.modifier = GREEDY;
- lastRE->quantifier.max = INT16_MAX;
- lastRE->quantifier.min = 1;
- }
- break;
- case '*':
- lastRE = peekStack(peekStack(parse_stack)->child_stack);
- if (lastRE == (RE*) NULL || lastRE->quantifier.type == NONE) {
- error("* Quantifier has to follow an exactly one", 2);
- }
- lastRE->quantifier.modifier = GREEDY;
- if (lastRE->quantifier.type == EXACTLY_ONE) {
- lastRE->quantifier.type = RANGE;
- lastRE->quantifier.modifier = GREEDY;
- lastRE->quantifier.max = INT16_MAX;
- lastRE->quantifier.min = 0;
- }
- break;
- case '(':
- regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
- regular_expression->child_stack = createParseStack(DEFAULT_STACK_SIZE);
-
- pushStack(parse_stack, regular_expression);
- break;
- case ')':
- regular_expression = popStack(parse_stack);
- if (regular_expression == (RE*) NULL || regular_expression->type == OR_GROUP) {
- error("Too many ) parentheses!", 2);
- }
-
- pushStack(peekStack(parse_stack)->child_stack, regular_expression);
- break;
- case '{':
- lastRE = peekStack(peekStack(parse_stack)->child_stack);
- if (lastRE == (RE*) NULL || lastRE->quantifier.type != EXACTLY_ONE) {
- error("Bracketed quantifier has to follow an exactly one", 2);
- }
-
- i = feedQuantifier(lastRE, i, re, len);
- break;
- case '[':
- regular_expression = createRegularExpression(LITERAL_GROUP, EXACTLY_ONE, re[i]);
- pushStack(peekStack(parse_stack)->child_stack, regular_expression);
-
- i = feedLiteral(regular_expression, i + 1, re, len);
- break;
- case '\\':
- if (++i < len) {
- switch (re[i]) {
- case 'S':
- regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
- regular_expression->child_stack = parse("[^ \n\t\v\f\r]", 9);
- break;
- case 'D':
- regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
- regular_expression->child_stack = parse("[^0-9]", 6);
- break;
- case 'W':
- regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
- regular_expression->child_stack = parse("[^a-zA-Z0-9]", 12);
- break;
- case 's':
- regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
- regular_expression->child_stack = parse("[ \n\t\v\f\r]", 9);
- break;
- case 'd':
- regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
- regular_expression->child_stack = parse("[0-9]", 6);
- break;
- case 'w':
- regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
- regular_expression->child_stack = parse("[a-zA-Z0-9]", 12);
- break;
- case '\0':
- break;
- default:
- regular_expression = createRegularExpression(LITERAL, EXACTLY_ONE, re[i]);
- break;
- }
- pushStack(peekStack(parse_stack)->child_stack, regular_expression);
- }
- break;
- case '|':
- lastRE = popStack(peekStack(parse_stack)->child_stack);
- if (lastRE == (RE*) NULL || lastRE->quantifier.type == NONE) {
- error("| has to follow something", 2);
- }
-
- RE* portal = createRegularExpression(PORTAL, NONE, NONE);
- portal->child_stack = peekStack(parse_stack)->child_stack;
-
- if (lastRE->type != OR_GROUP) {
- regular_expression = createRegularExpression(OR_GROUP, EXACTLY_ONE, re[i]);
- regular_expression->child_stack = createParseStack(DEFAULT_STACK_SIZE / 2);
-
- pushStack(peekStack(parse_stack)->child_stack, regular_expression);
- pushStack(regular_expression->child_stack, lastRE);
- } else {
- pushStack(peekStack(parse_stack)->child_stack, lastRE);
- }
-
- pushStack(parse_stack, portal);
-
- break;
- case '\0':
- break;
- default:
- regular_expression = createRegularExpression(LITERAL, EXACTLY_ONE, re[i]);
- pushStack(peekStack(parse_stack)->child_stack, regular_expression);
- break;
- }
- i++;
- }
-
- if (parse_stack[0]->type > 0) {
- int index = parse_stack[0]->type;
- switch (parse_stack[index]->type) {
- case GROUP:
- error("Incomplete parentheses", 2);
- break;
- case OR_GROUP:
- error("| must have both sides", 2);
- break;
- }
- }
-
- RE** return_stack = parse_stack[0]->child_stack;
-
- free(parse_stack[0]);
- free(parse_stack);
-
- return return_stack;
-}
\ No newline at end of file
diff --git a/src/Test.c b/src/Test.c
deleted file mode 100644
index e2df023..0000000
--- a/src/Test.c
+++ /dev/null
@@ -1,206 +0,0 @@
-#include
-#include
-#include
-#include
-
-BoolState stateMatchesStringAtIndex(RE *state, char *string, size_t len, int i)
-{
- BoolState returnState;
- returnState.consumed = 0;
- returnState.match = 0;
-
- if (i < len)
- {
- switch (state->type)
- {
- case WILDCARD:
- returnState.consumed = 1;
- returnState.match = 1;
- break;
- case LITERAL:
- returnState.match = (state->data == string[i]) ? 1 : 0;
- returnState.consumed = returnState.match;
- break;
- case GROUP:
- return test(state->child_stack, &(string[i]), len - i);
- case LITERAL_GROUP:
- returnState.match = (state->table[(int)string[i]] == 1) ? 1 : returnState.match;
- returnState.consumed = returnState.match;
- break;
- case OR_GROUP:
- // damn, this works :.)
- {
- int index = 1;
- RE* stack[3];
-
- stack[0] = (RE*) NULL;
- stack[2] = (RE*) NULL;
-
- while (state->child_stack[index] != (RE*) NULL) {
- stack[1] = state->child_stack[index];
- returnState = test(stack, &(string)[i], len - i);
- if (returnState.match == 1) { return returnState; }
- index++;
- }
- }
-
- break;
- default:
- error("Unsupported state type", 2);
- break;
- }
- return returnState;
- }
- return returnState;
-}
-
-BoolState test(RE **stack, char *string, size_t len)
-{
- int i = 0;
- int j = 0;
-
- BoolState returnState;
- returnState.consumed = 0;
- returnState.match = 0;
-
- RE *current_state = stack[++j];
- BackStack *back_stack = createBackStack();
-
- unsigned char stopLaziness = 0;
-
- while (current_state != (RE *)NULL)
- {
- BoolState state;
-
- BEGIN:
-
- current_state = stack[j];
-
- if (current_state == (RE*) NULL) { break; }
-
- int matches = current_state->matches;
- int max = current_state->quantifier.max;
- int min = current_state->quantifier.min;
-
- switch (current_state->quantifier.type)
- {
- case EXACTLY_ONE:
- case RANGE:
- while (matches < max)
- {
- if (i >= len)
- {
- break;
- }
-
- state.end = i;
-
- if (matches >= min)
- {
- if (current_state->quantifier.modifier != POSSESSIVE)
- {
- if (current_state->quantifier.modifier == LAZY && stopLaziness == 0) {
- pushBackStack(back_stack, state, current_state->quantifier.modifier, j);
- current_state = stack[++j];
- goto BEGIN;
- } else if (stopLaziness == 0) {
- pushBackStack(back_stack, state, current_state->quantifier.modifier, j);
- }
- }
- }
-
- state = stateMatchesStringAtIndex(current_state, string, len, i);
- if (state.match == 0)
- {
- break;
- }
-
- matches++;
- stopLaziness = 0;
-
- i += state.consumed;
- }
-
- if (matches < min)
- {
- BackState* backState = backtrack(back_stack);
- if (backState != (BackState*) NULL)
- {
- i = backState->index;
- j = backState->stateIndex + 1;
-
- if (backState->backTrackState == LAZY) {
- j--;
- free(backState);
- stopLaziness = 1;
- goto BEGIN;
- }
- free(backState);
-
- continue;
- } else {
-
- resetBackStack(back_stack);
- return returnState;
-
- }
- }
-
- current_state = stack[++j];
- continue;
- default:
- error("Unsupported quantifier", 2);
- }
- }
-
- returnState.consumed = i;
- returnState.match = 1;
-
- resetBackStack(back_stack);
- return returnState;
-}
-
-BoolState *match(RE **stack, char *string, size_t len)
-{
- BoolState *states = (BoolState *)malloc(sizeof(BoolState) * MATCHES_ARRAY);
- if (states == (BoolState *)NULL)
- {
- return (BoolState *)NULL;
- }
-
- int stateIndex = 0;
- size_t curIndex = 0;
-
- while (curIndex < len)
- {
- BoolState state = test(stack, string + curIndex, len - curIndex);
-
- if (state.match == 0 && state.consumed == 0)
- {
- curIndex++;
- }
- else
- {
- states[stateIndex].match = 1;
- states[stateIndex].consumed = curIndex;
-
- curIndex += state.consumed;
- states[stateIndex].end = curIndex;
-
- printf("%.*s Start/End at: %d/%d\n",
- states[stateIndex].end - states[stateIndex].consumed,
- string + states[stateIndex].consumed,
- states[stateIndex].consumed,
- states[stateIndex].end);
-
- stateIndex++;
-
- if (state.consumed == 0)
- {
- curIndex++;
- }
- }
- }
-
- return states;
-}
\ No newline at end of file
diff --git a/src/core/Backtracking.c b/src/core/Backtracking.c
new file mode 100644
index 0000000..1f32833
--- /dev/null
+++ b/src/core/Backtracking.c
@@ -0,0 +1,71 @@
+#include
+#include
+#include
+#include
+
+struct BackStack *createBackStack()
+{
+ struct BackStack *back_stack = (struct BackStack *)malloc(sizeof(struct BackStack));
+ if (back_stack == (struct BackStack *)NULL)
+ {
+ return back_stack;
+ }
+
+ back_stack->index = 0;
+ back_stack->max = BOOLSTACK_SIZE;
+ back_stack->states = (struct BackState **)malloc(sizeof(struct BackState *) * BOOLSTACK_SIZE);
+
+ return back_stack;
+};
+
+void resetBackStack(struct BackStack *stack)
+{
+ if (stack == (struct BackStack *)NULL)
+ {
+ return;
+ }
+ for (int i = 0; i < stack->max; i++)
+ {
+ free(stack->states[i]);
+ }
+ free(stack);
+ return;
+}
+
+struct BackStack *pushBackStack(struct BackStack *back_stack, struct BoolState state, unsigned short backTrackState, unsigned int stateIndex)
+{
+ if (back_stack->index < back_stack->max)
+ {
+
+ struct BackState *newState = (struct BackState *)malloc(sizeof(struct BackState));
+ newState->backTrackState = backTrackState;
+ newState->consumed = state.consumed;
+ newState->index = state.end;
+ newState->stateIndex = stateIndex;
+ back_stack->states[back_stack->index] = newState;
+
+ back_stack->index++;
+
+ return back_stack;
+ }
+
+ error("Bool stack overflow!", FATAL);
+ return (struct BackStack *)NULL;
+};
+
+struct BackState *popBackStack(struct BackStack *back_stack)
+{
+ if (back_stack->index > 0)
+ {
+ back_stack->index--;
+ }
+ struct BackState *poppedState = back_stack->states[back_stack->index];
+ back_stack->states[back_stack->index] = (struct BackState *)NULL;
+ return poppedState;
+}
+
+struct BackState *backtrack(struct BackStack *back_stack)
+{
+ struct BackState *poppedState = popBackStack(back_stack);
+ return poppedState;
+}
\ No newline at end of file
diff --git a/src/core/Error.c b/src/core/Error.c
new file mode 100644
index 0000000..c6372b2
--- /dev/null
+++ b/src/core/Error.c
@@ -0,0 +1,22 @@
+#include
+#include
+
+#include
+
+const static char *ERRORS[] =
+{
+ "Undefined",
+ "Generic",
+ "Fatal"
+};
+
+void error(char *message, unsigned int type)
+{
+ fprintf(stderr, "[ERROR] %s :::: [TYPE] %s\n", message, ERRORS[type]);
+ exit(EXIT_FAILURE);
+}
+
+void warn(char *message) {
+ fprintf(stderr, "[WARNING] %s\n", message);
+ fflush(stdout);
+}
\ No newline at end of file
diff --git a/src/core/LiteralGroup.c b/src/core/LiteralGroup.c
new file mode 100644
index 0000000..1d18872
--- /dev/null
+++ b/src/core/LiteralGroup.c
@@ -0,0 +1,72 @@
+#include
+#include
+#include
+#include
+
+static void activateLiteral(char *table, char literal, char last, int *addr_active_ranging)
+{
+ int index = (int)literal;
+ if ((*addr_active_ranging) == 1)
+ {
+ for (int i = last + 1; i <= literal; i++)
+ {
+ table[i] = 1 - table[i];
+ }
+ (*addr_active_ranging) = 0;
+ return;
+ }
+ table[index] = 1 - table[index];
+}
+
+int feedLiteral(struct RE *regular_expression, size_t i, char *re, size_t len)
+{
+
+ char *table = (char *)calloc(ASCII_TABLE, sizeof(char));
+ if (table == (char *)NULL)
+ {
+ return 0;
+ }
+
+ if (re[i] == '^')
+ {
+ memset(table, 1, sizeof(char) * ASCII_TABLE);
+ }
+
+ char last = '\0';
+ int active_ranging = 0;
+
+ while (i < len)
+ {
+ if (re[i] == ']')
+ {
+ break;
+ }
+
+ if (i + 1 < len - 1)
+ {
+ switch (re[i])
+ {
+ case '\\':
+ activateLiteral(table, re[++i], last, &active_ranging);
+ last = re[i];
+ i++;
+ continue;
+ case '-':
+ active_ranging = 1;
+ i++;
+ continue;
+ default:
+ break;
+ }
+ }
+
+ activateLiteral(table, re[i], last, &active_ranging);
+ last = re[i];
+ i++;
+ }
+
+ table[0] = 0;
+ regular_expression->table = table;
+
+ return i;
+}
\ No newline at end of file
diff --git a/src/core/Quantifier.c b/src/core/Quantifier.c
new file mode 100644
index 0000000..fcad42e
--- /dev/null
+++ b/src/core/Quantifier.c
@@ -0,0 +1,76 @@
+#include
+#include
+#include
+#include
+
+int feedQuantifier(struct RE *regular_expression, size_t i, char *re, size_t len)
+{
+ unsigned int max = 0;
+ unsigned int min = 0;
+
+ unsigned int *place = &min;
+
+ short accessedMin = 0;
+ short accessedMax = 0;
+
+ while (i < len)
+ {
+ switch (re[i])
+ {
+ case '9':
+ case '8':
+ case '7':
+ case '6':
+ case '5':
+ case '4':
+ case '3':
+ case '2':
+ case '1':
+ case '0':
+ (*place) = ((*place) * 10) + (re[i] - 48);
+ if (place == &min)
+ {
+ accessedMin = 1;
+ }
+ else
+ {
+ accessedMax = 1;
+ }
+ break;
+ case ',':
+ place = &max;
+ break;
+ case '}':
+ break;
+ default:
+ error("Symbol not allowed within {}", FATAL);
+ break;
+ }
+ i++;
+ }
+
+ if (accessedMin == 0 && accessedMax == 0)
+ {
+ max = INT32_MAX;
+ }
+ if (accessedMax == 0 && place == &max)
+ {
+ max = INT32_MAX;
+ }
+ if (max < min)
+ {
+ max = min;
+ }
+
+ // Funnily enough, by standards, using {} actually makes sense
+ // for it to match between LARGE_NUMBER and 0
+ // Another reason to not use regex
+ printf("Max: %d // Min: %d\n", max, min);
+
+ regular_expression->quantifier.type = RANGE;
+ regular_expression->quantifier.max = max;
+ regular_expression->quantifier.min = min;
+ regular_expression->quantifier.modifier = GREEDY;
+
+ return i;
+}
\ No newline at end of file
diff --git a/src/core/RegExp.c b/src/core/RegExp.c
new file mode 100644
index 0000000..ed5a308
--- /dev/null
+++ b/src/core/RegExp.c
@@ -0,0 +1,317 @@
+#include
+#include
+#include
+#include
+
+// I am not const'ing everything
+
+struct RE *createRegularExpression(int type, int quantifier, char data)
+{
+ struct RE *regular_expression = (struct RE *)malloc(sizeof(struct RE));
+ if (regular_expression == (struct RE *)NULL)
+ {
+ return (struct RE *)NULL;
+ }
+
+ regular_expression->type = type;
+ regular_expression->data = data;
+ regular_expression->matches = 0;
+
+ regular_expression->quantifier.type = quantifier;
+ regular_expression->quantifier.max = 1;
+ regular_expression->quantifier.min = 1;
+ regular_expression->quantifier.modifier = GREEDY;
+
+ regular_expression->child_stack = (struct RE **)NULL;
+ regular_expression->table = (char *)NULL;
+
+ return regular_expression;
+}
+
+struct RE **createParseStack(int size)
+{
+ //Look, I cast my mallocs; learned it from an old embedded guy
+ struct RE **parse_stack = (struct RE **)malloc(sizeof(struct RE *) * size);
+ if (parse_stack == (struct RE **)NULL || size < 1)
+ {
+ return (struct RE **)NULL;
+ }
+
+ struct RE *first_regexp = createRegularExpression(NONE, NONE, size);
+ parse_stack[0] = first_regexp;
+
+ return parse_stack;
+}
+
+struct RE *pushStack(struct RE **stack, struct RE *regular_expression)
+{
+ if (regular_expression == (struct RE *)NULL)
+ {
+ return (struct RE *)NULL;
+ }
+
+ stack[0]->type++;
+ // I'm not sure I'd find many to approve of this, but
+ // I used the first element of the array as a way to keep track of it
+ // i.e max elements, current index, works fine. In hindsight,
+ // I should have wrapped it in a struct
+ int index = stack[0]->type;
+ // Refactoring is simply too much
+ // I'd rather rewrite with these lessons in mind
+ // The data field contains the max size (DEFAULT_STACK_SIZE) of the regular expression stack
+ // Do not admonish me for the passions of youth
+ if (index >= stack[0]->data)
+ {
+ error("Stack overflow!", FATAL);
+ }
+
+ stack[index] = regular_expression;
+
+ return regular_expression;
+}
+
+struct RE *peekStack(struct RE **stack)
+{
+ int index = stack[0]->type;
+ if (index < 0 || stack[index] == (struct RE *)NULL)
+ {
+ return (struct RE *)NULL;
+ }
+
+ if (stack[index]->type == PORTAL)
+ {
+ struct RE **address = stack[index]->child_stack;
+ free(stack[index]);
+ stack[0]->type--;
+ return peekStack(address);
+ }
+
+ return stack[index];
+}
+
+struct RE *popStack(struct RE **stack)
+{
+ int index = stack[0]->type;
+ if (index < 1)
+ {
+ return (struct RE *)NULL;
+ }
+
+ struct RE *regular_expression = peekStack(stack);
+ stack[0]->type--;
+ return regular_expression;
+}
+
+void debug(struct RE **parseStack, int level)
+{
+ if (parseStack[0] != (struct RE *)NULL)
+ {
+ for (int i = 0; i <= parseStack[0]->type; i++)
+ {
+ printf("LEVEL: %d\n", level);
+ printf("--TYPE: %d\n", parseStack[i]->type);
+ printf("--QUANTIFIER: %d\n", parseStack[i]->quantifier.type);
+ printf("----MODIFIER: %d\n", parseStack[i]->quantifier.modifier);
+ printf("--DATA: %d\n", parseStack[i]->data);
+ printf("--CHILDSTACK: %p\n", parseStack[i]->child_stack);
+ if (parseStack[i]->child_stack != (struct RE **)NULL)
+ {
+ debug(parseStack[i]->child_stack, level + 1);
+ }
+ }
+ }
+}
+
+struct RE **parse(char *re, size_t len)
+{
+
+ struct RE **parse_stack = createParseStack(DEFAULT_STACK_SIZE);
+ if (parse_stack == (struct RE **)NULL)
+ {
+ return (struct RE **)NULL;
+ }
+
+ struct RE **child_stack = createParseStack(DEFAULT_STACK_SIZE);
+ parse_stack[0]->child_stack = child_stack;
+
+ size_t i = 0;
+ while (i < len)
+ {
+ struct RE *regular_expression = (struct RE *)NULL;
+ struct RE *lastRE;
+ switch (re[i])
+ {
+ case '.':
+ regular_expression = createRegularExpression(WILDCARD, EXACTLY_ONE, re[i]);
+ pushStack(peekStack(parse_stack)->child_stack, regular_expression);
+ break;
+ case '?':
+ lastRE = peekStack(peekStack(parse_stack)->child_stack);
+ if (lastRE == (struct RE *)NULL || lastRE->quantifier.type == NONE)
+ {
+ error("? struct Quantifier has to follow something", FATAL);
+ }
+ lastRE->quantifier.modifier = LAZY;
+ if (lastRE->quantifier.type == EXACTLY_ONE)
+ {
+ lastRE->quantifier.type = RANGE;
+ lastRE->quantifier.modifier = GREEDY;
+ lastRE->quantifier.max = 1;
+ lastRE->quantifier.min = 0;
+ }
+ break;
+ case '+':
+ lastRE = peekStack(peekStack(parse_stack)->child_stack);
+ if (lastRE == (struct RE *)NULL || lastRE->quantifier.type == NONE)
+ {
+ error("+ struct Quantifier has to follow something", FATAL);
+ }
+ lastRE->quantifier.modifier = POSSESSIVE;
+ if (lastRE->quantifier.type == EXACTLY_ONE)
+ {
+ lastRE->quantifier.type = RANGE;
+ lastRE->quantifier.modifier = GREEDY;
+ lastRE->quantifier.max = INT16_MAX;
+ lastRE->quantifier.min = 1;
+ }
+ break;
+ case '*':
+ lastRE = peekStack(peekStack(parse_stack)->child_stack);
+ if (lastRE == (struct RE *)NULL || lastRE->quantifier.type == NONE)
+ {
+ error("* struct Quantifier has to follow an exactly one", FATAL);
+ }
+ lastRE->quantifier.modifier = GREEDY;
+ if (lastRE->quantifier.type == EXACTLY_ONE)
+ {
+ lastRE->quantifier.type = RANGE;
+ lastRE->quantifier.modifier = GREEDY;
+ lastRE->quantifier.max = INT16_MAX;
+ lastRE->quantifier.min = 0;
+ }
+ break;
+ case '(':
+ regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
+ regular_expression->child_stack = createParseStack(DEFAULT_STACK_SIZE);
+
+ pushStack(parse_stack, regular_expression);
+ break;
+ case ')':
+ regular_expression = popStack(parse_stack);
+ if (regular_expression == (struct RE *)NULL || regular_expression->type == OR_GROUP)
+ {
+ error("Too many ) parentheses!", FATAL);
+ }
+
+ pushStack(peekStack(parse_stack)->child_stack, regular_expression);
+ break;
+ case '{':
+ lastRE = peekStack(peekStack(parse_stack)->child_stack);
+ if (lastRE == (struct RE *)NULL || lastRE->quantifier.type != EXACTLY_ONE)
+ {
+ error("Bracketed quantifier has to follow an exactly one", FATAL);
+ }
+
+ i = feedQuantifier(lastRE, i + 1, re, len);
+ break;
+ case '[':
+ regular_expression = createRegularExpression(LITERAL_GROUP, EXACTLY_ONE, re[i]);
+ pushStack(peekStack(parse_stack)->child_stack, regular_expression);
+
+ i = feedLiteral(regular_expression, i + 1, re, len);
+ break;
+ case '\\':
+ if (++i < len)
+ {
+ switch (re[i])
+ {
+ case 'S':
+ regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
+ regular_expression->child_stack = parse("[^ \n\t\v\f\r]", 9);
+ break;
+ case 'D':
+ regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
+ regular_expression->child_stack = parse("[^0-9]", 6);
+ break;
+ case 'W':
+ regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
+ regular_expression->child_stack = parse("[^a-zA-Z0-9]", 12);
+ break;
+ case 's':
+ regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
+ regular_expression->child_stack = parse("[ \n\t\v\f\r]", 9);
+ break;
+ case 'd':
+ regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
+ regular_expression->child_stack = parse("[0-9]", 6);
+ break;
+ case 'w':
+ regular_expression = createRegularExpression(GROUP, EXACTLY_ONE, re[i]);
+ regular_expression->child_stack = parse("[a-zA-Z0-9]", 12);
+ break;
+ case '\0':
+ break;
+ default:
+ regular_expression = createRegularExpression(LITERAL, EXACTLY_ONE, re[i]);
+ break;
+ }
+ pushStack(peekStack(parse_stack)->child_stack, regular_expression);
+ }
+ break;
+ case '|':
+ lastRE = popStack(peekStack(parse_stack)->child_stack);
+ if (lastRE == (struct RE *)NULL || lastRE->quantifier.type == NONE)
+ {
+ error("| has to follow something", FATAL);
+ }
+
+ struct RE *portal = createRegularExpression(PORTAL, NONE, NONE);
+ portal->child_stack = peekStack(parse_stack)->child_stack;
+
+ if (lastRE->type != OR_GROUP)
+ {
+ regular_expression = createRegularExpression(OR_GROUP, EXACTLY_ONE, re[i]);
+ regular_expression->child_stack = createParseStack(DEFAULT_STACK_SIZE / 2);
+
+ pushStack(peekStack(parse_stack)->child_stack, regular_expression);
+ pushStack(regular_expression->child_stack, lastRE);
+ }
+ else
+ {
+ pushStack(peekStack(parse_stack)->child_stack, lastRE);
+ }
+
+ pushStack(parse_stack, portal);
+
+ break;
+ case '\0':
+ break;
+ default:
+ regular_expression = createRegularExpression(LITERAL, EXACTLY_ONE, re[i]);
+ pushStack(peekStack(parse_stack)->child_stack, regular_expression);
+ break;
+ }
+ i++;
+ }
+
+ if (parse_stack[0]->type > 0)
+ {
+ int index = parse_stack[0]->type;
+ switch (parse_stack[index]->type)
+ {
+ case GROUP:
+ error("Incomplete parentheses", FATAL);
+ break;
+ case OR_GROUP:
+ error("| must have both sides", FATAL);
+ break;
+ }
+ }
+
+ struct RE **return_stack = parse_stack[0]->child_stack;
+
+ free(parse_stack[0]);
+ free(parse_stack);
+
+ return return_stack;
+}
\ No newline at end of file
diff --git a/src/core/Test.c b/src/core/Test.c
new file mode 100644
index 0000000..a5a66ee
--- /dev/null
+++ b/src/core/Test.c
@@ -0,0 +1,210 @@
+#include
+#include
+#include
+#include
+
+static struct BoolState stateMatchesStringAtIndex(struct RE *state, char *string, size_t len, int i)
+{
+ struct BoolState returnState;
+ returnState.consumed = 0;
+ returnState.match = 0;
+
+ if (i < len)
+ {
+ switch (state->type)
+ {
+ case WILDCARD:
+ returnState.consumed = 1;
+ returnState.match = 1;
+ break;
+ case LITERAL:
+ returnState.match = (state->data == string[i]) ? 1 : 0;
+ returnState.consumed = returnState.match;
+ break;
+ case GROUP:
+ return test(state->child_stack, &(string[i]), len - i);
+ case LITERAL_GROUP:
+ returnState.match = (state->table[(int)string[i]] == 1) ? 1 : returnState.match;
+ returnState.consumed = returnState.match;
+ break;
+ case OR_GROUP:
+ // damn, this works :.)
+ {
+ int index = 1;
+ struct RE *stack[3];
+
+ stack[0] = (struct RE *)NULL;
+ stack[2] = (struct RE *)NULL;
+
+ while (state->child_stack[index] != (struct RE *)NULL)
+ {
+ stack[1] = state->child_stack[index];
+ returnState = test(stack, &(string)[i], len - i);
+ if (returnState.match == 1)
+ {
+ return returnState;
+ }
+ index++;
+ }
+ }
+
+ break;
+ default:
+ error("Unsupported state type", FATAL);
+ break;
+ }
+ return returnState;
+ }
+ return returnState;
+}
+
+struct BoolState test(struct RE **stack, char *string, size_t len)
+{
+ int i = 0;
+ int j = 0;
+
+ struct BoolState returnState;
+ returnState.consumed = 0;
+ returnState.match = 0;
+
+ struct RE *current_state = stack[++j];
+ struct BackStack *back_stack = createBackStack();
+
+ unsigned char stopLaziness = 0;
+
+ while (current_state != (struct RE *)NULL)
+ {
+ struct BoolState state;
+
+ BEGIN_TEST_LOOP:
+
+ current_state = stack[j];
+
+ if (current_state == (struct RE *)NULL)
+ {
+ break;
+ }
+
+ int matches = current_state->matches;
+ int max = current_state->quantifier.max;
+ int min = current_state->quantifier.min;
+
+ switch (current_state->quantifier.type)
+ {
+ case EXACTLY_ONE:
+ case RANGE:
+ while (matches < max)
+ {
+ if (i >= len)
+ {
+ break;
+ }
+
+ state.end = i;
+
+ if (matches >= min
+ && current_state->quantifier.modifier != POSSESSIVE
+ && stopLaziness == 0)
+ {
+ if (current_state->quantifier.modifier == LAZY)
+ {
+ pushBackStack(back_stack, state, current_state->quantifier.modifier, j);
+ current_state = stack[++j];
+ goto BEGIN_TEST_LOOP;
+ }
+ pushBackStack(back_stack, state, current_state->quantifier.modifier, j);
+ }
+
+ state = stateMatchesStringAtIndex(current_state, string, len, i);
+ if (state.match == 0)
+ {
+ break;
+ }
+
+ matches++;
+ stopLaziness = 0;
+
+ i += state.consumed;
+ }
+
+ if (matches < min)
+ {
+ struct BackState *backState = backtrack(back_stack);
+ if (backState == (struct BackState *)NULL)
+ {
+ resetBackStack(back_stack);
+ return returnState;
+ }
+
+ i = backState->index;
+ j = backState->stateIndex + 1;
+
+ if (backState->backTrackState == LAZY)
+ {
+ j--;
+ free(backState);
+ stopLaziness = 1;
+ goto BEGIN_TEST_LOOP;
+ }
+ free(backState);
+
+ continue;
+ }
+
+ current_state = stack[++j];
+ continue;
+ default:
+ error("Unsupported quantifier", FATAL);
+ }
+ }
+
+ returnState.consumed = i;
+ returnState.match = 1;
+
+ resetBackStack(back_stack);
+ return returnState;
+}
+
+struct BoolState *match(struct RE **stack, char *string, size_t len)
+{
+ struct BoolState *states = (struct BoolState *)malloc(sizeof(struct BoolState) * MATCHES_ARRAY);
+ if (states == (struct BoolState *)NULL)
+ {
+ return (struct BoolState *)NULL;
+ }
+
+ int stateIndex = 0;
+ size_t curIndex = 0;
+
+ while (curIndex < len)
+ {
+ struct BoolState state = test(stack, string + curIndex, len - curIndex);
+
+ if (state.match == 0 && state.consumed == 0)
+ {
+ curIndex++;
+ continue;
+ }
+
+ states[stateIndex].match = 1;
+ states[stateIndex].consumed = curIndex;
+
+ curIndex += state.consumed;
+ states[stateIndex].end = curIndex;
+
+ printf("%.*s Start/End at: %d/%d\n",
+ states[stateIndex].end - states[stateIndex].consumed,
+ string + states[stateIndex].consumed,
+ states[stateIndex].consumed,
+ states[stateIndex].end);
+
+ stateIndex++;
+
+ if (state.consumed == 0)
+ {
+ curIndex++;
+ }
+ }
+
+ return states;
+}
\ No newline at end of file
diff --git a/src/interface/FileIO.c b/src/interface/FileIO.c
new file mode 100644
index 0000000..10b222c
--- /dev/null
+++ b/src/interface/FileIO.c
@@ -0,0 +1,2 @@
+#include
+
diff --git a/src/interface/Interface.c b/src/interface/Interface.c
new file mode 100644
index 0000000..fb0e654
--- /dev/null
+++ b/src/interface/Interface.c
@@ -0,0 +1,123 @@
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+/* Keep track of attributes of the shell. */
+
+static pid_t shell_pgid;
+static int shell_terminal;
+static char *currentDirectory;
+static struct termios shell_tmodes;
+
+/* A large deal originates from
+https://github.com/jmreyes/simple-c-shell/blob/master/simple-c-shell.c
+https://www.gnu.org/software/libc/manual/html_node/Initializing-the-Shell.html
+https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_01
+*/
+
+void welcomeScreen()
+{
+ printf("\n\t============================================\n");
+ printf("\t RexEngine Shell\n");
+ printf("\t--------------------------------------------\n");
+ printf("\t Licensed under GPLv3\n");
+ printf("\t============================================\n");
+ printf("\n\n");
+}
+
+void initInterface()
+{
+ /* See if we are running interactively. */
+ shell_terminal = STDIN_FILENO;
+ shell_is_interactive = isatty(shell_terminal);
+
+ if (shell_is_interactive)
+ {
+ /* Loop until we are in the foreground. */
+ while (tcgetpgrp(shell_terminal) != (shell_pgid = getpgrp()))
+ kill(-shell_pgid, SIGTTIN);
+
+ /* Ignore interactive and job-control signals. */
+ signal(SIGQUIT, SIG_IGN);
+ signal(SIGTSTP, SIG_IGN);
+ signal(SIGTTIN, SIG_IGN);
+ signal(SIGTTOU, SIG_IGN);
+ signal(SIGCHLD, SIG_IGN);
+
+ /* Put ourselves in our own process group. */
+ shell_pgid = getpid();
+ if (setpgid(shell_pgid, shell_pgid) < 0)
+ {
+ error("Couldn't put the shell in its own process group", FATAL);
+ }
+
+ /* Grab control of the terminal. */
+ tcsetpgrp(shell_terminal, shell_pgid);
+
+ /* Save default terminal attributes for shell. */
+ tcgetattr(shell_terminal, &shell_tmodes);
+
+ currentDirectory = (char *)calloc(INTERFACE_BUFFER_SIZE * 4, sizeof(char));
+ }
+ shell_pgid = getpid();
+}
+
+char *processFile(char *input_buffer, int actual_buffer_size)
+{
+
+ return NULL;
+}
+
+char *processTerminal(char *input_buffer, int actual_buffer_size)
+{
+ char *secondary_buffer;
+ unsigned int secondary_size;
+ unsigned int index = 0;
+ char c;
+ while (input_buffer != NULL)
+ {
+ c = getchar();
+
+ if (c == EOF || c == '\n')
+ {
+ input_buffer[index] = '\0';
+ lex(input_buffer);
+ return input_buffer;
+ }
+
+ input_buffer[index] = c;
+ index++;
+
+ if (index >= actual_buffer_size)
+ {
+ secondary_size = actual_buffer_size * 2;
+ secondary_buffer = realloc(input_buffer, secondary_size);
+ if (secondary_buffer == NULL)
+ {
+ warn("Input lost, unable to realloc buffer!");
+ index = actual_buffer_size - 1;
+ continue;
+ }
+ input_buffer = secondary_buffer;
+ actual_buffer_size = secondary_size;
+ }
+ }
+ return NULL;
+}
+
+void prompt()
+{
+ // We print the prompt in the form "@ >"
+ // char hostname[INTERFACE_BUFFER / 2] = "";
+ // gethostname(hostname, sizeof(hostname));
+ // printf("%s@%s %s > ", getenv("LOGNAME"), hostname, getcwd(currentDirectory, INTERFACE_BUFFER * 2));
+
+ printf("%s >", getcwd(currentDirectory, INTERFACE_BUFFER_SIZE * 2));
+}
\ No newline at end of file
diff --git a/src/interface/Lexer.c b/src/interface/Lexer.c
new file mode 100644
index 0000000..cefa38b
--- /dev/null
+++ b/src/interface/Lexer.c
@@ -0,0 +1,308 @@
+#include
+#include
+#include
+#include
+#include
+
+const static char *RESERVED_WORDS[] = {
+ "if", "then", "else", "elif", "fi", "do",
+ "done", "case", "esac", "until", "for"
+};
+
+// Shamelessly lifted from https://github.com/rui314/chibicc/blob/main/tokenize.c#L114
+static inline bool startsWith(char *word, char *sequence)
+{
+ return strncmp(word, sequence, strlen(sequence)) == 0;
+}
+
+// Please unroll me, compiler!
+static inline char *inc(char *input)
+{
+ if (startsWith(input, "\\\n")) {
+ return input + 2;
+ }
+ return input + 1;
+}
+
+static char escapedToLiteral(char *input)
+{
+ switch (*input)
+ {
+ case 'a': return '\a';
+ case 'b': return '\b';
+ case 't': return '\t';
+ case 'n': return '\n';
+ case 'v': return '\v';
+ case 'f': return '\f';
+ case 'r': return '\r';
+ case '"': return '\"';
+ case '\'': return '\'';
+ case '\\': return '\\';
+ default: return *input;
+ }
+
+ // Should not be reached
+ return '\0';
+}
+
+static size_t appendToTokenWithBuffer(struct Token *tok, char c)
+{
+ size_t len = strlen(tok->begin);
+ if (len >= tok->span)
+ {
+ char *temp = realloc(tok->begin, tok->span * 2);
+ if (temp == NULL)
+ {
+ error("Cannot realloc token buffer", FATAL);
+ }
+ tok->begin = temp;
+ tok->span *= 2;
+ }
+ *(tok->begin + len) = c;
+ return len;
+}
+
+static struct Token *createTokenWithBuffer(unsigned int size)
+{
+ struct Token *tok = calloc(sizeof(char), sizeof(*tok));
+ char *buffer = malloc(sizeof(char) * size);
+ if (buffer == NULL || tok == NULL)
+ {
+ error("Could not allocate new token with buffer", FATAL);
+ }
+ tok->begin = buffer;
+ tok->span = size;
+ return tok;
+}
+
+static struct Token *processWord(char **input)
+{
+ struct Token *tok = createTokenWithBuffer(CHAR_BUFFER_SIZE);
+ tok->id = WORD;
+
+ bool onlyDigits = true;
+
+ while (**input != '\0')
+ {
+
+ switch (**input)
+ {
+ case '<':
+ case '>':
+ if (onlyDigits)
+ {
+ tok->id = IO_NUMBER;
+ return tok;
+ }
+ case '!':
+ case '=':
+ case '&':
+ case '|':
+ case '{':
+ case '}':
+ case ';':
+ case '\n':
+ case '\r':
+ case '\v':
+ case '\f':
+ case '\t':
+ case ' ':
+ return tok;
+ case '\\':
+ (*input)++;
+ char c = escapedToLiteral(*input);
+ appendToTokenWithBuffer(tok, c);
+ break;
+ default:
+ appendToTokenWithBuffer(tok, **input);
+ break;
+ }
+
+ if (!(**input >= '0' && **input <= '9'))
+ {
+ onlyDigits = false;
+ }
+
+ (*input)++;
+ }
+
+ return tok;
+}
+
+static struct Token *processName(char **input)
+{
+ struct Token *tok = createTokenWithBuffer(CHAR_BUFFER_SIZE);
+ tok->id = NAME;
+
+ while (**input == '_'
+ || (**input >= 'A' && **input <= 'Z')
+ || (**input >= 'a' && **input <= 'z')
+ || (**input >= '0' && **input <= '9'))
+ {
+ appendToTokenWithBuffer(tok, **input);
+ (*input)++;
+ }
+
+ return tok;
+}
+
+static struct Token *processDoubleQuotes(char **input) {
+ struct Token *tok = createTokenWithBuffer(CHAR_BUFFER_SIZE);
+ tok->id = WORD;
+
+ (*input)++;
+
+ appendToTokenWithBuffer(tok, '\"');
+
+ while (**input != '\"') {
+ if (**input == '\0')
+ {
+ error("End reached before closing double quotes", FATAL);
+ }
+ switch (**input) {
+ case '\\':
+ (*input)++;
+ if (**input == '\n') break;
+
+ char c = escapedToLiteral(*input);
+ appendToTokenWithBuffer(tok, c);
+ break;
+ case '$':
+ // TODO
+ case '`':
+ // far future TODO
+ default:
+ appendToTokenWithBuffer(tok, **input);
+ break;
+ }
+ (*input)++;
+ }
+
+ (*input)++;
+
+ appendToTokenWithBuffer(tok, '\"');
+
+ return tok;
+}
+
+static struct Token *processSingleQuotes(char **input) {
+ struct Token *tok = malloc(sizeof(*tok));
+ tok->begin = *input;
+ tok->id = WORD;
+
+ unsigned int i = 0;
+ (*input)++;
+ i++;
+
+ while (**input != '\'') {
+ if (**input == '\0')
+ {
+ error("End reached before closing single quote", FATAL);
+ }
+ (*input)++;
+ i++;
+ }
+ (*input)++;
+
+ tok->span = i;
+ return tok;
+}
+
+struct Token *lex(char *input)
+{
+ if (input == NULL || *input == '\0')
+ {
+ error("Cannot parse empty input", FATAL);
+ }
+
+ struct Token head = {};
+ struct Token *tok = &head;
+
+ while (*input != '\0')
+ {
+ switch (*input)
+ {
+ case '#':
+ // C taste
+ for (; *input != '\n' && *input != '\0'; input++);
+ continue;
+ case '/':
+ if (startsWith(input, "/*"))
+ {
+ char *closer = strstr(input + 2, "*/");
+ if (closer == NULL)
+ {
+ error("Unclosed multiline comment somewhere", FATAL);
+ }
+ input = closer + 2;
+ continue;
+ }
+ error("Why is there a random / somehwhere", FATAL);
+ case '\'':
+ tok->next = processSingleQuotes(&input);
+ tok = tok->next;
+ continue;
+ case '\"':
+ tok->next = processDoubleQuotes(&input);
+ tok = tok->next;
+ continue;
+ case '$':
+ if (startsWith(input, "$("))
+ {
+ // TODO
+ }
+ case '`':
+ // far future TODO
+ input = inc(input);
+ continue;
+ case '\n':
+ {
+ struct Token *newln = createTokenWithBuffer(1);
+ newln->begin = input;
+ newln->span = 0;
+ newln->id = NEWLINE;
+ tok->next = newln;
+ tok = tok->next;
+ }
+ case '\r':
+ case '\v':
+ case '\f':
+ case '\t':
+ case ' ':
+ input = inc(input);
+ continue;
+ case '<':
+ case '>':
+ case '!':
+ case '=':
+ case '&':
+ case '|':
+ case '{':
+ case '}':
+ case '[':
+ case ']':
+ case ';':
+ // operator
+ input = inc(input);
+ continue;
+ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
+ case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
+ case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
+ case 'V': case 'W': case 'X': case 'Y': case 'Z':
+ case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
+ case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
+ case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
+ case 'v': case 'w': case 'x': case 'y': case 'z':
+ case '_':
+ tok->next = processName(&input);
+ tok = tok->next;
+ continue;
+ default:
+ tok->next = processWord(&input);
+ tok = tok->next;
+ break;
+ }
+ }
+
+ return head.next;
+}
\ No newline at end of file
diff --git a/src/utils/HashTable.c b/src/utils/HashTable.c
new file mode 100644
index 0000000..71a1b96
--- /dev/null
+++ b/src/utils/HashTable.c
@@ -0,0 +1,368 @@
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+// TODO: implement this paper https://cseweb.ucsd.edu//~tullsen/horton.pdf
+
+/*
+First, str is dereferenced to get the character it points to. This character is
+assigned to c. str is then advanced to the next character. Finally (and this is the part you care about),
+the value in c is checked against the null character, which is the test condition for the while loop.
+*/
+
+// This hash works on 32-bit so make sure uint32_t
+
+uint32_t djb2(const char *str)
+{
+ uint32_t hash = 5381;
+ uint32_t c;
+ while ((c = *str++))
+ hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
+ return hash;
+}
+
+uint32_t djb2_xor(const char *str)
+{
+ uint32_t hash = 5381;
+ uint32_t c;
+ while ((c = *str++))
+ hash = ((hash << 5) + hash) ^ c; /* hash * 33 ^ c */
+ return hash;
+}
+
+uint32_t djb2_hash(const char *str)
+{
+ uint32_t hash = 5381;
+ uint8_t *s = (uint8_t *) str;
+ uint32_t c = *s;
+ while (c)
+ {
+ hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
+ s++;
+ c = *s;
+ }
+ return hash;
+}
+
+uint32_t djb2_xor_hash(const char *str)
+{
+ uint32_t hash = 5381;
+ uint8_t *s = (uint8_t *) str;
+ uint32_t c = *s;
+ while (c)
+ {
+ hash = ((hash << 5) + hash) ^ c; /* hash * 33 ^ c */
+ s++;
+ c = *s;
+ }
+ return hash;
+}
+
+/*SACRED CODE*/
+
+// http://www.azillionmonkeys.com/qed/hash.html
+// Thanks to Paul Hsiesh
+
+#if !defined (get16bits)
+#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
+ +(uint32_t)(((const uint8_t *)(d))[0]) )
+#endif
+
+uint32_t SuperFastHash (const char * data, int len) {
+uint32_t hash = len, tmp;
+int rem;
+
+ if (len <= 0 || data == NULL) return 0;
+
+ rem = len & 3;
+ len >>= 2;
+
+ /* Main loop */
+ for (;len > 0; len--) {
+ hash += get16bits (data);
+ tmp = (get16bits (data+2) << 11) ^ hash;
+ hash = (hash << 16) ^ tmp;
+ data += 2*sizeof (uint16_t);
+ hash += hash >> 11;
+ }
+
+ /* Handle end cases */
+ switch (rem) {
+ case 3: hash += get16bits (data);
+ hash ^= hash << 16;
+ hash ^= ((signed char)data[sizeof (uint16_t)]) << 18;
+ hash += hash >> 11;
+ break;
+ case 2: hash += get16bits (data);
+ hash ^= hash << 11;
+ hash += hash >> 17;
+ break;
+ case 1: hash += (signed char)*data;
+ hash ^= hash << 10;
+ hash += hash >> 1;
+ }
+
+ /* Force "avalanching" of final 127 bits */
+ hash ^= hash << 3;
+ hash += hash >> 5;
+ hash ^= hash << 4;
+ hash += hash >> 17;
+ hash ^= hash << 25;
+ hash += hash >> 6;
+
+ return hash;
+}
+
+/*SACRED CODE*/
+
+uint32_t fnv_1_hash(const char *str)
+{
+ uint32_t hash = 0x811c9dc5;
+ uint8_t c;
+ while ((c = *str++))
+ {
+ hash *= 0x01000193;
+ hash ^= c;
+ }
+ return hash;
+}
+
+uint32_t fnv_1a_hash(const char *str)
+{
+ uint32_t hash = 0x811c9dc5;
+ uint8_t c;
+ while ((c = *str++))
+ {
+ hash ^= c;
+ hash *= 0x01000193;
+ }
+ return hash;
+}
+
+// HASHTABLE STUFF BELOW
+
+struct bch_table *make_bch_table(
+ size_t buckets, size_t bucket_slots,
+ size_t table_count, ...)
+{
+ struct bch_table *table = malloc(sizeof(*table));
+ if (!table) exit(EXIT_FAILURE);
+
+ table->info.used = 0;
+ table->info.buckets = buckets;
+ table->info.bucket_slots = bucket_slots;
+ table->table_count = table_count;
+ table->tables = malloc(sizeof(struct bch_buckets) * table_count);
+ if (!table->tables) exit(EXIT_FAILURE);
+
+ va_list ptr;
+ va_start(ptr, table_count);
+ for (size_t i = 0; i < table_count; i++)
+ {
+ HASH_BITS (*hash_f)(const char *) = va_arg(ptr, HASH_BITS (*)(const char *));
+ table->tables[i].hash_f = hash_f;
+ table->tables[i].bucket = malloc(sizeof(struct bch_llist_bucket) * buckets);
+ if (!table->tables[i].bucket) exit(EXIT_FAILURE);
+
+ for (size_t j = 0; j < buckets; j++)
+ {
+ table->tables[i].bucket[j].slot = NULL;
+ table->tables[i].bucket[j].slots_used = 0;
+ }
+ }
+ va_end(ptr);
+ return table;
+}
+
+static inline struct bch_llist_slot *_bch_find(
+ struct bch_llist_bucket *buckets, size_t index, const char *key)
+{
+ for (struct bch_llist_slot *p = buckets[index].slot; p; p = p->next)
+ if (strncmp(key, p->key, strlen(key)) == 0) return p;
+ return NULL;
+}
+
+struct bch_llist_slot *find_bch_table(
+ struct bch_table *table, const char *key)
+{
+ for (size_t i = 0; i < table->table_count; i++)
+ {
+ struct bch_buckets *current = table->tables + i;
+ size_t index = (current->hash_f)(key) % table->info.buckets;
+ struct bch_llist_slot *s = _bch_find(current->bucket, index, key);
+ if (s) return s;
+ }
+ return NULL;
+}
+
+static inline void swap_ptr(
+ void **a, void **b)
+{
+ void *temp = *a;
+ *a = *b;
+ *b = temp;
+}
+
+static inline void _swap_slots(
+ struct bch_llist_slot *a, struct bch_llist_slot *b)
+{
+ b->next = a->next;
+ a->next = b;
+
+ swap_ptr(&b->data, &a->data);
+ swap_ptr(&b->key, &a->key);
+}
+
+static inline struct bch_llist_slot *make_bch_slot(
+ void *data, const char *key)
+{
+ struct bch_llist_slot *slot = malloc(sizeof(*slot));
+ if (!slot) exit(EXIT_FAILURE);
+
+ slot->data = data;
+ slot->key = strndup(key, strlen(key));
+ if (!slot->key) exit(EXIT_FAILURE);
+
+ slot->next = NULL;
+ return slot;
+}
+
+static inline struct bch_llist_slot *_bch_insert(
+ struct bch_table *table, struct bch_llist_bucket *buckets,
+ struct bch_llist_slot *slot)
+{
+ table->info.used++;
+ buckets->slots_used++;
+ struct bch_llist_bucket *b = buckets;
+ struct bch_llist_slot *p = b->slot;
+ struct bch_llist_slot *d = slot;
+ if (p)
+ {
+ _swap_slots(p, d);
+ }
+ else
+ {
+ b->slot = d;
+ p = d;
+ }
+ return p;
+}
+
+static inline struct bch_llist_slot *_pop_last(
+ struct bch_llist_bucket *bucket)
+{
+ bucket->slots_used--;
+ struct bch_llist_slot *prev = bucket->slot;
+ struct bch_llist_slot *h = prev;
+ for (; h->next; h = h->next) prev = h;
+ prev->next = NULL;
+ return h;
+}
+
+struct bch_llist_slot *insert_bch_table(
+ struct bch_table *table, const char *key, void* value)
+{
+ struct bch_llist_slot *p;
+ if ((p = find_bch_table(table, key))) return p;
+
+ size_t cycles = 0;
+ size_t t_index = 0;
+ struct bch_llist_slot *result;
+ p = make_bch_slot(value, key);
+ while (p)
+ {
+ struct bch_buckets *current = table->tables + t_index;
+ size_t index = (current->hash_f)(key) % table->info.buckets;
+ struct bch_llist_bucket *b = current->bucket + index;
+ if (b->slots_used < 1)
+ {
+ result = _bch_insert(table, b, p);
+ break;
+ }
+ if (cycles >= table->info.buckets)
+ {
+ if (b->slots_used < table->info.bucket_slots) {
+ result = _bch_insert(table, b, p);
+ break;
+ }
+ result = _bch_insert(table, b, p);
+ p = _pop_last(b);
+ }
+ t_index = (t_index + 1) % table->info.buckets;
+ cycles++;
+ }
+ return result;
+}
+
+struct bch_llist_bucket *remove_bch_table(
+ struct bch_table *table, const char *key)
+{
+ for (size_t i = 0; i < table->table_count; i++)
+ {
+ struct bch_buckets *current = table->tables + i;
+ size_t index = (current->hash_f)(key) % table->info.buckets;
+ struct bch_llist_bucket *bucket = current->bucket + index;
+ struct bch_llist_slot *s = bucket->slot;
+ struct bch_llist_slot *p = s;
+ while (s)
+ {
+ if (strncmp(key, s->key, strlen(key)) == 0)
+ {
+ p->next = s->next;
+ free(s->data);
+ free(s->key);
+ free(s);
+ bucket->slots_used--;
+ table->info.used--;
+ if (!s->next) bucket->slot = NULL;
+ return bucket;
+ }
+ p = s;
+ s = s->next;
+ }
+ }
+ return NULL;
+}
+
+static inline void purge_bucket(
+ struct bch_llist_bucket *bucket
+)
+{
+ struct bch_llist_slot *slot = bucket->slot;
+ while (slot)
+ {
+ struct bch_llist_slot *next = slot->next;
+ if (slot->data) free(slot->data);
+ if (slot->key) free(slot->key);
+ free(slot);
+ slot = next;
+ }
+}
+
+static inline void purge_table(
+ struct bch_table *table, struct bch_buckets *bucket
+)
+{
+ for (size_t i = 0; i < table->info.buckets; i++)
+ {
+ purge_bucket(bucket->bucket + i);
+ }
+ free(bucket->bucket);
+}
+
+bool destroy_bch_table(
+ struct bch_table *table)
+{
+ for (size_t i = 0; i < table->table_count; i++)
+ {
+ struct bch_buckets *current = table->tables + i;
+ purge_table(table, current);
+ }
+ free(table->tables);
+ free(table);
+ return true;
+}
\ No newline at end of file
diff --git a/test/Makefile b/test/Makefile
new file mode 100644
index 0000000..c29a52a
--- /dev/null
+++ b/test/Makefile
@@ -0,0 +1,23 @@
+rootdir = $(realpath ..)
+inc_dir = $(rootdir)/include
+
+INCLUDE_DIRS = $(rootdir) $(inc_dir)
+INCLUDE_FLAGS = $(foreach dir,$(INCLUDE_DIRS),-I$(dir))
+
+FLAGS = -Wall
+
+SRCS = $(shell find ./ -name '*.c')
+OUTS = $(SRCS:%.c=%.test)
+
+.PHONY = test build clean
+
+test: clean build
+
+build: $(OUTS)
+ $(foreach tst,$^,./$(tst);)
+
+%.test: %.c
+ @gcc $(INCLUDE_FLAGS) $(FLAGS) -L"ihct" -rpath "ihct" -lihct -o $@ $<
+
+clean:
+ @-rm *.test
\ No newline at end of file
diff --git a/test/TestHashTable.c b/test/TestHashTable.c
new file mode 100644
index 0000000..ef6e2bc
--- /dev/null
+++ b/test/TestHashTable.c
@@ -0,0 +1,67 @@
+#include "ihct/ihct.h"
+#include "src/utils/HashTable.c"
+
+#if __INTELLISENSE__
+#pragma diag_suppress 1094
+#endif
+
+static inline void addTableHelper(
+ struct bch_table *table, const char *key, const char *value)
+{
+ const char *test_key = key;
+ const char *test_value = strndup(value, strlen(value));
+ struct bch_llist_slot *item = insert_bch_table(table, test_key, test_value);
+ if (item) printf("Key: %s || Value: %s\n", item->key, item->data);
+}
+
+IHCT_TEST(hash_test3)
+{
+ struct bch_table *table = make_bch_table(64, 4, 2, &fnv_1_hash, &fnv_1a_hash);
+ addTableHelper(table, "army", "ranger");
+ addTableHelper(table, "army", "ranger");
+ addTableHelper(table, "nap", "ster");
+ addTableHelper(table, "berlin", "versailles");
+ addTableHelper(table, "karl", "marx");
+ addTableHelper(table, "8=D", "^69");
+ addTableHelper(table, "420", "herb");
+ addTableHelper(table, "green", "fn");
+ addTableHelper(table, "alksdadawdad", "adniaw820");
+ addTableHelper(table, "alexander", "t");
+ printf("Used: %lu\n", table->info.used);
+ struct bch_llist_slot *s = find_bch_table(table, "army");
+ printf("Found: %p\n", s);
+ if (s) printf("Found data: %s\n", s->data);
+ remove_bch_table(table, "army");
+ printf("Used: %lu\n", table->info.used);
+ destroy_bch_table(table);
+ IHCT_PASS();
+}
+
+IHCT_TEST(hash_test2)
+{
+ unsigned long hash0 = djb2_hash("ab");
+ unsigned long hash1 = djb2_hash("bA");
+ const char test_string[] = "test";
+ unsigned long hash = djb2(test_string);
+ unsigned long correct = 0x7c9e6865;
+ IHCT_ASSERT(correct == hash);
+ IHCT_ASSERT(hash0 == hash1);
+}
+
+IHCT_TEST(hash_test1)
+{
+ unsigned long hash0 = djb2_xor("alexander");
+ unsigned long hash1 = djb2_xor_hash("alexander");
+ IHCT_ASSERT(hash0 == hash1);
+}
+
+IHCT_TEST(hash_test0)
+{
+ unsigned long hash = fnv_1_hash("geronimo");
+ unsigned long correct = 0x04224043;
+ IHCT_ASSERT(correct == hash);
+}
+
+int main(int argc, char **argv) {
+ return IHCT_RUN(argc, argv);
+}
\ No newline at end of file
diff --git a/test/TestHashTable.test b/test/TestHashTable.test
new file mode 100755
index 0000000..4cb6c82
Binary files /dev/null and b/test/TestHashTable.test differ
diff --git a/test/TestStringLex.c b/test/TestStringLex.c
new file mode 100644
index 0000000..12b29f8
--- /dev/null
+++ b/test/TestStringLex.c
@@ -0,0 +1,69 @@
+#include "ihct/ihct.h"
+#include "src/core/Error.c"
+#include "src/interface/Lexer.c"
+
+// Courtesy of https://github.com/microsoft/vscode-cpptools/issues/4503https://github.com/microsoft/vscode-cpptools/issues/4503
+// Some unresolved issue with intellisense since 2019
+#if __INTELLISENSE__
+#pragma diag_suppress 1094
+#endif
+
+IHCT_TEST(string_test4)
+{
+ char string[] = "\" \\n \\\\ \\\" \\\n still \"";
+ char *test_string = string;
+ char valid_string[] = "\" \n \\ \" still \"";
+ TokenType valid_token_type = WORD;
+ struct Token *token = processDoubleQuotes(&test_string);
+ IHCT_ASSERT(valid_token_type == token->id);
+ IHCT_ASSERT(strncmp(valid_string, token->begin, token->span) == 0);
+ IHCT_ASSERT(strlen(valid_string) == strlen(token->begin));
+}
+
+IHCT_TEST(string_test3)
+{
+ char string[] = "\"this is a double quoted string\"";
+ char *test_string = string;
+ TokenType valid_token_type = WORD;
+ struct Token *token = processDoubleQuotes(&test_string);
+ IHCT_ASSERT(valid_token_type == token->id);
+ IHCT_ASSERT(strncmp(string, token->begin, token->span) == 0);
+ IHCT_ASSERT(strlen(string) == strlen(token->begin));
+}
+
+IHCT_TEST(string_test2)
+{
+ char string[] = "\'\'\'";
+ char *test_string = string;
+ TokenType valid_token_type = WORD;
+ struct Token *token = processSingleQuotes(&test_string);
+ IHCT_ASSERT(valid_token_type == token->id);
+ IHCT_ASSERT(strncmp(string, token->begin, token->span) == 0);
+ IHCT_ASSERT(strlen(string) != token->span + 1);
+}
+
+IHCT_TEST(string_test1)
+{
+ char string[] = "\'string \\\n980:{>\'";
+ char *test_string = string;
+ TokenType valid_token_type = WORD;
+ struct Token *token = processSingleQuotes(&test_string);
+ IHCT_ASSERT(valid_token_type == token->id);
+ IHCT_ASSERT(strncmp(string, token->begin, token->span) == 0);
+ IHCT_ASSERT(strlen(string) == token->span + 1);
+}
+
+IHCT_TEST(string_test0)
+{
+ char string[] = "\'this is a string\'";
+ char *test_string = string;
+ TokenType valid_token_type = WORD;
+ struct Token *token = processSingleQuotes(&test_string);
+ IHCT_ASSERT(valid_token_type == token->id);
+ IHCT_ASSERT(strncmp(string, token->begin, token->span) == 0);
+ IHCT_ASSERT(strlen(string) == token->span + 1);
+}
+
+int main(int argc, char **argv) {
+ return IHCT_RUN(argc, argv);
+}
\ No newline at end of file
diff --git a/test/TestStringLex.test b/test/TestStringLex.test
new file mode 100755
index 0000000..c4564c9
Binary files /dev/null and b/test/TestStringLex.test differ
diff --git a/test/ihct/ihct.h b/test/ihct/ihct.h
new file mode 100644
index 0000000..957145e
--- /dev/null
+++ b/test/ihct/ihct.h
@@ -0,0 +1,151 @@
+#ifndef IHCT_H
+#define IHCT_H
+
+#include
+#include
+#include
+
+// Structure for a testunits return value. Contains state, the code (assert) which
+// failed the test, and a reference to where the code is.
+typedef struct {
+ enum {PASS, FAIL, FAIL_FORCE, ERR, TIMEOUT} status;
+ char *code;
+ char *file;
+ unsigned long line;
+} ihct_test_result;
+
+// Short for a function returning a test_result pointer, with no arguments.
+typedef void (*ihct_test_proc)(ihct_test_result *);
+
+// Called within a test.
+bool ihct_assert_impl(bool eval, ihct_test_result *result, char *code, char *file,
+ unsigned long line);
+
+void ihct_pass_impl(ihct_test_result *result, char *file, unsigned long line);
+void ihct_fail_impl(ihct_test_result *result, char *file, unsigned long line);
+
+// Called on test unit construction.
+void ihct_construct_test_impl(char *s, ihct_test_proc proc);
+
+// Runs all tests.
+int ihct_run(int argc, char **argv);
+
+// Initializes the unitlist (Has to be done before all testing units are created).
+// Using priority to ensure that the unit list is constructed before it gets populated.
+void ihct_init(void) __attribute__((constructor(101)));
+
+// Assertions
+/// @defgroup assertions Assertions
+/// @brief Wraps all assertions.
+///
+/// Decides the success of a test. Right now, tests can only result in
+/// PASS or FAIL. Assertions are only given for expressions.
+
+/// @brief Asserts a statement inside a test unit. If the expression is false,
+/// the unit will fail the test.
+/// @ingroup assertions
+/// @param expr the expression to evaluate.
+///
+/// Can be shortened to remove 'IHCT_' prefix by defining IHCT_SHORT.
+#define IHCT_ASSERT(expr) \
+ if(!ihct_assert_impl(expr, result, #expr, __FILE__, __LINE__)) return
+
+/// @brief Asserts a statement inside a test unit. If the expression is true,
+/// the unit will fail the test.
+/// @ingroup assertions
+/// @param expr the expression to evaluate.
+///
+/// Can be shortened to remove 'IHCT_' prefix by defining IHCT_SHORT.
+#define IHCT_NASSERT(expr) \
+ if(!ihct_assert_impl(!expr, result, "!(" #expr ")", __FILE__, __LINE__)) return
+
+/// @brief Asserts two strings inside a test unit to be equal. If there is any difference
+/// in the strings, the unit will fail the test.
+/// @ingroup assertions
+/// @param s1 first string to compare
+/// @param s2 second string to compare
+///
+/// Can be shortened to remove 'IHCT_' prefix by defining IHCT_SHORT.
+#define IHCT_ASSERT_STR(s1, s2) \
+ if(!ihct_assert_impl(!strcmp(s1, s2), result, #s1 " == " #s2, __FILE__, \
+ __LINE__)) return
+/// @brief Asserts two strings inside a test unit not to be equal. If there is any
+/// difference in the strings, the unit will fail the test.
+/// @ingroup assertions
+/// @param s1 first string to compare
+/// @param s2 second string to compare
+///
+/// Can be shortened to remove 'IHCT_' prefix by defining IHCT_SHORT.
+#define IHCT_NASSERT_STR(s1, s2) \
+ if(!ihct_assert_impl(strcmp(s1, s2), result, #s1 " != " #s2, __FILE__, \
+ __LINE__)) return
+
+/// @brief Set the test as passed and return.
+/// @ingroup assertions
+///
+/// Used for more complex tests where the PASS/FAIL status is more complex
+/// than an assert. Can be shortened to remove 'IHCT_' prefix by defining IHCT_SHORT.
+#define IHCT_PASS() \
+ do { ihct_pass_impl(result, __FILE__, __LINE__); return; } while(0)
+
+/// @brief Set the test as failed and return.
+/// @ingroup assertions
+///
+/// Used for more complex tests where the PASS/FAIL status is more complex
+/// than an assert. Can be shortened to remove 'IHCT_' prefix by defining IHCT_SHORT.
+#define IHCT_FAIL() \
+ do { ihct_fail_impl(result, __FILE__, __LINE__); return; } while(0)
+
+// Function macros
+/// @defgroup funcs Testing functions
+/// @brief More general macros for function.
+
+/// @brief Runs all tests. Is to be called once in the main entrypoint.
+/// @ingroup funcs
+/// @code
+/// int main(int argc, char **argv) {
+/// return IHCT_RUN(argc, argv);
+/// }
+/// @endcode
+/// @param argc argument count, directly passed from main.
+/// @param argv argument array, directly passed from main.
+#define IHCT_RUN(argc, argv) \
+ ihct_run(argc, argv)
+
+// Create a new test unit, and adds it using 'ihct_add_test'.
+/// @brief Create a new test unit, which can take any number of asserts.
+/// @ingroup funcs
+/// @code
+/// IHCT_TEST(basic_test) {
+/// IHCT_ASSERT(1 == 1);
+/// }
+/// @endcode
+/// @param name the name of the test.
+///
+/// Can be shortened to remove 'IHCT_' prefix by defining IHCT_SHORT.
+#define IHCT_TEST(name) \
+ static void test_##name(ihct_test_result *result); \
+ static void __attribute__((constructor(102))) __construct_test_##name(void) { \
+ ihct_construct_test_impl(#name, &test_##name); \
+ } \
+ static void test_##name(ihct_test_result *result)
+
+/// @brief Defines a fixture with data to be preloaded before a test.
+/// A ficture is included by a IHCT_REQUIRE inside a test.
+#define IHCT_FIXTURE(name) _Static_assert(0, "Fixtures not implemented.")
+
+/// @brief Make the test require the given fixtures.
+/// @param ... one or more fixture names.
+#define IHCT_REQUIRE(...) _Static_assert(0, "Fixture requirements not implemented.")
+
+#ifdef IHCT_SHORT
+#define TEST(name) IHCT_TEST(name)
+#define ASSERT(expr) IHCT_ASSERT(expr)
+#define NASSERT(expr) IHCT_NASSERT(expr)
+#define ASSERT_STR(s1, s2) IHCT_ASSERT_STR(s1, s2)
+#define NASSERT_STR(s1, s2) IHCT_NASSERT_STR(s1, s2)
+#define PASS() IHCT_PASS()
+#define FAIL() IHCT_FAIL()
+#endif
+
+#endif
\ No newline at end of file
diff --git a/test/ihct/libihct.dylib b/test/ihct/libihct.dylib
new file mode 100755
index 0000000..8d89c2e
Binary files /dev/null and b/test/ihct/libihct.dylib differ
diff --git a/test/misc/example.rx b/test/misc/example.rx
new file mode 100644
index 0000000..2b078a0
--- /dev/null
+++ b/test/misc/example.rx
@@ -0,0 +1,3 @@
+if [ true && true ]
+then echo "cheese"
+else echo "pizza"
\ No newline at end of file