From 71a09170c9e59710a6e0e8dd25070b3231aa7219 Mon Sep 17 00:00:00 2001 From: Elara Musayelyan Date: Sat, 28 Oct 2023 18:10:17 -0700 Subject: [PATCH] Initial Commit --- .gitignore | 2 + LICENSE | 674 +++++++ README.md | 77 + examples/readme/main.go | 71 + examples/readme/readme.salix.html | 16 + examples/replybot/main.go | 36 + examples/replybot/replybot.salix.txt | 8 + expr.go | 166 ++ for_tag.go | 110 ++ funcs.go | 31 + go.mod | 3 + go.sum | 0 if_tag.go | 118 ++ internal/ast/ast.go | 201 ++ internal/parser/gen.go | 3 + internal/parser/parser.go | 2713 ++++++++++++++++++++++++++ internal/parser/salix.peg | 220 +++ parse.go | 52 + salix.go | 445 +++++ tags.go | 45 + 20 files changed, 4991 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 examples/readme/main.go create mode 100644 examples/readme/readme.salix.html create mode 100644 examples/replybot/main.go create mode 100644 examples/replybot/replybot.salix.txt create mode 100644 expr.go create mode 100644 for_tag.go create mode 100644 funcs.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 if_tag.go create mode 100644 internal/ast/ast.go create mode 100644 internal/parser/gen.go create mode 100644 internal/parser/parser.go create mode 100644 internal/parser/salix.peg create mode 100644 parse.go create mode 100644 salix.go create mode 100644 tags.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4301ce5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/readme +/replybot \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..1840fd9 --- /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/README.md b/README.md new file mode 100644 index 0000000..bb3eb9f --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +# Salix + +Salix (pronounced *say-lix*) is a Go templating engine inspired by [Leaf](https://github.com/vapor/leaf). + +Salix's syntax is similar to Leaf and (in my opinion at least), it's much more fun to write than the Go template syntax. If you like this project, please star the repo. I hope you enjoy! :) + +## Examples + +### Template + +```html + + + #(page.Title) + + + #for(i, user in users): +
+

#(toLower(user.Name))

+

User ID: #(i)

+ #if(user.LoggedIn):

This user is logged in

#!if + #if(user.IsAdmin):

This user is an admin!

#!if +

Registered: #(user.RegisteredTime.Format("01-02-2006"))

+
+ #!for + + +``` + +### API Usage + +```go +t, err := salix.New(). + WithVarMap(vars). + WithFuncMap(funcs). + WithEscapeHTML(true). + ParseFile("example.salix.txt") +if err != nil { + panic(err) +} + +err = t.Execute(os.Stdout) +if err != nil { + panic(err) +} +``` + +See the [examples](examples) directory for more examples. + +## Functions + +Functions that are used in a template can have any amount of arguments, but cannot have more than two return values. If a function has two return values, the second one must be an error value. + +Salix includes the following default functions in all templates: + +- `len(v any) int`: Returns the length of the value passed in. If the length cannot be found, it returns `-1`. +- `toUpper(s string) string`: Returns `s`, but with all characters mapped to their uppercase equivalents. +- `toLower(s string) string`: Returns `s`, but with all characters mapped to their lowercase equivalents. +- `hasPrefix(s, prefix string) bool`: Returns true if `s` starts with `prefix`. +- `trimPrefix(s, prefix string) string`: Returns `s`, but with `prefix` removed from the beginning. +- `hasSuffix(s, suffix string) bool`: Returns true if `s` ends with `suffix`. +- `trimSuffix(s, suffix string) string`: Returns `s`, but with `suffix` removed from the end. +- `trimSpace(s string) string`: Returns `s`, but with any whitespace characters removed from the beginning and end. +- `equalFold(s1, s2 string) bool`: Returns true if `s1` is equal to `s2` under Unicode case-folding, which is a general form of case-insensitivity. +- `count(s, substr string) int`: Returns the amount of times that `substr` appears in `s`. +- `split(s, sep string) []string`: Returns a slice containing all substrings separated by `sep`. +- `join(ss []string, sep string) string`: Returns a string with all substrings in `ss` joined by `sep`. + +## What does the name mean? + +Salix is the latin name for willow trees. I wanted to use a name related to plants since the syntax was highly inspired by Leaf, and I really liked the name Salix. + +## Acknowledgements + +- [Pigeon](https://github.com/mna/pigeon): Salix uses a [PEG](https://en.wikipedia.org/wiki/Parsing_expression_grammar) parser generated by pigeon. Salix would've been a lot more difficult to write without it. +- [Leaf](https://github.com/vapor/leaf): Leaf was the first templaing language I ever used, and it inspired a lot of the syntax I've implemented in Salix because I found it really fun to use. + diff --git a/examples/readme/main.go b/examples/readme/main.go new file mode 100644 index 0000000..480f382 --- /dev/null +++ b/examples/readme/main.go @@ -0,0 +1,71 @@ +package main + +import ( + _ "embed" + "log" + "os" + "time" + + "go.elara.ws/salix" +) + +//go:embed readme.salix.html +var tmpl string + +type User struct { + Name string + LoggedIn bool + IsAdmin bool + RegisteredTime time.Time +} + +var users = []User{ + { + Name: "Elara", + LoggedIn: true, + IsAdmin: true, + RegisteredTime: time.Date(2023, time.January, 10, 10, 10, 10, 0, time.UTC), + }, + { + Name: "Karl Marx", + LoggedIn: false, + IsAdmin: true, + RegisteredTime: time.Date(1818, time.May, 5, 10, 10, 10, 0, time.UTC), + }, + { + Name: "Jane Doe", + LoggedIn: true, + IsAdmin: false, + RegisteredTime: time.Date(2050, time.March, 6, 10, 10, 10, 0, time.UTC), + }, + { + Name: "John Doe ", + LoggedIn: false, + IsAdmin: false, + RegisteredTime: time.Date(1700, time.November, 20, 10, 10, 10, 0, time.UTC), + }, +} + +type Page struct { + Title string +} + +func main() { + vars := map[string]any{ + "users": users, + "page": Page{Title: "Users"}, + } + + t, err := salix.New(). + WithVarMap(vars). + WithEscapeHTML(true). + ParseString("readme.salix.html", tmpl) + if err != nil { + log.Fatalln(err) + } + + err = t.Execute(os.Stdout) + if err != nil { + log.Fatalln(err) + } +} diff --git a/examples/readme/readme.salix.html b/examples/readme/readme.salix.html new file mode 100644 index 0000000..f9b313b --- /dev/null +++ b/examples/readme/readme.salix.html @@ -0,0 +1,16 @@ + + + #(page.Title) + + + #for(i, user in users): +
+

#(toLower(user.Name))

+

User ID: #(i)

+ #if(user.LoggedIn):

This user is logged in

#!if + #if(user.IsAdmin):

This user is an admin!

#!if +

Registered: #(user.RegisteredTime.Format("01-02-2006"))

+
+ #!for + + \ No newline at end of file diff --git a/examples/replybot/main.go b/examples/replybot/main.go new file mode 100644 index 0000000..7fd668c --- /dev/null +++ b/examples/replybot/main.go @@ -0,0 +1,36 @@ +package main + +import ( + _ "embed" + "log" + "os" + + "go.elara.ws/salix" +) + +//go:embed replybot.salix.txt +var tmpl string + +var matches = [][]string{ + {"https://i.imgur.com/aaaaaaa.jpg", "aaaaaaa.jpg"}, + {"https://imgur.com/a/bbbbbbb.jpg", "a/bbbbbbb.jpg"}, +} + +func main() { + vars := map[string]any{ + "type": "post", + "matches": matches, + } + + t, err := salix.New(). + WithVarMap(vars). + ParseString("replybot.salix.txt", tmpl) + if err != nil { + log.Fatalln(err) + } + + err = t.Execute(os.Stdout) + if err != nil { + log.Fatalln(err) + } +} diff --git a/examples/replybot/replybot.salix.txt b/examples/replybot/replybot.salix.txt new file mode 100644 index 0000000..b1e5c86 --- /dev/null +++ b/examples/replybot/replybot.salix.txt @@ -0,0 +1,8 @@ +#if(len(matches) > 1):Imgur links were#else:An Imgur link was#!if detected in your #(type). Here are links to the same #if(len(matches) > 1):locations#else:location#!if on alternative frontends that protect your privacy. +#for(i, match in matches): +#if(len(matches) > 1):Link #(i+1):#!if +- [imgur.artemislena.eu](https://imgur.artemislena.eu/#(match[1])) +- [rimgo.projectsegfau.lt](https://rimgo.projectsegfau.lt/#(match[1])) +- [imgin.voidnet.tech](https://imgin.voidnet.tech/#(match[1])) + +#!for \ No newline at end of file diff --git a/expr.go b/expr.go new file mode 100644 index 0000000..4bce95c --- /dev/null +++ b/expr.go @@ -0,0 +1,166 @@ +package salix + +import ( + "reflect" + "strings" + + "go.elara.ws/salix/internal/ast" +) + +func (t *Template) evalExpr(expr ast.Expr, local map[string]any) (any, error) { + val, err := t.getValue(expr.Segment, local) + if err != nil { + return nil, err + } + a := reflect.ValueOf(val) + + for _, exprB := range expr.Rest { + val, err := t.getValue(exprB.Segment, local) + if err != nil { + return nil, err + } + b := reflect.ValueOf(val) + a = reflect.ValueOf(t.performOp(a, b, exprB.Logical)) + } + + return a.Interface(), nil +} + +func (t *Template) evalExprSegment(expr ast.ExprSegment, local map[string]any) (any, error) { + val, err := t.getValue(expr.Value, local) + if err != nil { + return nil, err + } + a := reflect.ValueOf(val) + + for _, exprB := range expr.Rest { + val, err := t.getValue(exprB.Value, local) + if err != nil { + return nil, err + } + b := reflect.ValueOf(val) + a = reflect.ValueOf(t.performOp(a, b, exprB.Operator)) + } + + return a.Interface(), nil +} + +func (t *Template) performOp(a, b reflect.Value, op ast.Op) any { + if op.Op() == "in" { + switch b.Kind() { + case reflect.Slice, reflect.Array: + if a.CanConvert(b.Type().Elem()) { + a = a.Convert(b.Type().Elem()) + } else { + panic("todo: invalid in operation") + } + case reflect.String: + if a.Kind() != reflect.String { + panic("todo: invalid in operation") + } + } + } else if b.CanConvert(a.Type()) { + b = b.Convert(a.Type()) + } else { + panic("todo: invalid operation") + } + + switch op.Op() { + case "==": + return a.Equal(b) + case "&&": + if a.Kind() != reflect.Bool || b.Kind() != reflect.Bool { + panic("todo: invalid logical") + } + return a.Bool() && b.Bool() + case "||": + if a.Kind() != reflect.Bool || b.Kind() != reflect.Bool { + panic("todo: invalid logical") + } + return a.Bool() || b.Bool() + case ">=": + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() >= b.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() >= b.Uint() + case reflect.Float64, reflect.Float32: + return a.Float() >= b.Float() + } + case "<=": + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() <= b.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() <= b.Uint() + case reflect.Float64, reflect.Float32: + return a.Float() <= b.Float() + } + case ">": + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() > b.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() > b.Uint() + case reflect.Float64, reflect.Float32: + return a.Float() > b.Float() + } + case "<": + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() < b.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Float64, reflect.Float32: + return a.Float() < b.Float() + } + case "+": + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() + b.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() + b.Uint() + case reflect.Float64, reflect.Float32: + return a.Float() + b.Float() + } + case "-": + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() - b.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() - b.Uint() + case reflect.Float64, reflect.Float32: + return a.Float() - b.Float() + } + case "*": + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() * b.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() * b.Uint() + case reflect.Float64, reflect.Float32: + return a.Float() * b.Float() + } + case "/": + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() / b.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() / b.Uint() + case reflect.Float64, reflect.Float32: + return a.Float() / b.Float() + } + case "in": + if a.Kind() == reflect.String && b.Kind() == reflect.String { + return strings.Contains(b.String(), a.String()) + } else { + for i := 0; i < b.Len(); i++ { + if a.Equal(b.Index(i)) { + return true + } + } + return false + } + } + return false +} diff --git a/for_tag.go b/for_tag.go new file mode 100644 index 0000000..cbd980c --- /dev/null +++ b/for_tag.go @@ -0,0 +1,110 @@ +package salix + +import ( + "errors" + "reflect" + + "go.elara.ws/salix/internal/ast" +) + +var ErrForTagInvalidArgs = errors.New("invalid arguments in for tag") + +// forTag represents a #if tag within a Salix template +type forTag struct{} + +func (ft forTag) Run(tc *TagContext, block, args []ast.Node) error { + if len(args) == 0 || len(args) > 2 { + return ErrForTagInvalidArgs + } + + var expr ast.ExprSegment + if len(args) == 1 { + expr2, ok := args[0].(ast.ExprSegment) + if !ok { + return ErrForTagInvalidArgs + } + expr = expr2 + } else if len(args) == 2 { + expr2, ok := args[1].(ast.ExprSegment) + if !ok { + return ErrForTagInvalidArgs + } + expr = expr2 + } + + var vars []string + var in reflect.Value + + if len(args) == 2 { + varName, ok := unwrap(args[0]).(ast.Ident) + if !ok { + return ErrForTagInvalidArgs + } + vars = append(vars, varName.Value) + + } + + varName, ok := unwrap(expr.Value).(ast.Ident) + if !ok { + return ErrForTagInvalidArgs + } + vars = append(vars, varName.Value) + + if len(expr.Rest) != 1 { + return ErrForTagInvalidArgs + } + rest := expr.Rest[0] + + if rest.Operator.Value != "in" { + return ErrForTagInvalidArgs + } + + val, err := tc.GetValue(rest, nil) + if err != nil { + return err + } + in = reflect.ValueOf(val) + + switch in.Kind() { + case reflect.Slice, reflect.Array: + local := map[string]any{} + for i := 0; i < in.Len(); i++ { + if len(vars) == 1 { + local[vars[0]] = in.Index(i).Interface() + } else if len(vars) == 2 { + local[vars[0]] = i + local[vars[1]] = in.Index(i).Interface() + } + + err = tc.Execute(block, local) + if err != nil { + return err + } + } + case reflect.Map: + local := map[string]any{} + iter := in.MapRange() + for iter.Next() { + if len(vars) == 1 { + local[vars[0]] = iter.Value().Interface() + } else if len(vars) == 2 { + local[vars[0]] = iter.Key().Interface() + local[vars[1]] = iter.Value().Interface() + } + + err = tc.Execute(block, local) + if err != nil { + return err + } + } + } + + return nil +} + +func unwrap(n ast.Node) ast.Node { + if v, ok := n.(ast.Value); ok { + return v.Node + } + return n +} diff --git a/funcs.go b/funcs.go new file mode 100644 index 0000000..9fea2a3 --- /dev/null +++ b/funcs.go @@ -0,0 +1,31 @@ +package salix + +import ( + "reflect" + "strings" +) + +var defaultFuncs = map[string]any{ + "len": tmplLen, + "toUpper": strings.ToUpper, + "toLower": strings.ToLower, + "hasPrefix": strings.HasPrefix, + "trimPrefix": strings.TrimPrefix, + "hasSuffix": strings.HasSuffix, + "trimSuffix": strings.TrimSuffix, + "trimSpace": strings.TrimSpace, + "equalFold": strings.EqualFold, + "count": strings.Count, + "split": strings.Split, + "join": strings.Join, +} + +func tmplLen(v any) int { + val := reflect.ValueOf(v) + switch val.Kind() { + case reflect.Array, reflect.Slice, reflect.String, reflect.Map: + return val.Len() + default: + return -1 + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..67f4bd2 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module go.elara.ws/salix + +go 1.21.2 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e69de29 diff --git a/if_tag.go b/if_tag.go new file mode 100644 index 0000000..b73cdee --- /dev/null +++ b/if_tag.go @@ -0,0 +1,118 @@ +package salix + +import ( + "errors" + "go.elara.ws/salix/internal/ast" +) + +var ( + ErrIfExpectsOneArg = errors.New("if tag expects one argument") + ErrIfExpectsBool = errors.New("if tag expects a bool value") + ErrIfTwoElse = errors.New("if tags can only have one else tag inside") +) + +// ifTag represents a #if tag within a Salix template +type ifTag struct{} + +func (it ifTag) Run(tc *TagContext, block, args []ast.Node) error { + if len(args) != 1 { + return ErrIfExpectsOneArg + } + + inner, err := it.findInner(block) + if err != nil { + return err + } + + val, err := tc.GetValue(args[0], nil) + if err != nil { + return err + } + + cond, ok := val.(bool) + if !ok { + return ErrIfExpectsBool + } + + if cond { + return tc.Execute(block[:inner.endRoot], nil) + } else { + if len(inner.elifTags) > 0 { + for i, elifTag := range inner.elifTags { + val, err := tc.GetValue(elifTag.value, nil) + if err != nil { + return err + } + + cond, ok := val.(bool) + if !ok { + return ErrIfExpectsBool + } + + nextIndex := len(block) + if i < len(inner.elifTags)-1 { + nextIndex = inner.elifTags[i+1].index + } else if inner.elseIndex != 0 { + nextIndex = inner.elseIndex + } + + if cond { + return tc.Execute(block[elifTag.index+1:nextIndex], nil) + } + } + } + + if inner.elseIndex != 0 { + return tc.Execute(block[inner.elseIndex+1:], nil) + } + } + + return nil +} + +type innerTags struct { + endRoot int + elifTags []elif + elseIndex int +} + +type elif struct { + index int + value ast.Node +} + +// findInner finds the inner elif and else tags in a block +// passed to the if tag. +func (it ifTag) findInner(block []ast.Node) (innerTags, error) { + var out innerTags + for i, node := range block { + if tag, ok := node.(ast.Tag); ok { + switch tag.Name.Value { + case "elif": + if out.endRoot == 0 { + out.endRoot = i + } + if len(tag.Params) > 1 { + return innerTags{}, ErrIfExpectsOneArg + } + out.elifTags = append(out.elifTags, elif{ + index: i, + value: tag.Params[0], + }) + case "else": + if out.elseIndex != 0 { + return innerTags{}, ErrIfTwoElse + } + if out.endRoot == 0 { + out.endRoot = i + } + out.elseIndex = i + break + } + } + } + if out.endRoot == 0 { + out.endRoot = len(block) + } + return out, nil +} diff --git a/internal/ast/ast.go b/internal/ast/ast.go new file mode 100644 index 0000000..72a2681 --- /dev/null +++ b/internal/ast/ast.go @@ -0,0 +1,201 @@ +package ast + +import "fmt" + +func PosError(n Node, filename, format string, v ...any) error { + return fmt.Errorf(filename+":"+n.Pos().String()+": "+format, v...) +} + +type Node interface { + Pos() Position +} + +type Position struct { + Line int + Col int +} + +func (p Position) String() string { + return fmt.Sprintf("%d:%d", p.Line, p.Col) +} + +type Tag struct { + Name Ident + Params []Node + HasBody bool + Position Position +} + +func (t Tag) Pos() Position { + return t.Position +} + +type ExprTag struct { + Value Node + Position Position +} + +func (et ExprTag) Pos() Position { + return et.Position +} + +type EndTag struct { + Name Ident + Position Position +} + +func (et EndTag) Pos() Position { + return et.Position +} + +type Text struct { + Data []byte + Position Position +} + +func (t Text) Pos() Position { + return t.Position +} + +type Value struct { + Node + Not bool +} + +type Expr struct { + Segment Node + Logical Logical + Rest []Expr + Position Position +} + +func (e Expr) Pos() Position { + return e.Position +} + +type ExprSegment struct { + Value Node + Operator Operator + Rest []ExprSegment + Position Position +} + +func (es ExprSegment) Pos() Position { + return es.Position +} + +type FuncCall struct { + Name Ident + Params []Node + Position Position +} + +func (fc FuncCall) Pos() Position { + return fc.Position +} + +type MethodCall struct { + Value Node + Name Ident + Params []Node + Position Position +} + +func (mc MethodCall) Pos() Position { + return mc.Position +} + +type FieldAccess struct { + Value Node + Name Ident + Position Position +} + +func (fa FieldAccess) Pos() Position { + return fa.Position +} + +type Index struct { + Value Node + Index Node + Position Position +} + +func (i Index) Pos() Position { + return i.Position +} + +type Ident struct { + Value string + Position Position +} + +func (id Ident) Pos() Position { + return id.Position +} + +type String struct { + Value string + Position Position +} + +func (s String) Pos() Position { + return s.Position +} + +type Float struct { + Value float64 + Position Position +} + +func (f Float) Pos() Position { + return f.Position +} + +type Integer struct { + Value int64 + Position Position +} + +func (i Integer) Pos() Position { + return i.Position +} + +type Bool struct { + Value bool + Position Position +} + +func (b Bool) Pos() Position { + return b.Position +} + +type Op interface { + Op() string +} + +type Operator struct { + Value string + Position Position +} + +func (op Operator) Pos() Position { + return op.Position +} + +func (op Operator) Op() string { + return op.Value +} + +type Logical struct { + Value string + Position Position +} + +func (l Logical) Pos() Position { + return l.Position +} + +func (l Logical) Op() string { + return l.Value +} diff --git a/internal/parser/gen.go b/internal/parser/gen.go new file mode 100644 index 0000000..59adee0 --- /dev/null +++ b/internal/parser/gen.go @@ -0,0 +1,3 @@ +package parser + +//go:generate pigeon --support-left-recursion -o parser.go salix.peg diff --git a/internal/parser/parser.go b/internal/parser/parser.go new file mode 100644 index 0000000..3db0f6f --- /dev/null +++ b/internal/parser/parser.go @@ -0,0 +1,2713 @@ +// Code generated by pigeon; DO NOT EDIT. + +package parser + +import ( + "bytes" + "errors" + "fmt" + "io" + "math" + "os" + "sort" + "strconv" + "strings" + "sync" + "unicode" + "unicode/utf8" + + "go.elara.ws/salix/internal/ast" +) + +func toAnySlice(v any) []any { + if v == nil { + return nil + } + return v.([]any) +} + +func toNodeSlice(v any) []ast.Node { + if v == nil { + return nil + } + return v.([]ast.Node) +} + +func getPos(c *current) ast.Position { + return ast.Position{ + Line: c.pos.line, + Col: c.pos.col, + } +} + +var g = &grammar{ + rules: []*rule{ + { + name: "Root", + pos: position{line: 33, col: 1, offset: 416}, + expr: &actionExpr{ + pos: position{line: 33, col: 8, offset: 423}, + run: (*parser).callonRoot1, + expr: &labeledExpr{ + pos: position{line: 33, col: 8, offset: 423}, + label: "items", + expr: &zeroOrMoreExpr{ + pos: position{line: 33, col: 14, offset: 429}, + expr: &choiceExpr{ + pos: position{line: 33, col: 15, offset: 430}, + alternatives: []any{ + &ruleRefExpr{ + pos: position{line: 33, col: 15, offset: 430}, + name: "Tag", + }, + &ruleRefExpr{ + pos: position{line: 33, col: 21, offset: 436}, + name: "ExprTag", + }, + &ruleRefExpr{ + pos: position{line: 33, col: 31, offset: 446}, + name: "EndTag", + }, + &ruleRefExpr{ + pos: position{line: 33, col: 40, offset: 455}, + name: "Text", + }, + }, + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "Tag", + pos: position{line: 42, col: 1, offset: 641}, + expr: &actionExpr{ + pos: position{line: 42, col: 7, offset: 647}, + run: (*parser).callonTag1, + expr: &seqExpr{ + pos: position{line: 42, col: 7, offset: 647}, + exprs: []any{ + &litMatcher{ + pos: position{line: 42, col: 7, offset: 647}, + val: "#", + ignoreCase: false, + want: "\"#\"", + }, + &labeledExpr{ + pos: position{line: 42, col: 11, offset: 651}, + label: "name", + expr: &ruleRefExpr{ + pos: position{line: 42, col: 16, offset: 656}, + name: "Ident", + }, + }, + &labeledExpr{ + pos: position{line: 42, col: 22, offset: 662}, + label: "params", + expr: &zeroOrOneExpr{ + pos: position{line: 42, col: 29, offset: 669}, + expr: &ruleRefExpr{ + pos: position{line: 42, col: 29, offset: 669}, + name: "ParamList", + }, + }, + }, + &labeledExpr{ + pos: position{line: 42, col: 40, offset: 680}, + label: "body", + expr: &zeroOrOneExpr{ + pos: position{line: 42, col: 45, offset: 685}, + expr: &litMatcher{ + pos: position{line: 42, col: 45, offset: 685}, + val: ":", + ignoreCase: false, + want: "\":\"", + }, + }, + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "EndTag", + pos: position{line: 51, col: 1, offset: 861}, + expr: &actionExpr{ + pos: position{line: 51, col: 10, offset: 870}, + run: (*parser).callonEndTag1, + expr: &seqExpr{ + pos: position{line: 51, col: 10, offset: 870}, + exprs: []any{ + &litMatcher{ + pos: position{line: 51, col: 10, offset: 870}, + val: "#!", + ignoreCase: false, + want: "\"#!\"", + }, + &labeledExpr{ + pos: position{line: 51, col: 15, offset: 875}, + label: "name", + expr: &ruleRefExpr{ + pos: position{line: 51, col: 20, offset: 880}, + name: "Ident", + }, + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "ExprTag", + pos: position{line: 58, col: 1, offset: 990}, + expr: &actionExpr{ + pos: position{line: 58, col: 11, offset: 1000}, + run: (*parser).callonExprTag1, + expr: &seqExpr{ + pos: position{line: 58, col: 11, offset: 1000}, + exprs: []any{ + &litMatcher{ + pos: position{line: 58, col: 11, offset: 1000}, + val: "#(", + ignoreCase: false, + want: "\"#(\"", + }, + &labeledExpr{ + pos: position{line: 58, col: 16, offset: 1005}, + label: "expr", + expr: &ruleRefExpr{ + pos: position{line: 58, col: 21, offset: 1010}, + name: "Expr", + }, + }, + &litMatcher{ + pos: position{line: 58, col: 26, offset: 1015}, + val: ")", + ignoreCase: false, + want: "\")\"", + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "Expr", + pos: position{line: 65, col: 1, offset: 1123}, + expr: &actionExpr{ + pos: position{line: 65, col: 8, offset: 1130}, + run: (*parser).callonExpr1, + expr: &seqExpr{ + pos: position{line: 65, col: 8, offset: 1130}, + exprs: []any{ + &labeledExpr{ + pos: position{line: 65, col: 8, offset: 1130}, + label: "first", + expr: &ruleRefExpr{ + pos: position{line: 65, col: 14, offset: 1136}, + name: "ExprSegment", + }, + }, + &labeledExpr{ + pos: position{line: 65, col: 26, offset: 1148}, + label: "rest", + expr: &zeroOrMoreExpr{ + pos: position{line: 65, col: 31, offset: 1153}, + expr: &seqExpr{ + pos: position{line: 65, col: 32, offset: 1154}, + exprs: []any{ + &ruleRefExpr{ + pos: position{line: 65, col: 32, offset: 1154}, + name: "_", + }, + &ruleRefExpr{ + pos: position{line: 65, col: 34, offset: 1156}, + name: "Logical", + }, + &ruleRefExpr{ + pos: position{line: 65, col: 42, offset: 1164}, + name: "_", + }, + &ruleRefExpr{ + pos: position{line: 65, col: 44, offset: 1166}, + name: "ExprSegment", + }, + }, + }, + }, + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "ExprSegment", + pos: position{line: 84, col: 1, offset: 1680}, + expr: &actionExpr{ + pos: position{line: 84, col: 15, offset: 1694}, + run: (*parser).callonExprSegment1, + expr: &seqExpr{ + pos: position{line: 84, col: 15, offset: 1694}, + exprs: []any{ + &labeledExpr{ + pos: position{line: 84, col: 15, offset: 1694}, + label: "first", + expr: &ruleRefExpr{ + pos: position{line: 84, col: 21, offset: 1700}, + name: "Value", + }, + }, + &labeledExpr{ + pos: position{line: 84, col: 27, offset: 1706}, + label: "rest", + expr: &zeroOrMoreExpr{ + pos: position{line: 84, col: 32, offset: 1711}, + expr: &seqExpr{ + pos: position{line: 84, col: 33, offset: 1712}, + exprs: []any{ + &ruleRefExpr{ + pos: position{line: 84, col: 33, offset: 1712}, + name: "_", + }, + &ruleRefExpr{ + pos: position{line: 84, col: 35, offset: 1714}, + name: "Operator", + }, + &ruleRefExpr{ + pos: position{line: 84, col: 44, offset: 1723}, + name: "_", + }, + &ruleRefExpr{ + pos: position{line: 84, col: 46, offset: 1725}, + name: "Value", + }, + }, + }, + }, + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "ParamList", + pos: position{line: 103, col: 1, offset: 2246}, + expr: &actionExpr{ + pos: position{line: 103, col: 13, offset: 2258}, + run: (*parser).callonParamList1, + expr: &seqExpr{ + pos: position{line: 103, col: 13, offset: 2258}, + exprs: []any{ + &litMatcher{ + pos: position{line: 103, col: 13, offset: 2258}, + val: "(", + ignoreCase: false, + want: "\"(\"", + }, + &labeledExpr{ + pos: position{line: 103, col: 17, offset: 2262}, + label: "params", + expr: &zeroOrOneExpr{ + pos: position{line: 103, col: 24, offset: 2269}, + expr: &seqExpr{ + pos: position{line: 103, col: 25, offset: 2270}, + exprs: []any{ + &ruleRefExpr{ + pos: position{line: 103, col: 25, offset: 2270}, + name: "Expr", + }, + &zeroOrMoreExpr{ + pos: position{line: 103, col: 30, offset: 2275}, + expr: &seqExpr{ + pos: position{line: 103, col: 32, offset: 2277}, + exprs: []any{ + &litMatcher{ + pos: position{line: 103, col: 32, offset: 2277}, + val: ",", + ignoreCase: false, + want: "\",\"", + }, + &ruleRefExpr{ + pos: position{line: 103, col: 36, offset: 2281}, + name: "_", + }, + &ruleRefExpr{ + pos: position{line: 103, col: 38, offset: 2283}, + name: "Expr", + }, + }, + }, + }, + }, + }, + }, + }, + &litMatcher{ + pos: position{line: 103, col: 49, offset: 2294}, + val: ")", + ignoreCase: false, + want: "\")\"", + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "Value", + pos: position{line: 117, col: 1, offset: 2656}, + expr: &actionExpr{ + pos: position{line: 117, col: 9, offset: 2664}, + run: (*parser).callonValue1, + expr: &seqExpr{ + pos: position{line: 117, col: 9, offset: 2664}, + exprs: []any{ + &labeledExpr{ + pos: position{line: 117, col: 9, offset: 2664}, + label: "not", + expr: &zeroOrOneExpr{ + pos: position{line: 117, col: 13, offset: 2668}, + expr: &litMatcher{ + pos: position{line: 117, col: 13, offset: 2668}, + val: "!", + ignoreCase: false, + want: "\"!\"", + }, + }, + }, + &labeledExpr{ + pos: position{line: 117, col: 18, offset: 2673}, + label: "node", + expr: &choiceExpr{ + pos: position{line: 117, col: 24, offset: 2679}, + alternatives: []any{ + &ruleRefExpr{ + pos: position{line: 117, col: 24, offset: 2679}, + name: "MethodCall", + }, + &ruleRefExpr{ + pos: position{line: 117, col: 37, offset: 2692}, + name: "FieldAccess", + }, + &ruleRefExpr{ + pos: position{line: 117, col: 51, offset: 2706}, + name: "Index", + }, + &ruleRefExpr{ + pos: position{line: 117, col: 59, offset: 2714}, + name: "String", + }, + &ruleRefExpr{ + pos: position{line: 117, col: 68, offset: 2723}, + name: "RawString", + }, + &ruleRefExpr{ + pos: position{line: 117, col: 80, offset: 2735}, + name: "Float", + }, + &ruleRefExpr{ + pos: position{line: 117, col: 88, offset: 2743}, + name: "Integer", + }, + &ruleRefExpr{ + pos: position{line: 117, col: 98, offset: 2753}, + name: "Bool", + }, + &ruleRefExpr{ + pos: position{line: 117, col: 105, offset: 2760}, + name: "FuncCall", + }, + &ruleRefExpr{ + pos: position{line: 117, col: 116, offset: 2771}, + name: "Ident", + }, + }, + }, + }, + }, + }, + }, + leader: true, + leftRecursive: true, + }, + { + name: "MethodCall", + pos: position{line: 124, col: 1, offset: 2873}, + expr: &actionExpr{ + pos: position{line: 124, col: 14, offset: 2886}, + run: (*parser).callonMethodCall1, + expr: &seqExpr{ + pos: position{line: 124, col: 14, offset: 2886}, + exprs: []any{ + &labeledExpr{ + pos: position{line: 124, col: 14, offset: 2886}, + label: "value", + expr: &ruleRefExpr{ + pos: position{line: 124, col: 20, offset: 2892}, + name: "Value", + }, + }, + &litMatcher{ + pos: position{line: 124, col: 26, offset: 2898}, + val: ".", + ignoreCase: false, + want: "\".\"", + }, + &labeledExpr{ + pos: position{line: 124, col: 30, offset: 2902}, + label: "name", + expr: &ruleRefExpr{ + pos: position{line: 124, col: 35, offset: 2907}, + name: "Ident", + }, + }, + &labeledExpr{ + pos: position{line: 124, col: 41, offset: 2913}, + label: "params", + expr: &ruleRefExpr{ + pos: position{line: 124, col: 48, offset: 2920}, + name: "ParamList", + }, + }, + }, + }, + }, + leader: false, + leftRecursive: true, + }, + { + name: "Index", + pos: position{line: 133, col: 1, offset: 3113}, + expr: &actionExpr{ + pos: position{line: 133, col: 9, offset: 3121}, + run: (*parser).callonIndex1, + expr: &seqExpr{ + pos: position{line: 133, col: 9, offset: 3121}, + exprs: []any{ + &labeledExpr{ + pos: position{line: 133, col: 9, offset: 3121}, + label: "value", + expr: &ruleRefExpr{ + pos: position{line: 133, col: 15, offset: 3127}, + name: "Value", + }, + }, + &litMatcher{ + pos: position{line: 133, col: 21, offset: 3133}, + val: "[", + ignoreCase: false, + want: "\"[\"", + }, + &labeledExpr{ + pos: position{line: 133, col: 25, offset: 3137}, + label: "index", + expr: &ruleRefExpr{ + pos: position{line: 133, col: 31, offset: 3143}, + name: "Value", + }, + }, + &litMatcher{ + pos: position{line: 133, col: 37, offset: 3149}, + val: "]", + ignoreCase: false, + want: "\"]\"", + }, + }, + }, + }, + leader: false, + leftRecursive: true, + }, + { + name: "FieldAccess", + pos: position{line: 141, col: 1, offset: 3292}, + expr: &actionExpr{ + pos: position{line: 141, col: 15, offset: 3306}, + run: (*parser).callonFieldAccess1, + expr: &seqExpr{ + pos: position{line: 141, col: 15, offset: 3306}, + exprs: []any{ + &labeledExpr{ + pos: position{line: 141, col: 15, offset: 3306}, + label: "value", + expr: &ruleRefExpr{ + pos: position{line: 141, col: 21, offset: 3312}, + name: "Value", + }, + }, + &litMatcher{ + pos: position{line: 141, col: 27, offset: 3318}, + val: ".", + ignoreCase: false, + want: "\".\"", + }, + &labeledExpr{ + pos: position{line: 141, col: 31, offset: 3322}, + label: "name", + expr: &ruleRefExpr{ + pos: position{line: 141, col: 36, offset: 3327}, + name: "Ident", + }, + }, + }, + }, + }, + leader: false, + leftRecursive: true, + }, + { + name: "Ident", + pos: position{line: 149, col: 1, offset: 3478}, + expr: &actionExpr{ + pos: position{line: 149, col: 9, offset: 3486}, + run: (*parser).callonIdent1, + expr: &seqExpr{ + pos: position{line: 149, col: 9, offset: 3486}, + exprs: []any{ + &charClassMatcher{ + pos: position{line: 149, col: 9, offset: 3486}, + val: "[a-z]i", + ranges: []rune{'a', 'z'}, + ignoreCase: true, + inverted: false, + }, + &zeroOrMoreExpr{ + pos: position{line: 149, col: 16, offset: 3493}, + expr: &charClassMatcher{ + pos: position{line: 149, col: 16, offset: 3493}, + val: "[a-z0-9_]i", + chars: []rune{'_'}, + ranges: []rune{'a', 'z', '0', '9'}, + ignoreCase: true, + inverted: false, + }, + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "FuncCall", + pos: position{line: 156, col: 1, offset: 3607}, + expr: &actionExpr{ + pos: position{line: 156, col: 12, offset: 3618}, + run: (*parser).callonFuncCall1, + expr: &seqExpr{ + pos: position{line: 156, col: 12, offset: 3618}, + exprs: []any{ + &labeledExpr{ + pos: position{line: 156, col: 12, offset: 3618}, + label: "name", + expr: &ruleRefExpr{ + pos: position{line: 156, col: 17, offset: 3623}, + name: "Ident", + }, + }, + &labeledExpr{ + pos: position{line: 156, col: 23, offset: 3629}, + label: "params", + expr: &ruleRefExpr{ + pos: position{line: 156, col: 30, offset: 3636}, + name: "ParamList", + }, + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "Integer", + pos: position{line: 164, col: 1, offset: 3791}, + expr: &actionExpr{ + pos: position{line: 164, col: 11, offset: 3801}, + run: (*parser).callonInteger1, + expr: &choiceExpr{ + pos: position{line: 164, col: 12, offset: 3802}, + alternatives: []any{ + &seqExpr{ + pos: position{line: 164, col: 12, offset: 3802}, + exprs: []any{ + &litMatcher{ + pos: position{line: 164, col: 12, offset: 3802}, + val: "0x", + ignoreCase: false, + want: "\"0x\"", + }, + &oneOrMoreExpr{ + pos: position{line: 164, col: 17, offset: 3807}, + expr: &charClassMatcher{ + pos: position{line: 164, col: 17, offset: 3807}, + val: "[0-9a-f]i", + ranges: []rune{'0', '9', 'a', 'f'}, + ignoreCase: true, + inverted: false, + }, + }, + }, + }, + &seqExpr{ + pos: position{line: 164, col: 30, offset: 3820}, + exprs: []any{ + &litMatcher{ + pos: position{line: 164, col: 30, offset: 3820}, + val: "0o", + ignoreCase: false, + want: "\"0o\"", + }, + &oneOrMoreExpr{ + pos: position{line: 164, col: 35, offset: 3825}, + expr: &charClassMatcher{ + pos: position{line: 164, col: 35, offset: 3825}, + val: "[0-7]", + ranges: []rune{'0', '7'}, + ignoreCase: false, + inverted: false, + }, + }, + }, + }, + &seqExpr{ + pos: position{line: 164, col: 44, offset: 3834}, + exprs: []any{ + &litMatcher{ + pos: position{line: 164, col: 44, offset: 3834}, + val: "0b", + ignoreCase: false, + want: "\"0b\"", + }, + &oneOrMoreExpr{ + pos: position{line: 164, col: 49, offset: 3839}, + expr: &charClassMatcher{ + pos: position{line: 164, col: 49, offset: 3839}, + val: "[01]", + chars: []rune{'0', '1'}, + ignoreCase: false, + inverted: false, + }, + }, + }, + }, + &oneOrMoreExpr{ + pos: position{line: 164, col: 57, offset: 3847}, + expr: &charClassMatcher{ + pos: position{line: 164, col: 57, offset: 3847}, + val: "[0-9]", + ranges: []rune{'0', '9'}, + ignoreCase: false, + inverted: false, + }, + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "Float", + pos: position{line: 172, col: 1, offset: 3999}, + expr: &actionExpr{ + pos: position{line: 172, col: 9, offset: 4007}, + run: (*parser).callonFloat1, + expr: &labeledExpr{ + pos: position{line: 172, col: 9, offset: 4007}, + label: "value", + expr: &seqExpr{ + pos: position{line: 172, col: 16, offset: 4014}, + exprs: []any{ + &oneOrMoreExpr{ + pos: position{line: 172, col: 16, offset: 4014}, + expr: &charClassMatcher{ + pos: position{line: 172, col: 16, offset: 4014}, + val: "[0-9]", + ranges: []rune{'0', '9'}, + ignoreCase: false, + inverted: false, + }, + }, + &litMatcher{ + pos: position{line: 172, col: 23, offset: 4021}, + val: ".", + ignoreCase: false, + want: "\".\"", + }, + &oneOrMoreExpr{ + pos: position{line: 172, col: 27, offset: 4025}, + expr: &charClassMatcher{ + pos: position{line: 172, col: 27, offset: 4025}, + val: "[0-9]", + ranges: []rune{'0', '9'}, + ignoreCase: false, + inverted: false, + }, + }, + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "String", + pos: position{line: 180, col: 1, offset: 4174}, + expr: &actionExpr{ + pos: position{line: 180, col: 10, offset: 4183}, + run: (*parser).callonString1, + expr: &seqExpr{ + pos: position{line: 180, col: 10, offset: 4183}, + exprs: []any{ + &litMatcher{ + pos: position{line: 180, col: 10, offset: 4183}, + val: "\"", + ignoreCase: false, + want: "\"\\\"\"", + }, + &labeledExpr{ + pos: position{line: 180, col: 14, offset: 4187}, + label: "value", + expr: &zeroOrMoreExpr{ + pos: position{line: 180, col: 20, offset: 4193}, + expr: &charClassMatcher{ + pos: position{line: 180, col: 20, offset: 4193}, + val: "[^\"]", + chars: []rune{'"'}, + ignoreCase: false, + inverted: true, + }, + }, + }, + &litMatcher{ + pos: position{line: 180, col: 26, offset: 4199}, + val: "\"", + ignoreCase: false, + want: "\"\\\"\"", + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "RawString", + pos: position{line: 188, col: 1, offset: 4338}, + expr: &actionExpr{ + pos: position{line: 188, col: 13, offset: 4350}, + run: (*parser).callonRawString1, + expr: &seqExpr{ + pos: position{line: 188, col: 13, offset: 4350}, + exprs: []any{ + &litMatcher{ + pos: position{line: 188, col: 13, offset: 4350}, + val: "`", + ignoreCase: false, + want: "\"`\"", + }, + &labeledExpr{ + pos: position{line: 188, col: 17, offset: 4354}, + label: "value", + expr: &zeroOrMoreExpr{ + pos: position{line: 188, col: 23, offset: 4360}, + expr: &charClassMatcher{ + pos: position{line: 188, col: 23, offset: 4360}, + val: "[^`]", + chars: []rune{'`'}, + ignoreCase: false, + inverted: true, + }, + }, + }, + &litMatcher{ + pos: position{line: 188, col: 29, offset: 4366}, + val: "`", + ignoreCase: false, + want: "\"`\"", + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "Bool", + pos: position{line: 196, col: 1, offset: 4505}, + expr: &actionExpr{ + pos: position{line: 196, col: 8, offset: 4512}, + run: (*parser).callonBool1, + expr: &choiceExpr{ + pos: position{line: 196, col: 9, offset: 4513}, + alternatives: []any{ + &litMatcher{ + pos: position{line: 196, col: 9, offset: 4513}, + val: "true", + ignoreCase: true, + want: "\"true\"i", + }, + &litMatcher{ + pos: position{line: 196, col: 19, offset: 4523}, + val: "false", + ignoreCase: true, + want: "\"false\"i", + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "Operator", + pos: position{line: 204, col: 1, offset: 4668}, + expr: &actionExpr{ + pos: position{line: 204, col: 12, offset: 4679}, + run: (*parser).callonOperator1, + expr: &choiceExpr{ + pos: position{line: 204, col: 13, offset: 4680}, + alternatives: []any{ + &litMatcher{ + pos: position{line: 204, col: 13, offset: 4680}, + val: "==", + ignoreCase: false, + want: "\"==\"", + }, + &litMatcher{ + pos: position{line: 204, col: 20, offset: 4687}, + val: "<=", + ignoreCase: false, + want: "\"<=\"", + }, + &litMatcher{ + pos: position{line: 204, col: 27, offset: 4694}, + val: ">=", + ignoreCase: false, + want: "\">=\"", + }, + &litMatcher{ + pos: position{line: 204, col: 34, offset: 4701}, + val: "in", + ignoreCase: true, + want: "\"in\"i", + }, + &litMatcher{ + pos: position{line: 204, col: 42, offset: 4709}, + val: "<", + ignoreCase: false, + want: "\"<\"", + }, + &litMatcher{ + pos: position{line: 204, col: 48, offset: 4715}, + val: ">", + ignoreCase: false, + want: "\">\"", + }, + &litMatcher{ + pos: position{line: 204, col: 54, offset: 4721}, + val: "+", + ignoreCase: false, + want: "\"+\"", + }, + &litMatcher{ + pos: position{line: 204, col: 60, offset: 4727}, + val: "-", + ignoreCase: false, + want: "\"-\"", + }, + &litMatcher{ + pos: position{line: 204, col: 66, offset: 4733}, + val: "/", + ignoreCase: false, + want: "\"/\"", + }, + &litMatcher{ + pos: position{line: 204, col: 72, offset: 4739}, + val: "*", + ignoreCase: false, + want: "\"*\"", + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "Logical", + pos: position{line: 211, col: 1, offset: 4848}, + expr: &actionExpr{ + pos: position{line: 211, col: 11, offset: 4858}, + run: (*parser).callonLogical1, + expr: &choiceExpr{ + pos: position{line: 211, col: 12, offset: 4859}, + alternatives: []any{ + &litMatcher{ + pos: position{line: 211, col: 12, offset: 4859}, + val: "&&", + ignoreCase: false, + want: "\"&&\"", + }, + &litMatcher{ + pos: position{line: 211, col: 19, offset: 4866}, + val: "||", + ignoreCase: false, + want: "\"||\"", + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "Text", + pos: position{line: 218, col: 1, offset: 4975}, + expr: &actionExpr{ + pos: position{line: 218, col: 8, offset: 4982}, + run: (*parser).callonText1, + expr: &seqExpr{ + pos: position{line: 218, col: 8, offset: 4982}, + exprs: []any{ + &anyMatcher{ + line: 218, col: 8, offset: 4982, + }, + &zeroOrMoreExpr{ + pos: position{line: 218, col: 10, offset: 4984}, + expr: &charClassMatcher{ + pos: position{line: 218, col: 10, offset: 4984}, + val: "[^#]", + chars: []rune{'#'}, + ignoreCase: false, + inverted: true, + }, + }, + }, + }, + }, + leader: false, + leftRecursive: false, + }, + { + name: "_", + displayName: "\"whitespace\"", + pos: position{line: 220, col: 1, offset: 5051}, + expr: &zeroOrMoreExpr{ + pos: position{line: 220, col: 18, offset: 5070}, + expr: &charClassMatcher{ + pos: position{line: 220, col: 18, offset: 5070}, + val: "[ \\t\\r\\n]", + chars: []rune{' ', '\t', '\r', '\n'}, + ignoreCase: false, + inverted: false, + }, + }, + leader: false, + leftRecursive: false, + }, + }, +} + +func (c *current) onRoot1(items any) (any, error) { + itemSlice := toAnySlice(items) + out := make([]ast.Node, len(itemSlice)) + for i, item := range itemSlice { + out[i] = item.(ast.Node) + } + return out, nil +} + +func (p *parser) callonRoot1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onRoot1(stack["items"]) +} + +func (c *current) onTag1(name, params, body any) (any, error) { + return ast.Tag{ + Name: name.(ast.Ident), + Params: toNodeSlice(params), + HasBody: body != nil, + Position: getPos(c), + }, nil +} + +func (p *parser) callonTag1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onTag1(stack["name"], stack["params"], stack["body"]) +} + +func (c *current) onEndTag1(name any) (any, error) { + return ast.EndTag{ + Name: name.(ast.Ident), + Position: getPos(c), + }, nil +} + +func (p *parser) callonEndTag1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onEndTag1(stack["name"]) +} + +func (c *current) onExprTag1(expr any) (any, error) { + return ast.ExprTag{ + Value: expr.(ast.Node), + Position: getPos(c), + }, nil +} + +func (p *parser) callonExprTag1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onExprTag1(stack["expr"]) +} + +func (c *current) onExpr1(first, rest any) (any, error) { + restSlice := toAnySlice(rest) + if len(restSlice) == 0 { + return first, nil + } + + out := ast.Expr{Segment: first.(ast.Node), Position: getPos(c)} + for _, restValue := range restSlice { + valueSlice := toAnySlice(restValue) + out.Rest = append(out.Rest, ast.Expr{ + Logical: valueSlice[1].(ast.Logical), + Segment: valueSlice[3].(ast.Node), + Position: valueSlice[3].(ast.Node).Pos(), + }) + } + + return out, nil +} + +func (p *parser) callonExpr1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onExpr1(stack["first"], stack["rest"]) +} + +func (c *current) onExprSegment1(first, rest any) (any, error) { + restSlice := toAnySlice(rest) + if len(restSlice) == 0 { + return first, nil + } + + out := ast.ExprSegment{Value: first.(ast.Node), Position: getPos(c)} + for _, restValue := range restSlice { + valueSlice := toAnySlice(restValue) + out.Rest = append(out.Rest, ast.ExprSegment{ + Operator: valueSlice[1].(ast.Operator), + Value: valueSlice[3].(ast.Node), + Position: valueSlice[3].(ast.Node).Pos(), + }) + } + + return out, nil +} + +func (p *parser) callonExprSegment1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onExprSegment1(stack["first"], stack["rest"]) +} + +func (c *current) onParamList1(params any) (any, error) { + paramSlice := toAnySlice(params) + if len(paramSlice) == 0 { + return []ast.Node{}, nil + } + out := []ast.Node{paramSlice[0].(ast.Node)} + restSlice := toAnySlice(paramSlice[1]) + for _, value := range restSlice { + valueSlice := toAnySlice(value) + out = append(out, valueSlice[2].(ast.Node)) + } + return out, nil +} + +func (p *parser) callonParamList1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onParamList1(stack["params"]) +} + +func (c *current) onValue1(not, node any) (any, error) { + return ast.Value{ + Node: node.(ast.Node), + Not: not != nil, + }, nil +} + +func (p *parser) callonValue1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onValue1(stack["not"], stack["node"]) +} + +func (c *current) onMethodCall1(value, name, params any) (any, error) { + return ast.MethodCall{ + Value: value.(ast.Node), + Name: name.(ast.Ident), + Params: toNodeSlice(params), + Position: getPos(c), + }, nil +} + +func (p *parser) callonMethodCall1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onMethodCall1(stack["value"], stack["name"], stack["params"]) +} + +func (c *current) onIndex1(value, index any) (any, error) { + return ast.Index{ + Value: value.(ast.Node), + Index: index.(ast.Node), + Position: getPos(c), + }, nil +} + +func (p *parser) callonIndex1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onIndex1(stack["value"], stack["index"]) +} + +func (c *current) onFieldAccess1(value, name any) (any, error) { + return ast.FieldAccess{ + Value: value.(ast.Node), + Name: name.(ast.Ident), + Position: getPos(c), + }, nil +} + +func (p *parser) callonFieldAccess1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onFieldAccess1(stack["value"], stack["name"]) +} + +func (c *current) onIdent1() (any, error) { + + return ast.Ident{ + Value: string(c.text), + Position: getPos(c), + }, nil +} + +func (p *parser) callonIdent1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onIdent1() +} + +func (c *current) onFuncCall1(name, params any) (any, error) { + return ast.FuncCall{ + Name: name.(ast.Ident), + Params: toNodeSlice(params), + Position: getPos(c), + }, nil +} + +func (p *parser) callonFuncCall1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onFuncCall1(stack["name"], stack["params"]) +} + +func (c *current) onInteger1() (any, error) { + i, err := strconv.ParseInt(string(c.text), 0, 64) + return ast.Integer{ + Value: i, + Position: getPos(c), + }, err +} + +func (p *parser) callonInteger1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onInteger1() +} + +func (c *current) onFloat1(value any) (any, error) { + f, err := strconv.ParseFloat(string(c.text), 64) + return ast.Float{ + Value: f, + Position: getPos(c), + }, err +} + +func (p *parser) callonFloat1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onFloat1(stack["value"]) +} + +func (c *current) onString1(value any) (any, error) { + s, err := strconv.Unquote(string(c.text)) + return ast.String{ + Value: s, + Position: getPos(c), + }, err +} + +func (p *parser) callonString1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onString1(stack["value"]) +} + +func (c *current) onRawString1(value any) (any, error) { + s, err := strconv.Unquote(string(c.text)) + return ast.String{ + Value: s, + Position: getPos(c), + }, err +} + +func (p *parser) callonRawString1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onRawString1(stack["value"]) +} + +func (c *current) onBool1() (any, error) { + b, err := strconv.ParseBool(string(c.text)) + return ast.Bool{ + Value: b, + Position: getPos(c), + }, err +} + +func (p *parser) callonBool1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onBool1() +} + +func (c *current) onOperator1() (any, error) { + return ast.Operator{ + Value: string(c.text), + Position: getPos(c), + }, nil +} + +func (p *parser) callonOperator1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onOperator1() +} + +func (c *current) onLogical1() (any, error) { + return ast.Logical{ + Value: string(c.text), + Position: getPos(c), + }, nil +} + +func (p *parser) callonLogical1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onLogical1() +} + +func (c *current) onText1() (any, error) { + return ast.Text{Data: c.text, Position: getPos(c)}, nil +} + +func (p *parser) callonText1() (any, error) { + stack := p.vstack[len(p.vstack)-1] + _ = stack + return p.cur.onText1() +} + +var ( + // errNoRule is returned when the grammar to parse has no rule. + errNoRule = errors.New("grammar has no rule") + + // errInvalidEntrypoint is returned when the specified entrypoint rule + // does not exit. + errInvalidEntrypoint = errors.New("invalid entrypoint") + + // errInvalidEncoding is returned when the source is not properly + // utf8-encoded. + errInvalidEncoding = errors.New("invalid encoding") + + // errMaxExprCnt is used to signal that the maximum number of + // expressions have been parsed. + errMaxExprCnt = errors.New("max number of expresssions parsed") +) + +// Option is a function that can set an option on the parser. It returns +// the previous setting as an Option. +type Option func(*parser) Option + +// MaxExpressions creates an Option to stop parsing after the provided +// number of expressions have been parsed, if the value is 0 then the parser will +// parse for as many steps as needed (possibly an infinite number). +// +// The default for maxExprCnt is 0. +func MaxExpressions(maxExprCnt uint64) Option { + return func(p *parser) Option { + oldMaxExprCnt := p.maxExprCnt + p.maxExprCnt = maxExprCnt + return MaxExpressions(oldMaxExprCnt) + } +} + +// Entrypoint creates an Option to set the rule name to use as entrypoint. +// The rule name must have been specified in the -alternate-entrypoints +// if generating the parser with the -optimize-grammar flag, otherwise +// it may have been optimized out. Passing an empty string sets the +// entrypoint to the first rule in the grammar. +// +// The default is to start parsing at the first rule in the grammar. +func Entrypoint(ruleName string) Option { + return func(p *parser) Option { + oldEntrypoint := p.entrypoint + p.entrypoint = ruleName + if ruleName == "" { + p.entrypoint = g.rules[0].name + } + return Entrypoint(oldEntrypoint) + } +} + +// Statistics adds a user provided Stats struct to the parser to allow +// the user to process the results after the parsing has finished. +// Also the key for the "no match" counter is set. +// +// Example usage: +// +// input := "input" +// stats := Stats{} +// _, err := Parse("input-file", []byte(input), Statistics(&stats, "no match")) +// if err != nil { +// log.Panicln(err) +// } +// b, err := json.MarshalIndent(stats.ChoiceAltCnt, "", " ") +// if err != nil { +// log.Panicln(err) +// } +// fmt.Println(string(b)) +func Statistics(stats *Stats, choiceNoMatch string) Option { + return func(p *parser) Option { + oldStats := p.Stats + p.Stats = stats + oldChoiceNoMatch := p.choiceNoMatch + p.choiceNoMatch = choiceNoMatch + if p.Stats.ChoiceAltCnt == nil { + p.Stats.ChoiceAltCnt = make(map[string]map[string]int) + } + return Statistics(oldStats, oldChoiceNoMatch) + } +} + +// Debug creates an Option to set the debug flag to b. When set to true, +// debugging information is printed to stdout while parsing. +// +// The default is false. +func Debug(b bool) Option { + return func(p *parser) Option { + old := p.debug + p.debug = b + return Debug(old) + } +} + +// Memoize creates an Option to set the memoize flag to b. When set to true, +// the parser will cache all results so each expression is evaluated only +// once. This guarantees linear parsing time even for pathological cases, +// at the expense of more memory and slower times for typical cases. +// +// The default is false. +func Memoize(b bool) Option { + return func(p *parser) Option { + old := p.memoize + p.memoize = b + return Memoize(old) + } +} + +// AllowInvalidUTF8 creates an Option to allow invalid UTF-8 bytes. +// Every invalid UTF-8 byte is treated as a utf8.RuneError (U+FFFD) +// by character class matchers and is matched by the any matcher. +// The returned matched value, c.text and c.offset are NOT affected. +// +// The default is false. +func AllowInvalidUTF8(b bool) Option { + return func(p *parser) Option { + old := p.allowInvalidUTF8 + p.allowInvalidUTF8 = b + return AllowInvalidUTF8(old) + } +} + +// Recover creates an Option to set the recover flag to b. When set to +// true, this causes the parser to recover from panics and convert it +// to an error. Setting it to false can be useful while debugging to +// access the full stack trace. +// +// The default is true. +func Recover(b bool) Option { + return func(p *parser) Option { + old := p.recover + p.recover = b + return Recover(old) + } +} + +// GlobalStore creates an Option to set a key to a certain value in +// the globalStore. +func GlobalStore(key string, value any) Option { + return func(p *parser) Option { + old := p.cur.globalStore[key] + p.cur.globalStore[key] = value + return GlobalStore(key, old) + } +} + +// InitState creates an Option to set a key to a certain value in +// the global "state" store. +func InitState(key string, value any) Option { + return func(p *parser) Option { + old := p.cur.state[key] + p.cur.state[key] = value + return InitState(key, old) + } +} + +// ParseFile parses the file identified by filename. +func ParseFile(filename string, opts ...Option) (i any, err error) { + f, err := os.Open(filename) + if err != nil { + return nil, err + } + defer func() { + if closeErr := f.Close(); closeErr != nil { + err = closeErr + } + }() + return ParseReader(filename, f, opts...) +} + +// ParseReader parses the data from r using filename as information in the +// error messages. +func ParseReader(filename string, r io.Reader, opts ...Option) (any, error) { + b, err := io.ReadAll(r) + if err != nil { + return nil, err + } + + return Parse(filename, b, opts...) +} + +// Parse parses the data from b using filename as information in the +// error messages. +func Parse(filename string, b []byte, opts ...Option) (any, error) { + return newParser(filename, b, opts...).parse(g) +} + +// position records a position in the text. +type position struct { + line, col, offset int +} + +func (p position) String() string { + return strconv.Itoa(p.line) + ":" + strconv.Itoa(p.col) + " [" + strconv.Itoa(p.offset) + "]" +} + +// savepoint stores all state required to go back to this point in the +// parser. +type savepoint struct { + position + rn rune + w int +} + +type current struct { + pos position // start position of the match + text []byte // raw text of the match + + // state is a store for arbitrary key,value pairs that the user wants to be + // tied to the backtracking of the parser. + // This is always rolled back if a parsing rule fails. + state storeDict + + // globalStore is a general store for the user to store arbitrary key-value + // pairs that they need to manage and that they do not want tied to the + // backtracking of the parser. This is only modified by the user and never + // rolled back by the parser. It is always up to the user to keep this in a + // consistent state. + globalStore storeDict +} + +type storeDict map[string]any + +// the AST types... + +type grammar struct { + pos position + rules []*rule +} + +type rule struct { + pos position + name string + displayName string + expr any + + leader bool + leftRecursive bool +} + +type choiceExpr struct { + pos position + alternatives []any +} + +type actionExpr struct { + pos position + expr any + run func(*parser) (any, error) +} + +type recoveryExpr struct { + pos position + expr any + recoverExpr any + failureLabel []string +} + +type seqExpr struct { + pos position + exprs []any +} + +type throwExpr struct { + pos position + label string +} + +type labeledExpr struct { + pos position + label string + expr any +} + +type expr struct { + pos position + expr any +} + +type ( + andExpr expr + notExpr expr + zeroOrOneExpr expr + zeroOrMoreExpr expr + oneOrMoreExpr expr +) + +type ruleRefExpr struct { + pos position + name string +} + +type stateCodeExpr struct { + pos position + run func(*parser) error +} + +type andCodeExpr struct { + pos position + run func(*parser) (bool, error) +} + +type notCodeExpr struct { + pos position + run func(*parser) (bool, error) +} + +type litMatcher struct { + pos position + val string + ignoreCase bool + want string +} + +type charClassMatcher struct { + pos position + val string + basicLatinChars [128]bool + chars []rune + ranges []rune + classes []*unicode.RangeTable + ignoreCase bool + inverted bool +} + +type anyMatcher position + +// errList cumulates the errors found by the parser. +type errList []error + +func (e *errList) add(err error) { + *e = append(*e, err) +} + +func (e errList) err() error { + if len(e) == 0 { + return nil + } + e.dedupe() + return e +} + +func (e *errList) dedupe() { + var cleaned []error + set := make(map[string]bool) + for _, err := range *e { + if msg := err.Error(); !set[msg] { + set[msg] = true + cleaned = append(cleaned, err) + } + } + *e = cleaned +} + +func (e errList) Error() string { + switch len(e) { + case 0: + return "" + case 1: + return e[0].Error() + default: + var buf bytes.Buffer + + for i, err := range e { + if i > 0 { + buf.WriteRune('\n') + } + buf.WriteString(err.Error()) + } + return buf.String() + } +} + +// parserError wraps an error with a prefix indicating the rule in which +// the error occurred. The original error is stored in the Inner field. +type parserError struct { + Inner error + pos position + prefix string + expected []string +} + +// Error returns the error message. +func (p *parserError) Error() string { + return p.prefix + ": " + p.Inner.Error() +} + +// newParser creates a parser with the specified input source and options. +func newParser(filename string, b []byte, opts ...Option) *parser { + stats := Stats{ + ChoiceAltCnt: make(map[string]map[string]int), + } + + p := &parser{ + filename: filename, + errs: new(errList), + data: b, + pt: savepoint{position: position{line: 1}}, + recover: true, + cur: current{ + state: make(storeDict), + globalStore: make(storeDict), + }, + maxFailPos: position{col: 1, line: 1}, + maxFailExpected: make([]string, 0, 20), + Stats: &stats, + // start rule is rule [0] unless an alternate entrypoint is specified + entrypoint: g.rules[0].name, + } + p.setOptions(opts) + + if p.maxExprCnt == 0 { + p.maxExprCnt = math.MaxUint64 + } + + return p +} + +// setOptions applies the options to the parser. +func (p *parser) setOptions(opts []Option) { + for _, opt := range opts { + opt(p) + } +} + +type resultTuple struct { + v any + b bool + end savepoint +} + +const choiceNoMatch = -1 + +// Stats stores some statistics, gathered during parsing +type Stats struct { + // ExprCnt counts the number of expressions processed during parsing + // This value is compared to the maximum number of expressions allowed + // (set by the MaxExpressions option). + ExprCnt uint64 + + // ChoiceAltCnt is used to count for each ordered choice expression, + // which alternative is used how may times. + // These numbers allow to optimize the order of the ordered choice expression + // to increase the performance of the parser + // + // The outer key of ChoiceAltCnt is composed of the name of the rule as well + // as the line and the column of the ordered choice. + // The inner key of ChoiceAltCnt is the number (one-based) of the matching alternative. + // For each alternative the number of matches are counted. If an ordered choice does not + // match, a special counter is incremented. The name of this counter is set with + // the parser option Statistics. + // For an alternative to be included in ChoiceAltCnt, it has to match at least once. + ChoiceAltCnt map[string]map[string]int +} + +type ruleWithExpsStack struct { + rule *rule + estack []any +} + +type parser struct { + filename string + pt savepoint + cur current + + data []byte + errs *errList + + depth int + recover bool + debug bool + + memoize bool + // memoization table for the packrat algorithm: + // map[offset in source] map[expression or rule] {value, match} + memo map[int]map[any]resultTuple + + // rules table, maps the rule identifier to the rule node + rules map[string]*rule + // variables stack, map of label to value + vstack []map[string]any + // rule stack, allows identification of the current rule in errors + rstack []*rule + + // parse fail + maxFailPos position + maxFailExpected []string + maxFailInvertExpected bool + + // max number of expressions to be parsed + maxExprCnt uint64 + // entrypoint for the parser + entrypoint string + + allowInvalidUTF8 bool + + *Stats + + choiceNoMatch string + // recovery expression stack, keeps track of the currently available recovery expression, these are traversed in reverse + recoveryStack []map[string]any +} + +// push a variable set on the vstack. +func (p *parser) pushV() { + if cap(p.vstack) == len(p.vstack) { + // create new empty slot in the stack + p.vstack = append(p.vstack, nil) + } else { + // slice to 1 more + p.vstack = p.vstack[:len(p.vstack)+1] + } + + // get the last args set + m := p.vstack[len(p.vstack)-1] + if m != nil && len(m) == 0 { + // empty map, all good + return + } + + m = make(map[string]any) + p.vstack[len(p.vstack)-1] = m +} + +// pop a variable set from the vstack. +func (p *parser) popV() { + // if the map is not empty, clear it + m := p.vstack[len(p.vstack)-1] + if len(m) > 0 { + // GC that map + p.vstack[len(p.vstack)-1] = nil + } + p.vstack = p.vstack[:len(p.vstack)-1] +} + +// push a recovery expression with its labels to the recoveryStack +func (p *parser) pushRecovery(labels []string, expr any) { + if cap(p.recoveryStack) == len(p.recoveryStack) { + // create new empty slot in the stack + p.recoveryStack = append(p.recoveryStack, nil) + } else { + // slice to 1 more + p.recoveryStack = p.recoveryStack[:len(p.recoveryStack)+1] + } + + m := make(map[string]any, len(labels)) + for _, fl := range labels { + m[fl] = expr + } + p.recoveryStack[len(p.recoveryStack)-1] = m +} + +// pop a recovery expression from the recoveryStack +func (p *parser) popRecovery() { + // GC that map + p.recoveryStack[len(p.recoveryStack)-1] = nil + + p.recoveryStack = p.recoveryStack[:len(p.recoveryStack)-1] +} + +func (p *parser) print(prefix, s string) string { + if !p.debug { + return s + } + + fmt.Printf("%s %d:%d:%d: %s [%#U]\n", + prefix, p.pt.line, p.pt.col, p.pt.offset, s, p.pt.rn) + return s +} + +func (p *parser) printIndent(mark string, s string) string { + return p.print(strings.Repeat(" ", p.depth)+mark, s) +} + +func (p *parser) in(s string) string { + res := p.printIndent(">", s) + p.depth++ + return res +} + +func (p *parser) out(s string) string { + p.depth-- + return p.printIndent("<", s) +} + +func (p *parser) addErr(err error) { + p.addErrAt(err, p.pt.position, []string{}) +} + +func (p *parser) addErrAt(err error, pos position, expected []string) { + var buf bytes.Buffer + if p.filename != "" { + buf.WriteString(p.filename) + } + if buf.Len() > 0 { + buf.WriteString(":") + } + buf.WriteString(fmt.Sprintf("%d:%d (%d)", pos.line, pos.col, pos.offset)) + if len(p.rstack) > 0 { + if buf.Len() > 0 { + buf.WriteString(": ") + } + rule := p.rstack[len(p.rstack)-1] + if rule.displayName != "" { + buf.WriteString("rule " + rule.displayName) + } else { + buf.WriteString("rule " + rule.name) + } + } + pe := &parserError{Inner: err, pos: pos, prefix: buf.String(), expected: expected} + p.errs.add(pe) +} + +func (p *parser) failAt(fail bool, pos position, want string) { + // process fail if parsing fails and not inverted or parsing succeeds and invert is set + if fail == p.maxFailInvertExpected { + if pos.offset < p.maxFailPos.offset { + return + } + + if pos.offset > p.maxFailPos.offset { + p.maxFailPos = pos + p.maxFailExpected = p.maxFailExpected[:0] + } + + if p.maxFailInvertExpected { + want = "!" + want + } + p.maxFailExpected = append(p.maxFailExpected, want) + } +} + +// read advances the parser to the next rune. +func (p *parser) read() { + p.pt.offset += p.pt.w + rn, n := utf8.DecodeRune(p.data[p.pt.offset:]) + p.pt.rn = rn + p.pt.w = n + p.pt.col++ + if rn == '\n' { + p.pt.line++ + p.pt.col = 0 + } + + if rn == utf8.RuneError && n == 1 { // see utf8.DecodeRune + if !p.allowInvalidUTF8 { + p.addErr(errInvalidEncoding) + } + } +} + +// restore parser position to the savepoint pt. +func (p *parser) restore(pt savepoint) { + if p.debug { + defer p.out(p.in("restore")) + } + if pt.offset == p.pt.offset { + return + } + p.pt = pt +} + +// Cloner is implemented by any value that has a Clone method, which returns a +// copy of the value. This is mainly used for types which are not passed by +// value (e.g map, slice, chan) or structs that contain such types. +// +// This is used in conjunction with the global state feature to create proper +// copies of the state to allow the parser to properly restore the state in +// the case of backtracking. +type Cloner interface { + Clone() any +} + +var statePool = &sync.Pool{ + New: func() any { return make(storeDict) }, +} + +func (sd storeDict) Discard() { + for k := range sd { + delete(sd, k) + } + statePool.Put(sd) +} + +// clone and return parser current state. +func (p *parser) cloneState() storeDict { + if p.debug { + defer p.out(p.in("cloneState")) + } + + state := statePool.Get().(storeDict) + for k, v := range p.cur.state { + if c, ok := v.(Cloner); ok { + state[k] = c.Clone() + } else { + state[k] = v + } + } + return state +} + +// restore parser current state to the state storeDict. +// every restoreState should applied only one time for every cloned state +func (p *parser) restoreState(state storeDict) { + if p.debug { + defer p.out(p.in("restoreState")) + } + p.cur.state.Discard() + p.cur.state = state +} + +// get the slice of bytes from the savepoint start to the current position. +func (p *parser) sliceFrom(start savepoint) []byte { + return p.data[start.position.offset:p.pt.position.offset] +} + +func (p *parser) getMemoized(node any) (resultTuple, bool) { + if len(p.memo) == 0 { + return resultTuple{}, false + } + m := p.memo[p.pt.offset] + if len(m) == 0 { + return resultTuple{}, false + } + res, ok := m[node] + return res, ok +} + +func (p *parser) setMemoized(pt savepoint, node any, tuple resultTuple) { + if p.memo == nil { + p.memo = make(map[int]map[any]resultTuple) + } + m := p.memo[pt.offset] + if m == nil { + m = make(map[any]resultTuple) + p.memo[pt.offset] = m + } + m[node] = tuple +} + +func (p *parser) buildRulesTable(g *grammar) { + p.rules = make(map[string]*rule, len(g.rules)) + for _, r := range g.rules { + p.rules[r.name] = r + } +} + +func (p *parser) parse(g *grammar) (val any, err error) { + if len(g.rules) == 0 { + p.addErr(errNoRule) + return nil, p.errs.err() + } + + // TODO : not super critical but this could be generated + p.buildRulesTable(g) + + if p.recover { + // panic can be used in action code to stop parsing immediately + // and return the panic as an error. + defer func() { + if e := recover(); e != nil { + if p.debug { + defer p.out(p.in("panic handler")) + } + val = nil + switch e := e.(type) { + case error: + p.addErr(e) + default: + p.addErr(fmt.Errorf("%v", e)) + } + err = p.errs.err() + } + }() + } + + startRule, ok := p.rules[p.entrypoint] + if !ok { + p.addErr(errInvalidEntrypoint) + return nil, p.errs.err() + } + + p.read() // advance to first rune + val, ok = p.parseRuleWrap(startRule) + if !ok { + if len(*p.errs) == 0 { + // If parsing fails, but no errors have been recorded, the expected values + // for the farthest parser position are returned as error. + maxFailExpectedMap := make(map[string]struct{}, len(p.maxFailExpected)) + for _, v := range p.maxFailExpected { + maxFailExpectedMap[v] = struct{}{} + } + expected := make([]string, 0, len(maxFailExpectedMap)) + eof := false + if _, ok := maxFailExpectedMap["!."]; ok { + delete(maxFailExpectedMap, "!.") + eof = true + } + for k := range maxFailExpectedMap { + expected = append(expected, k) + } + sort.Strings(expected) + if eof { + expected = append(expected, "EOF") + } + p.addErrAt(errors.New("no match found, expected: "+listJoin(expected, ", ", "or")), p.maxFailPos, expected) + } + + return nil, p.errs.err() + } + return val, p.errs.err() +} + +func listJoin(list []string, sep string, lastSep string) string { + switch len(list) { + case 0: + return "" + case 1: + return list[0] + default: + return strings.Join(list[:len(list)-1], sep) + " " + lastSep + " " + list[len(list)-1] + } +} + +func (p *parser) parseRuleRecursiveLeader(rule *rule) (any, bool) { + result, ok := p.getMemoized(rule) + if ok { + p.restore(result.end) + return result.v, result.b + } + + if p.debug { + defer p.out(p.in("recursive " + rule.name)) + } + + var ( + depth = 0 + startMark = p.pt + lastResult = resultTuple{nil, false, startMark} + lastErrors = *p.errs + ) + + for { + lastState := p.cloneState() + p.setMemoized(startMark, rule, lastResult) + val, ok := p.parseRule(rule) + endMark := p.pt + if p.debug { + p.printIndent("RECURSIVE", fmt.Sprintf( + "Rule %s depth %d: %t -> %s", + rule.name, depth, ok, string(p.sliceFrom(startMark)))) + } + if (!ok) || (endMark.offset <= lastResult.end.offset && depth != 0) { + p.restoreState(lastState) + *p.errs = lastErrors + break + } + lastResult = resultTuple{val, ok, endMark} + lastErrors = *p.errs + p.restore(startMark) + depth++ + } + + p.restore(lastResult.end) + p.setMemoized(startMark, rule, lastResult) + return lastResult.v, lastResult.b +} + +func (p *parser) parseRuleRecursiveNoLeader(rule *rule) (any, bool) { + return p.parseRule(rule) +} + +func (p *parser) parseRuleMemoize(rule *rule) (any, bool) { + res, ok := p.getMemoized(rule) + if ok { + p.restore(res.end) + return res.v, res.b + } + + startMark := p.pt + val, ok := p.parseRule(rule) + p.setMemoized(startMark, rule, resultTuple{val, ok, p.pt}) + + return val, ok +} + +func (p *parser) parseRuleWrap(rule *rule) (any, bool) { + if p.debug { + defer p.out(p.in("parseRule " + rule.name)) + } + var ( + val any + ok bool + startMark = p.pt + ) + + if p.memoize || rule.leftRecursive { + if rule.leader { + val, ok = p.parseRuleRecursiveLeader(rule) + } else if p.memoize && !rule.leftRecursive { + val, ok = p.parseRuleMemoize(rule) + } else { + val, ok = p.parseRuleRecursiveNoLeader(rule) + } + } else { + val, ok = p.parseRule(rule) + } + + if ok && p.debug { + p.printIndent("MATCH", string(p.sliceFrom(startMark))) + } + return val, ok +} + +func (p *parser) parseRule(rule *rule) (any, bool) { + p.rstack = append(p.rstack, rule) + p.pushV() + val, ok := p.parseExprWrap(rule.expr) + p.popV() + p.rstack = p.rstack[:len(p.rstack)-1] + return val, ok +} + +func (p *parser) parseExprWrap(expr any) (any, bool) { + var pt savepoint + + isLeftRecusion := p.rstack[len(p.rstack)-1].leftRecursive + if p.memoize && !isLeftRecusion { + res, ok := p.getMemoized(expr) + if ok { + p.restore(res.end) + return res.v, res.b + } + pt = p.pt + } + + val, ok := p.parseExpr(expr) + + if p.memoize && !isLeftRecusion { + p.setMemoized(pt, expr, resultTuple{val, ok, p.pt}) + } + return val, ok +} + +func (p *parser) parseExpr(expr any) (any, bool) { + p.ExprCnt++ + if p.ExprCnt > p.maxExprCnt { + panic(errMaxExprCnt) + } + + var val any + var ok bool + switch expr := expr.(type) { + case *actionExpr: + val, ok = p.parseActionExpr(expr) + case *andCodeExpr: + val, ok = p.parseAndCodeExpr(expr) + case *andExpr: + val, ok = p.parseAndExpr(expr) + case *anyMatcher: + val, ok = p.parseAnyMatcher(expr) + case *charClassMatcher: + val, ok = p.parseCharClassMatcher(expr) + case *choiceExpr: + val, ok = p.parseChoiceExpr(expr) + case *labeledExpr: + val, ok = p.parseLabeledExpr(expr) + case *litMatcher: + val, ok = p.parseLitMatcher(expr) + case *notCodeExpr: + val, ok = p.parseNotCodeExpr(expr) + case *notExpr: + val, ok = p.parseNotExpr(expr) + case *oneOrMoreExpr: + val, ok = p.parseOneOrMoreExpr(expr) + case *recoveryExpr: + val, ok = p.parseRecoveryExpr(expr) + case *ruleRefExpr: + val, ok = p.parseRuleRefExpr(expr) + case *seqExpr: + val, ok = p.parseSeqExpr(expr) + case *stateCodeExpr: + val, ok = p.parseStateCodeExpr(expr) + case *throwExpr: + val, ok = p.parseThrowExpr(expr) + case *zeroOrMoreExpr: + val, ok = p.parseZeroOrMoreExpr(expr) + case *zeroOrOneExpr: + val, ok = p.parseZeroOrOneExpr(expr) + default: + panic(fmt.Sprintf("unknown expression type %T", expr)) + } + return val, ok +} + +func (p *parser) parseActionExpr(act *actionExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseActionExpr")) + } + + start := p.pt + val, ok := p.parseExprWrap(act.expr) + if ok { + p.cur.pos = start.position + p.cur.text = p.sliceFrom(start) + state := p.cloneState() + actVal, err := act.run(p) + if err != nil { + p.addErrAt(err, start.position, []string{}) + } + p.restoreState(state) + + val = actVal + } + if ok && p.debug { + p.printIndent("MATCH", string(p.sliceFrom(start))) + } + return val, ok +} + +func (p *parser) parseAndCodeExpr(and *andCodeExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseAndCodeExpr")) + } + + state := p.cloneState() + + ok, err := and.run(p) + if err != nil { + p.addErr(err) + } + p.restoreState(state) + + return nil, ok +} + +func (p *parser) parseAndExpr(and *andExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseAndExpr")) + } + + pt := p.pt + state := p.cloneState() + p.pushV() + _, ok := p.parseExprWrap(and.expr) + p.popV() + p.restoreState(state) + p.restore(pt) + + return nil, ok +} + +func (p *parser) parseAnyMatcher(any *anyMatcher) (any, bool) { + if p.debug { + defer p.out(p.in("parseAnyMatcher")) + } + + if p.pt.rn == utf8.RuneError && p.pt.w == 0 { + // EOF - see utf8.DecodeRune + p.failAt(false, p.pt.position, ".") + return nil, false + } + start := p.pt + p.read() + p.failAt(true, start.position, ".") + return p.sliceFrom(start), true +} + +func (p *parser) parseCharClassMatcher(chr *charClassMatcher) (any, bool) { + if p.debug { + defer p.out(p.in("parseCharClassMatcher")) + } + + cur := p.pt.rn + start := p.pt + + // can't match EOF + if cur == utf8.RuneError && p.pt.w == 0 { // see utf8.DecodeRune + p.failAt(false, start.position, chr.val) + return nil, false + } + + if chr.ignoreCase { + cur = unicode.ToLower(cur) + } + + // try to match in the list of available chars + for _, rn := range chr.chars { + if rn == cur { + if chr.inverted { + p.failAt(false, start.position, chr.val) + return nil, false + } + p.read() + p.failAt(true, start.position, chr.val) + return p.sliceFrom(start), true + } + } + + // try to match in the list of ranges + for i := 0; i < len(chr.ranges); i += 2 { + if cur >= chr.ranges[i] && cur <= chr.ranges[i+1] { + if chr.inverted { + p.failAt(false, start.position, chr.val) + return nil, false + } + p.read() + p.failAt(true, start.position, chr.val) + return p.sliceFrom(start), true + } + } + + // try to match in the list of Unicode classes + for _, cl := range chr.classes { + if unicode.Is(cl, cur) { + if chr.inverted { + p.failAt(false, start.position, chr.val) + return nil, false + } + p.read() + p.failAt(true, start.position, chr.val) + return p.sliceFrom(start), true + } + } + + if chr.inverted { + p.read() + p.failAt(true, start.position, chr.val) + return p.sliceFrom(start), true + } + p.failAt(false, start.position, chr.val) + return nil, false +} + +func (p *parser) incChoiceAltCnt(ch *choiceExpr, altI int) { + choiceIdent := fmt.Sprintf("%s %d:%d", p.rstack[len(p.rstack)-1].name, ch.pos.line, ch.pos.col) + m := p.ChoiceAltCnt[choiceIdent] + if m == nil { + m = make(map[string]int) + p.ChoiceAltCnt[choiceIdent] = m + } + // We increment altI by 1, so the keys do not start at 0 + alt := strconv.Itoa(altI + 1) + if altI == choiceNoMatch { + alt = p.choiceNoMatch + } + m[alt]++ +} + +func (p *parser) parseChoiceExpr(ch *choiceExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseChoiceExpr")) + } + + for altI, alt := range ch.alternatives { + // dummy assignment to prevent compile error if optimized + _ = altI + + state := p.cloneState() + + p.pushV() + val, ok := p.parseExprWrap(alt) + p.popV() + if ok { + p.incChoiceAltCnt(ch, altI) + return val, ok + } + p.restoreState(state) + } + p.incChoiceAltCnt(ch, choiceNoMatch) + return nil, false +} + +func (p *parser) parseLabeledExpr(lab *labeledExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseLabeledExpr")) + } + + p.pushV() + val, ok := p.parseExprWrap(lab.expr) + p.popV() + if ok && lab.label != "" { + m := p.vstack[len(p.vstack)-1] + m[lab.label] = val + } + return val, ok +} + +func (p *parser) parseLitMatcher(lit *litMatcher) (any, bool) { + if p.debug { + defer p.out(p.in("parseLitMatcher")) + } + + start := p.pt + for _, want := range lit.val { + cur := p.pt.rn + if lit.ignoreCase { + cur = unicode.ToLower(cur) + } + if cur != want { + p.failAt(false, start.position, lit.want) + p.restore(start) + return nil, false + } + p.read() + } + p.failAt(true, start.position, lit.want) + return p.sliceFrom(start), true +} + +func (p *parser) parseNotCodeExpr(not *notCodeExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseNotCodeExpr")) + } + + state := p.cloneState() + + ok, err := not.run(p) + if err != nil { + p.addErr(err) + } + p.restoreState(state) + + return nil, !ok +} + +func (p *parser) parseNotExpr(not *notExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseNotExpr")) + } + + pt := p.pt + state := p.cloneState() + p.pushV() + p.maxFailInvertExpected = !p.maxFailInvertExpected + _, ok := p.parseExprWrap(not.expr) + p.maxFailInvertExpected = !p.maxFailInvertExpected + p.popV() + p.restoreState(state) + p.restore(pt) + + return nil, !ok +} + +func (p *parser) parseOneOrMoreExpr(expr *oneOrMoreExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseOneOrMoreExpr")) + } + + var vals []any + + for { + p.pushV() + val, ok := p.parseExprWrap(expr.expr) + p.popV() + if !ok { + if len(vals) == 0 { + // did not match once, no match + return nil, false + } + return vals, true + } + vals = append(vals, val) + } +} + +func (p *parser) parseRecoveryExpr(recover *recoveryExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseRecoveryExpr (" + strings.Join(recover.failureLabel, ",") + ")")) + } + + p.pushRecovery(recover.failureLabel, recover.recoverExpr) + val, ok := p.parseExprWrap(recover.expr) + p.popRecovery() + + return val, ok +} + +func (p *parser) parseRuleRefExpr(ref *ruleRefExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseRuleRefExpr " + ref.name)) + } + + if ref.name == "" { + panic(fmt.Sprintf("%s: invalid rule: missing name", ref.pos)) + } + + rule := p.rules[ref.name] + if rule == nil { + p.addErr(fmt.Errorf("undefined rule: %s", ref.name)) + return nil, false + } + return p.parseRuleWrap(rule) +} + +func (p *parser) parseSeqExpr(seq *seqExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseSeqExpr")) + } + + vals := make([]any, 0, len(seq.exprs)) + + pt := p.pt + state := p.cloneState() + for _, expr := range seq.exprs { + val, ok := p.parseExprWrap(expr) + if !ok { + p.restoreState(state) + p.restore(pt) + return nil, false + } + vals = append(vals, val) + } + return vals, true +} + +func (p *parser) parseStateCodeExpr(state *stateCodeExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseStateCodeExpr")) + } + + err := state.run(p) + if err != nil { + p.addErr(err) + } + return nil, true +} + +func (p *parser) parseThrowExpr(expr *throwExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseThrowExpr")) + } + + for i := len(p.recoveryStack) - 1; i >= 0; i-- { + if recoverExpr, ok := p.recoveryStack[i][expr.label]; ok { + if val, ok := p.parseExprWrap(recoverExpr); ok { + return val, ok + } + } + } + + return nil, false +} + +func (p *parser) parseZeroOrMoreExpr(expr *zeroOrMoreExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseZeroOrMoreExpr")) + } + + var vals []any + + for { + p.pushV() + val, ok := p.parseExprWrap(expr.expr) + p.popV() + if !ok { + return vals, true + } + vals = append(vals, val) + } +} + +func (p *parser) parseZeroOrOneExpr(expr *zeroOrOneExpr) (any, bool) { + if p.debug { + defer p.out(p.in("parseZeroOrOneExpr")) + } + + p.pushV() + val, _ := p.parseExprWrap(expr.expr) + p.popV() + // whether it matched or not, consider it a match + return val, true +} diff --git a/internal/parser/salix.peg b/internal/parser/salix.peg new file mode 100644 index 0000000..b5ed40c --- /dev/null +++ b/internal/parser/salix.peg @@ -0,0 +1,220 @@ +{ +package parser + +import ( + "strconv" + + "go.elara.ws/salix/internal/ast" +) + +func toAnySlice(v any) []any { + if v == nil { + return nil + } + return v.([]any) +} + +func toNodeSlice(v any) []ast.Node { + if v == nil { + return nil + } + return v.([]ast.Node) +} + +func getPos(c *current) ast.Position { + return ast.Position{ + Line: c.pos.line, + Col: c.pos.col, + } +} + +} + +Root = items:(Tag / ExprTag / EndTag / Text)* { + itemSlice := toAnySlice(items) + out := make([]ast.Node, len(itemSlice)) + for i, item := range itemSlice{ + out[i] = item.(ast.Node) + } + return out, nil +} + +Tag = '#' name:Ident params:ParamList? body:':'? { + return ast.Tag{ + Name: name.(ast.Ident), + Params: toNodeSlice(params), + HasBody: body != nil, + Position: getPos(c), + }, nil +} + +EndTag = "#!" name:Ident { + return ast.EndTag{ + Name: name.(ast.Ident), + Position: getPos(c), + }, nil +} + +ExprTag = "#(" expr:Expr ')' { + return ast.ExprTag{ + Value: expr.(ast.Node), + Position: getPos(c), + }, nil +} + +Expr = first:ExprSegment rest:(_ Logical _ ExprSegment)* { + restSlice := toAnySlice(rest) + if len(restSlice) == 0 { + return first, nil + } + + out := ast.Expr{Segment: first.(ast.Node), Position: getPos(c)} + for _, restValue := range restSlice { + valueSlice := toAnySlice(restValue) + out.Rest = append(out.Rest, ast.Expr{ + Logical: valueSlice[1].(ast.Logical), + Segment: valueSlice[3].(ast.Node), + Position: valueSlice[3].(ast.Node).Pos(), + }) + } + + return out, nil +} + +ExprSegment = first:Value rest:(_ Operator _ Value)* { + restSlice := toAnySlice(rest) + if len(restSlice) == 0 { + return first, nil + } + + out := ast.ExprSegment{Value: first.(ast.Node), Position: getPos(c)} + for _, restValue := range restSlice { + valueSlice := toAnySlice(restValue) + out.Rest = append(out.Rest, ast.ExprSegment{ + Operator: valueSlice[1].(ast.Operator), + Value: valueSlice[3].(ast.Node), + Position: valueSlice[3].(ast.Node).Pos(), + }) + } + + return out, nil +} + +ParamList = '(' params:(Expr ( ',' _ Expr )* )? ')' { + paramSlice := toAnySlice(params) + if len(paramSlice) == 0 { + return []ast.Node{}, nil + } + out := []ast.Node{paramSlice[0].(ast.Node)} + restSlice := toAnySlice(paramSlice[1]) + for _, value := range restSlice { + valueSlice := toAnySlice(value) + out = append(out, valueSlice[2].(ast.Node)) + } + return out, nil +} + +Value = not:"!"? node:(MethodCall / FieldAccess / Index / String / RawString / Float / Integer / Bool / FuncCall / Ident) { + return ast.Value{ + Node: node.(ast.Node), + Not: not != nil, + }, nil +} + +MethodCall = value:Value '.' name:Ident params:ParamList { + return ast.MethodCall{ + Value: value.(ast.Node), + Name: name.(ast.Ident), + Params: toNodeSlice(params), + Position: getPos(c), + }, nil +} + +Index = value:Value '[' index:Value ']' { + return ast.Index{ + Value: value.(ast.Node), + Index: index.(ast.Node), + Position: getPos(c), + }, nil +} + +FieldAccess = value:Value '.' name:Ident { + return ast.FieldAccess{ + Value: value.(ast.Node), + Name: name.(ast.Ident), + Position: getPos(c), + }, nil +} + +Ident = [a-z]i [a-z0-9_]i* { + return ast.Ident{ + Value: string(c.text), + Position: getPos(c), + }, nil +} + +FuncCall = name:Ident params:ParamList { + return ast.FuncCall{ + Name: name.(ast.Ident), + Params: toNodeSlice(params), + Position: getPos(c), + }, nil +} + +Integer = ("0x" [0-9a-f]i+ / "0o" [0-7]+ / "0b" [01]+ / [0-9]+) { + i, err := strconv.ParseInt(string(c.text), 0, 64) + return ast.Integer{ + Value: i, + Position: getPos(c), + }, err +} + +Float = value:([0-9]+ '.' [0-9]+) { + f, err := strconv.ParseFloat(string(c.text), 64) + return ast.Float{ + Value: f, + Position: getPos(c), + }, err +} + +String = '"' value:[^"]* '"' { + s, err := strconv.Unquote(string(c.text)) + return ast.String{ + Value: s, + Position: getPos(c), + }, err +} + +RawString = '`' value:[^`]* '`' { + s, err := strconv.Unquote(string(c.text)) + return ast.String{ + Value: s, + Position: getPos(c), + }, err +} + +Bool = ("true"i / "false"i) { + b, err := strconv.ParseBool(string(c.text)) + return ast.Bool{ + Value: b, + Position: getPos(c), + }, err +} + +Operator = ("==" / "<=" / ">=" / "in"i / '<' / '>' / '+' / '-' / '/' / '*') { + return ast.Operator{ + Value: string(c.text), + Position: getPos(c), + }, nil +} + +Logical = ("&&" / "||") { + return ast.Logical{ + Value: string(c.text), + Position: getPos(c), + }, nil +} + +Text = . [^#]* { return ast.Text{Data: c.text, Position: getPos(c)}, nil } + +_ "whitespace" ← [ \t\r\n]* \ No newline at end of file diff --git a/parse.go b/parse.go new file mode 100644 index 0000000..245d550 --- /dev/null +++ b/parse.go @@ -0,0 +1,52 @@ +package salix + +import ( + "bytes" + "io" + "os" + "strings" + + "go.elara.ws/salix/internal/ast" + "go.elara.ws/salix/internal/parser" +) + +// Parse parses a salix template from r. If the reader has a Name method +// that returns a string, that will be used as the filename. +func (t *Template) Parse(r io.Reader) (*Template, error) { + fname := "" + if r, ok := r.(interface{ Name() string }); ok { + fname = r.Name() + } + return t.ParseWithFilename(fname, r) +} + +// ParseWithFilename parses a salix template from r, using the given filename. +func (t *Template) ParseWithFilename(filename string, r io.Reader) (*Template, error) { + astVal, err := parser.ParseReader(filename, r) + if err != nil { + return nil, err + } + t.file = filename + t.ast = astVal.([]ast.Node) + return t, nil +} + +// ParseFile parses the file at path as a salix template +func (t *Template) ParseFile(path string) (*Template, error) { + fl, err := os.Open(path) + if err != nil { + return nil, err + } + defer fl.Close() + return t.Parse(fl) +} + +// ParseString parses a string using the given filename. +func (t *Template) ParseString(filename, tmpl string) (*Template, error) { + return t.ParseWithFilename(filename, strings.NewReader(tmpl)) +} + +// ParseString parses bytes using the given filename. +func (t *Template) ParseBytes(filename string, tmpl []byte) (*Template, error) { + return t.ParseWithFilename(filename, bytes.NewReader(tmpl)) +} diff --git a/salix.go b/salix.go new file mode 100644 index 0000000..73bc294 --- /dev/null +++ b/salix.go @@ -0,0 +1,445 @@ +package salix + +import ( + "bytes" + "errors" + "fmt" + "html" + "io" + "reflect" + + "go.elara.ws/salix/internal/ast" +) + +var ( + ErrNoSuchFunc = errors.New("no such function") + ErrNoSuchVar = errors.New("no such variable") + ErrNoSuchMethod = errors.New("no such method") + ErrNoSuchField = errors.New("no such field") + ErrNoSuchTag = errors.New("no such tag") + ErrNotOperatorNonBool = errors.New("not operator cannot be used on a non-bool value") + ErrParamNumMismatch = errors.New("incorrect parameter amount") + ErrIncorrectParamType = errors.New("incorrect parameter type for function") + ErrEndTagWithoutStart = errors.New("end tag without a start tag") + ErrIncorrectIndexType = errors.New("incorrect index type") + ErrIndexOutOfRange = errors.New("index out of range") + ErrMapIndexNotFound = errors.New("map index not found") + ErrMapInvalidIndexType = errors.New("invalid map index type") + ErrFuncTooManyReturns = errors.New("template functions can only have two return values") + ErrFuncNoReturns = errors.New("template functions must return at least one value") + ErrFuncSecondReturnType = errors.New("the second return value of a template function must be an error") +) + +type HTML string + +// Template represents a Salix template +type Template struct { + file string + ast []ast.Node + + escapeHTML bool + + tags map[string]Tag + funcs map[string]reflect.Value + vars map[string]reflect.Value +} + +// New creates a new base template with the default +// tags and functions added. +func New() *Template { + t := &Template{ + funcs: map[string]reflect.Value{}, + vars: map[string]reflect.Value{}, + tags: map[string]Tag{}, + } + return t.WithTagMap(defaultTags).WithFuncMap(defaultFuncs) +} + +// WithFuncMap adds all the functions in m to the template's +// global function map. If a function with the given name already +// exists, it will be overwritten. +func (t *Template) WithFuncMap(m map[string]any) *Template { + if m != nil { + for name, fn := range m { + t.funcs[name] = reflect.ValueOf(fn) + } + } + return t +} + +// WithVarMap adds all the variables in m to the template's +// global variable map. If a variable with the given name already +// exists, it will be overwritten. +func (t *Template) WithVarMap(m map[string]any) *Template { + if m != nil { + for name, val := range m { + t.vars[name] = reflect.ValueOf(val) + } + } + return t +} + +// WithTagMap adds all the tags in m to the template's +// global tag map. If a tag with the given name already +// exists, it will be overwritten. +func (t *Template) WithTagMap(m map[string]Tag) *Template { + if m != nil { + for name, tag := range m { + t.tags[name] = tag + } + } + return t +} + +// WithEscapeHTML enables or disables HTML escaping. +// The HTML escaping functionality is NOT context-aware. +// Using the HTML type allows you to get around the escaping. +func (t *Template) WithEscapeHTML(b bool) *Template { + t.escapeHTML = true + return t +} + +// Execute executes a parsed template and writes +// the result to w. +func (t *Template) Execute(w io.Writer) error { + return t.execute(w, t.ast, nil) +} + +func (t *Template) execute(w io.Writer, nodes []ast.Node, local map[string]any) error { + for i := 0; i < len(nodes); i++ { + switch node := nodes[i].(type) { + case ast.Text: + _, err := w.Write(node.Data) + if err != nil { + return t.posError(node, "%w", err) + } + case ast.Tag: + newOffset, err := t.execTag(node, w, nodes, i, local) + if err != nil { + return err + } + i = newOffset + case ast.EndTag: + // We should never see an end tag here because it + // should be taken care of by execTag, so if we do, + // return an error because execTag was never called, + // which means there was no start tag. + return ErrEndTagWithoutStart + case ast.ExprTag: + v, err := t.getValue(node.Value, local) + if err != nil { + return err + } + _, err = io.WriteString(w, t.toString(v)) + if err != nil { + return err + } + } + } + return nil +} + +func (t *Template) toString(v any) string { + if h, ok := v.(HTML); ok { + return string(h) + } else if t.escapeHTML { + return html.EscapeString(fmt.Sprint(v)) + } + return fmt.Sprint(v) +} + +// getBlock gets all the nodes in the input, up to the end tag with the given name +func (t *Template) getBlock(nodes []ast.Node, offset, startLine int, name string) []ast.Node { + var out []ast.Node + tagAmount := 1 + for i := offset; i < len(nodes); i++ { + switch node := nodes[i].(type) { + case ast.Tag: + // If we encounter another tag with the same name, + // increment tagAmount so that we know that the next + // end tag isn't the end of this tag. + if node.Name.Value == name { + tagAmount++ + } + out = append(out, node) + case ast.EndTag: + if node.Name.Value == name { + tagAmount-- + } + // Once tagAmount is zero (all the tags of the same name) + // have been closed with an end tag, we can handle our newlines + // and return the nodes we've accumulated. + if tagAmount == 0 { + // If the end tag is on the same line as the start tag, + // we don't need to remove any newlines. + if node.Position.Line != startLine { + t.handleNewlines(nodes, i) + } + return out + } else { + out = append(out, node) + } + default: + out = append(out, node) + } + } + return out +} + +// getValue gets a Go value from an AST node +func (t *Template) getValue(node ast.Node, local map[string]any) (any, error) { + switch node := node.(type) { + case ast.Value: + return t.unwrapASTValue(node, local) + case ast.Ident: + return t.getVar(node, local) + case ast.String: + return node.Value, nil + case ast.Float: + return node.Value, nil + case ast.Integer: + return node.Value, nil + case ast.Bool: + return node.Value, nil + case ast.Expr: + return t.evalExpr(node, local) + case ast.ExprSegment: + return t.evalExprSegment(node, local) + case ast.FuncCall: + return t.execFuncCall(node, local) + case ast.Index: + return t.getIndex(node, local) + case ast.FieldAccess: + return t.getField(node, local) + case ast.MethodCall: + return t.execMethodCall(node, local) + default: + return nil, nil + } +} + +// unwrapASTValue unwraps an ast.Value node into its underlying value +func (t *Template) unwrapASTValue(node ast.Value, local map[string]any) (any, error) { + v, err := t.getValue(node.Node, local) + if err != nil { + return nil, err + } + + if node.Not { + rval := reflect.ValueOf(v) + if rval.Kind() != reflect.Bool { + return nil, ErrNotOperatorNonBool + } + return !rval.Bool(), nil + } + + return v, err +} + +// getVar tries to get a variable from the local map. If it's not found, +// it'll try the global variable map. If it doesn't exist in either map, +// it will return an error. +func (t *Template) getVar(id ast.Ident, local map[string]any) (any, error) { + if local != nil { + v, ok := local[id.Value] + if ok { + return v, nil + } + } + + v, ok := t.vars[id.Value] + if !ok { + return nil, t.posError(id, "%w: %s", ErrNoSuchVar, id.Value) + } + + return v.Interface(), nil +} + +// handleNewlines removes newlines above and below the given index +// in the nodes slice. +func (t *Template) handleNewlines(nodes []ast.Node, i int) { + if i != 0 { + if node, ok := nodes[i-1].(ast.Text); ok { + ni := bytes.LastIndexByte(node.Data, '\n') + if ni != -1 { + node.Data = node.Data[:ni] + } + nodes[i-1] = node + } + } + + lastIndex := len(nodes) - 1 + if i != lastIndex { + if node, ok := nodes[i+1].(ast.Text); ok { + ni := bytes.IndexByte(node.Data, '\n') + if ni != -1 { + node.Data = node.Data[ni:] + } + nodes[i+1] = node + } + } +} + +// execTag executes a tag +func (t *Template) execTag(node ast.Tag, w io.Writer, nodes []ast.Node, i int, local map[string]any) (newOffset int, err error) { + tag, ok := t.tags[node.Name.Value] + if !ok { + return 0, t.posError(node, "%w: %s", ErrNoSuchTag, node.Name.Value) + } + + t.handleNewlines(nodes, i) + + var block []ast.Node + if node.HasBody { + block = t.getBlock(nodes, i+1, node.Position.Line, node.Name.Value) + i += len(block) + 1 + } + + tc := &TagContext{w, t, local} + + err = tag.Run(tc, block, node.Params) + if err != nil { + return 0, err + } + + return i, nil +} + +// execFuncCall executes a function call +func (t *Template) execFuncCall(fc ast.FuncCall, local map[string]any) (any, error) { + fn, ok := t.funcs[fc.Name.Value] + if !ok { + return nil, t.posError(fc, "%w: %s", ErrNoSuchFunc, fc.Name.Value) + } + return t.execFunc(fn, fc, fc.Params, local) +} + +// getIndex tries to evaluate an ast.Index node by indexing the underlying value. +func (t *Template) getIndex(i ast.Index, local map[string]any) (any, error) { + val, err := t.getValue(i.Value, local) + if err != nil { + return nil, err + } + + index, err := t.getValue(i.Index, local) + if err != nil { + return nil, err + } + + rval := reflect.ValueOf(val) + rindex := reflect.ValueOf(index) + switch rval.Kind() { + case reflect.Slice, reflect.Array: + intType := reflect.TypeOf(0) + if rindex.CanConvert(intType) { + rindex = rindex.Convert(intType) + } else { + return nil, ErrIncorrectIndexType + } + + intIndex := rindex.Interface().(int) + if intIndex < rval.Len() { + return rval.Index(intIndex).Interface(), nil + } else { + return nil, t.posError(i, "%w: %d", ErrIndexOutOfRange, intIndex) + } + case reflect.Map: + if rindex.CanConvert(rval.Type().Key()) { + rindex = rindex.Convert(rval.Type().Key()) + } else { + return nil, t.posError(i, "%w: %T (expected %s)", ErrMapInvalidIndexType, index, rval.Type().Key()) + } + if out := rval.MapIndex(rindex); out.IsValid() { + return out.Interface(), nil + } else { + return nil, t.posError(i, "%w: %q", ErrMapIndexNotFound, index) + } + } + return nil, nil +} + +// getField tries to get a struct field from the underlying value +func (t *Template) getField(fa ast.FieldAccess, local map[string]any) (any, error) { + val, err := t.getValue(fa.Value, local) + if err != nil { + return nil, err + } + rval := reflect.ValueOf(val) + field := rval.FieldByName(fa.Name.Value) + if !field.IsValid() { + return nil, t.posError(fa, "%w: %s", ErrNoSuchField, fa.Name.Value) + } + return field.Interface(), nil +} + +// execMethodCall executes a method call on the underlying value +func (t *Template) execMethodCall(mc ast.MethodCall, local map[string]any) (any, error) { + val, err := t.getValue(mc.Value, local) + if err != nil { + return nil, err + } + rval := reflect.ValueOf(val) + mtd := rval.MethodByName(mc.Name.Value) + if !mtd.IsValid() { + return nil, t.posError(mc, "%w: %s", ErrNoSuchMethod, mc.Name.Value) + } + return t.execFunc(mtd, mc, mc.Params, local) +} + +// execFunc executes a function call +func (t *Template) execFunc(fn reflect.Value, node ast.Node, args []ast.Node, local map[string]any) (any, error) { + fnType := fn.Type() + if fnType.NumIn() != len(args) { + return nil, t.posError(node, "%w: %d (expected %d)", ErrParamNumMismatch, len(args), fnType.NumIn()) + } + + if err := validateFunc(fnType); err != nil { + return nil, t.posError(node, "%w", err) + } + + params := make([]reflect.Value, fnType.NumIn()) + for i, arg := range args { + paramVal, err := t.getValue(arg, local) + if err != nil { + return nil, err + } + params[i] = reflect.ValueOf(paramVal) + if params[i].CanConvert(fnType.In(i)) { + params[i] = params[i].Convert(fnType.In(i)) + } else { + return nil, t.posError(node, "%w", ErrIncorrectParamType) + } + } + + ret := fn.Call(params) + if len(ret) == 1 { + retv := ret[0].Interface() + if err, ok := retv.(error); ok { + return nil, err + } + return ret[0].Interface(), nil + } else { + return ret[0].Interface(), ret[1].Interface().(error) + } +} + +func (t *Template) posError(n ast.Node, format string, v ...any) error { + return ast.PosError(n, t.file, format, v...) +} + +func validateFunc(t reflect.Type) error { + numOut := t.NumOut() + if numOut > 2 { + return ErrFuncTooManyReturns + } else if numOut == 0 { + return ErrFuncNoReturns + } + + if numOut == 2 { + if !t.Out(1).Implements(reflect.TypeOf(error(nil))) { + return ErrFuncSecondReturnType + } + } + + return nil +} diff --git a/tags.go b/tags.go new file mode 100644 index 0000000..21acc78 --- /dev/null +++ b/tags.go @@ -0,0 +1,45 @@ +package salix + +import ( + "io" + + "go.elara.ws/salix/internal/ast" +) + +type Tag interface { + Run(tc *TagContext, block, args []ast.Node) error +} + +var defaultTags = map[string]Tag{ + "if": ifTag{}, + "for": forTag{}, +} + +type TagContext struct { + w io.Writer + t *Template + local map[string]any +} + +func (tc *TagContext) Execute(nodes []ast.Node, local map[string]any) error { + return tc.t.execute(tc.w, nodes, mergeMap(tc.local, local)) +} + +func (tc *TagContext) GetValue(node ast.Node, local map[string]any) (any, error) { + return tc.t.getValue(node, mergeMap(tc.local, local)) +} + +func mergeMap(a, b map[string]any) map[string]any { + out := map[string]any{} + if a != nil { + for k, v := range a { + out[k] = v + } + } + if b != nil { + for k, v := range b { + out[k] = v + } + } + return out +}