rozbir (empty) → 0.1.0.0
raw patch · 37 files changed
+7792/−0 lines, 37 filesdep +QuickCheckdep +aesondep +base
Dependencies added: QuickCheck, aeson, base, bytestring, containers, deepseq, directory, filepath, hspec, mtl, rozbir, text, time
Files
- CHANGELOG.md +7/−0
- LICENSE.md +675/−0
- README.md +49/−0
- rozbir.cabal +106/−0
- src/Rozbir.hs +48/−0
- src/Rozbir/Changelog.hs +146/−0
- src/Rozbir/Edit.hs +219/−0
- src/Rozbir/Eval.hs +743/−0
- src/Rozbir/Eval/Builtin.hs +365/−0
- src/Rozbir/Eval/LuaPattern.hs +154/−0
- src/Rozbir/Eval/Shell.hs +578/−0
- src/Rozbir/Eval/Types.hs +342/−0
- src/Rozbir/IO.hs +112/−0
- src/Rozbir/Lint.hs +142/−0
- src/Rozbir/Lint/Core.hs +328/−0
- src/Rozbir/Lint/Rpmlint.hs +317/−0
- src/Rozbir/Lint/Terra.hs +98/−0
- src/Rozbir/Lint/Types.hs +160/−0
- src/Rozbir/MacroFile.hs +74/−0
- src/Rozbir/Query.hs +203/−0
- src/Rozbir/Spec.hs +636/−0
- src/Rozbir/Syntax.hs +493/−0
- src/Rozbir/Syntax/Expr.hs +382/−0
- src/Rozbir/Syntax/Parse.hs +438/−0
- src/Rozbir/Syntax/Render.hs +171/−0
- src/Rozbir/Version.hs +125/−0
- test/Arbitrary.hs +33/−0
- test/EditSpec.hs +40/−0
- test/EvalSpec.hs +98/−0
- test/ExprSpec.hs +40/−0
- test/LintSpec.hs +118/−0
- test/ParseSpec.hs +101/−0
- test/QuerySpec.hs +81/−0
- test/ShellSpec.hs +67/−0
- test/Spec.hs +24/−0
- test/TotalitySpec.hs +53/−0
- test/VersionSpec.hs +26/−0
+ CHANGELOG.md view
@@ -0,0 +1,7 @@+# Revision history for rozbir++## 0.1.0.0 -- 11/24/2026++- first version: lossless spec parser, partial evaluator with a pure+ sh/sed/tr/cut subset, semantic model, queries, minimal-diff edits, and the+ core, rpmlint and terra lint rulesets
+ LICENSE.md view
@@ -0,0 +1,675 @@+# GNU GENERAL PUBLIC LICENSE++Version 3, 29 June 2007++Copyright (C) 2007 Free Software Foundation, Inc.+<https://fsf.org/>++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.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ 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 <https://www.gnu.org/licenses/>.++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:++ <program> Copyright (C) <year> <name of author>+ 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 <https://www.gnu.org/licenses/>.++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 <https://www.gnu.org/licenses/why-not-lgpl.html>.
+ README.md view
@@ -0,0 +1,49 @@+# rozbir, an RPM spec library for Haskell++розбір is Ukrainian for "parsing."++rozbir parses, evaluates, edits and lints RPM spec files without running+anything: no `rpmspec`, no shell, no Lua. it was written for+[oglyad](https://github.com/terrapkg/oglyad), and+[korektor](https://github.com/terrapkg/korektor) builds a CLI and language+server on it.++```haskell+import Rozbir+import Rozbir.IO (readSpec)++main :: IO ()+main = do+ tree <- readSpec "foo.spec"+ let target = Target (Just "x86_64") (Just "linux") [("dist", Just ".fc44"), ("fedora", Just "44")]+ print (evr (resolve (newEnv False) target tree))+ print (versionInputs tree)+```++- `Rozbir.Syntax.Parse.parse` is total and lossless: `render (parse s) == s`+- `Rozbir.Spec.resolve` evaluates macros and conditionals. a small pure+ subset of shell (`echo`, `${c:0:7}`, `sed s///`, `tr`, `cut`) is+ interpreted, anything else that would run code comes back `Opaque`, and+ conditions it can't decide keep both branches. over terrapkg/packages and+ tuatara it agrees with `rpmspec` on every spec it can finish, which is 98%+ of them+- `Rozbir.Query` answers the usual questions: name, EVR, sources, patches,+ bconds, BuildRequires, and which macros feed `Version:`+- `Rozbir.Edit` sets tags and macros, bumps Release and adds changelog entries+ as minimal text edits+- `Rozbir.Lint` runs the core, rpmlint and (opt-in) terra rulesets. a comment+ like `# rozbir: ignore[hardcoded-path] reason` suppresses a finding on the+ next line, and `# rozbir: ignore-file[rule]` for the whole spec++## development++```sh+cabal build all --enable-tests+cabal test --test-show-details=direct+ormolu --mode inplace $(git ls-files '*.hs')+dev/differential.sh <(find ../packages -name '*.spec' -printf '%p\n' | xargs realpath)+```++## license++this project is licensed under GPL-3.0-or-later. see [LICENSE.md](LICENSE.md).
+ rozbir.cabal view
@@ -0,0 +1,106 @@+cabal-version: 3.0+name: rozbir+version: 0.1.0.0+synopsis: parse, evaluate, edit and lint RPM spec files+description:+ rozbir is a pure library for RPM spec files. it parses them into a+ lossless syntax tree, partially evaluates macros and conditionals without+ running any shell or Lua, edits them with minimal diffs, and lints them.++category: Distribution+homepage: https://github.com/terrapkg/rozbir+bug-reports: https://github.com/terrapkg/rozbir/issues+license: GPL-3.0-or-later+license-file: LICENSE.md+author: Cypress Reed+maintainer: cypress@fyralabs.com+build-type: Simple+extra-doc-files:+ CHANGELOG.md+ README.md++tested-with: GHC ==9.6.6 || ==9.10.3++source-repository head+ type: git+ location: https://github.com/terrapkg/rozbir.git++common shared+ default-language: GHC2021+ default-extensions:+ DeriveAnyClass+ DerivingStrategies+ LambdaCase+ MultiWayIf+ OverloadedStrings+ RecordWildCards++ ghc-options:+ -Wall -Wcompat -Widentities -Wincomplete-uni-patterns+ -Wincomplete-record-updates -Wredundant-constraints++ build-depends:+ , base >=4.18 && <4.21+ , containers >=0.6.7 && <0.8+ , deepseq >=1.4.8 && <1.6+ , text >=2.0.2 && <2.2++library+ import: shared+ hs-source-dirs: src+ exposed-modules:+ Rozbir+ Rozbir.Changelog+ Rozbir.Edit+ Rozbir.Eval+ Rozbir.Eval.Builtin+ Rozbir.Eval.LuaPattern+ Rozbir.Eval.Shell+ Rozbir.Eval.Types+ Rozbir.IO+ Rozbir.Lint+ Rozbir.Lint.Core+ Rozbir.Lint.Rpmlint+ Rozbir.Lint.Terra+ Rozbir.Lint.Types+ Rozbir.MacroFile+ Rozbir.Query+ Rozbir.Spec+ Rozbir.Syntax+ Rozbir.Syntax.Expr+ Rozbir.Syntax.Parse+ Rozbir.Syntax.Render+ Rozbir.Version++ build-depends:+ , aeson >=2.1.2 && <2.4+ , bytestring >=0.11.5 && <0.13+ , directory >=1.3.8 && <1.4+ , filepath >=1.4.300 && <1.6+ , mtl >=2.3.1 && <2.4+ , deepseq+ , time >=1.12.2 && <1.13++test-suite rozbir-test+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Spec.hs+ ghc-options: -threaded+ other-modules:+ Arbitrary+ EditSpec+ EvalSpec+ ExprSpec+ LintSpec+ ParseSpec+ QuerySpec+ ShellSpec+ TotalitySpec+ VersionSpec++ build-depends:+ , hspec >=2.11.9 && <2.12+ , QuickCheck >=2.14.3 && <2.20+ , rozbir+ , time >=1.12.2 && <1.13
+ src/Rozbir.hs view
@@ -0,0 +1,48 @@+-- | the main entry point. it re-exports what most callers need: the syntax+-- tree, parsing, evaluation and queries.+--+-- > import Data.Text.IO qualified as T+-- > import Rozbir+-- >+-- > main :: IO ()+-- > main = do+-- > tree <- parse <$> T.readFile "foo.spec"+-- > let target = Target (Just "x86_64") (Just "linux") [("dist", Just ".fc44"), ("fedora", Just "44")]+-- > spec = resolve (newEnv False) target tree+-- > case evr spec of+-- > Resolved v -> T.putStrLn (renderEVR v)+-- > Unresolved reasons -> print reasons+-- > print (versionInputs tree)+module Rozbir+ ( -- * Queries+ module Rozbir.Query,++ -- * Versions+ module Rozbir.Version,++ -- * Syntax tree+ module Rozbir.Syntax,++ -- * Parsing and rendering+ parse,+ render,++ -- * Evaluation+ resolve,+ resolveWith,+ ResolveOptions (..),+ defaultOptions,+ Spec,+ Target (..),+ unknownTarget,+ newEnv,+ )+where++import Rozbir.Eval (Target (..), newEnv, unknownTarget)+import Rozbir.Query+import Rozbir.Spec (ResolveOptions (..), Spec, defaultOptions, resolve, resolveWith)+import Rozbir.Syntax+import Rozbir.Syntax.Parse (parse)+import Rozbir.Syntax.Render (render)+import Rozbir.Version
+ src/Rozbir/Changelog.hs view
@@ -0,0 +1,146 @@+-- | parse @%changelog@ entries and write new ones+module Rozbir.Changelog+ ( Entry (..),+ EntryHeader (..),+ parseHeader,+ parseEntries,+ renderEntry,+ renderDate,+ )+where++import Control.DeepSeq (NFData)+import Data.Aeson (ToJSON (..), object, (.=))+import Data.Char (isDigit, isSpace)+import Data.List (elemIndex)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Calendar (Day, DayOfWeek (..), dayOfWeek, fromGregorianValid, toGregorian)+import GHC.Generics (Generic)+import Rozbir.Syntax (Span)+import Text.Read (readMaybe)++-- | the parts of an entry's @*@ line+data EntryHeader = EntryHeader+ { -- | the weekday as written, such as @Mon@+ ehWeekday :: !Text,+ -- | the date. 'Nothing' when it isn't a real day.+ ehDate :: !(Maybe Day),+ -- | whether the weekday is right for the date+ ehWeekdayMatches :: !Bool,+ -- | the author, usually a name and an email+ ehAuthor :: !Text,+ -- | the version after the author, if there is one+ ehEvr :: !(Maybe Text)+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | one changelog entry+data Entry = Entry+ { -- | the parsed header. its fields are empty when the header didn't parse.+ entryHeader :: !EntryHeader,+ -- | the header line, trimmed+ entryHeaderText :: !Text,+ -- | where the header line is+ entrySpan :: !Span,+ -- | the lines after the header, without blank lines+ entryItems :: ![(Span, Text)]+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON Entry where+ toJSON Entry {entryHeader = EntryHeader {..}, ..} =+ object+ [ "date" .= fmap show ehDate,+ "author" .= ehAuthor,+ "evr" .= ehEvr,+ "items" .= map snd entryItems+ ]++weekdays :: [Text]+weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]++months :: [Text]+months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]++-- | parse a header such as @* Mon Nov 23 2026 Name \<mail> - 1.0-1@. a time and timezone after the day are allowed.+-- 'Left' explains what is wrong. a weekday that doesn't match the date is not an error.+parseHeader :: Text -> Either Text EntryHeader+parseHeader line = do+ rest <- maybe (Left "a changelog entry starts with '* '") Right (T.stripPrefix "*" line)+ case T.words rest of+ wd : mon : dayT : more -> do+ monthIx <- maybe (Left ("unknown month " <> mon)) Right (elemIndex mon months)+ dayN <- maybe (Left ("bad day " <> dayT)) Right (readMaybe (T.unpack dayT))+ let (yearT, afterYear) = case more of+ t : _ : y : r | isTime t -> (y, r)+ y : r -> (y, r)+ [] -> ("", [])+ yearN <- maybe (Left ("bad year " <> yearT)) Right (readMaybe (T.unpack yearT))+ let date = fromGregorianValid yearN (monthIx + 1) dayN+ matches = case date of+ Just d -> weekdayName (dayOfWeek d) == wd+ Nothing -> False+ tailText = T.unwords afterYear+ (author, evr) = splitEvr tailText+ if wd `notElem` weekdays+ then Left ("unknown weekday " <> wd)+ else Right (EntryHeader wd date matches author evr)+ _ -> Left "the entry header needs a date"+ where+ isTime t = T.count ":" t == 2 && T.all (\c -> isDigit c || c == ':') t++splitEvr :: Text -> (Text, Maybe Text)+splitEvr t = case T.breakOnEnd ">" t of+ ("", _) -> case T.breakOnEnd " - " t of+ ("", _) -> (T.strip t, Nothing)+ (pre, evr) -> (T.strip (T.dropEnd 3 pre), nonEmpty (T.strip evr))+ (pre, after) ->+ let a = T.strip after+ evr = T.strip (maybe a id (T.stripPrefix "-" a))+ in (T.strip pre, nonEmpty evr)+ where+ nonEmpty x = if T.null x then Nothing else Just x++weekdayName :: DayOfWeek -> Text+weekdayName = \case+ Monday -> "Mon"+ Tuesday -> "Tue"+ Wednesday -> "Wed"+ Thursday -> "Thu"+ Friday -> "Fri"+ Saturday -> "Sat"+ Sunday -> "Sun"++-- | group the lines of a @%changelog@ section into entries, and return the problems found.+-- a header that fails to parse still starts an entry.+parseEntries :: [(Span, Text)] -> ([Entry], [(Span, Text)])+parseEntries = go Nothing [] []+ where+ go cur entries problems = \case+ [] -> (reverse (close cur entries), reverse problems)+ (sp, raw) : rest+ | "*" `T.isPrefixOf` T.stripStart raw -> case parseHeader (T.stripStart raw) of+ Right h -> go (Just (Entry h (T.strip raw) sp [])) (close cur entries) problems rest+ Left e -> go (Just (Entry (EntryHeader "" Nothing False "" Nothing) (T.strip raw) sp [])) (close cur entries) ((sp, e) : problems) rest+ | T.all isSpace raw -> go cur entries problems rest+ | otherwise -> case cur of+ Just e -> go (Just e {entryItems = entryItems e <> [(sp, raw)]}) entries problems rest+ Nothing -> go cur entries ((sp, "text before the first changelog entry") : problems) rest+ close cur entries = maybe entries (: entries) cur++-- | a date the way rpm writes it, such as @Mon Nov 23 2026@+renderDate :: Day -> Text+renderDate d =+ let (y, m, dd) = toGregorian d+ pad n = if n < 10 then "0" <> T.pack (show n) else T.pack (show n)+ in weekdayName (dayOfWeek d) <> " " <> (months !! (m - 1)) <> " " <> pad dd <> " " <> T.pack (show y)++-- | write a new entry from a date, author, optional version and items. items get a @- @ prefix unless they already have one.+renderEntry :: Day -> Text -> Maybe Text -> [Text] -> Text+renderEntry day author evr items =+ T.unlines (("* " <> renderDate day <> " " <> author <> maybe "" (" - " <>) evr) : map item items)+ where+ item i = if "-" `T.isPrefixOf` i then i else "- " <> i
+ src/Rozbir/Edit.hs view
@@ -0,0 +1,219 @@+-- | small text edits to a spec that keep the rest of the file unchanged.+-- functions return edits instead of new text, so callers can show or combine+-- them before calling 'apply'.+module Rozbir.Edit+ ( TextEdit (..),+ EditError (..),+ describeEditError,+ apply,+ applyToTree,+ setTag,+ setTagLiteral,+ setMacro,+ bumpRelease,+ setVersion,+ ChangelogInput (..),+ addChangelog,+ tagValueSpan,+ defineBodySpan,+ preambleTags,+ )+where++import Data.Aeson (ToJSON (..), object, (.=))+import Data.Char (isDigit)+import Data.List (sortOn)+import Data.Map.Strict qualified as Map+import Data.Ord (Down (..))+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Calendar (Day)+import Rozbir.Changelog (renderEntry)+import Rozbir.Query (definitions)+import Rozbir.Syntax+import Rozbir.Syntax.Parse (parse)+import Rozbir.Syntax.Render (render, renderFrags)++-- | replace the text in a span+data TextEdit = TextEdit+ { -- | the text to replace, empty for an insert+ editSpan :: !Span,+ editText :: !Text+ }+ deriving stock (Eq, Show)++instance ToJSON TextEdit where+ toJSON (TextEdit sp t) = object ["span" .= sp, "text" .= t]++-- | why an edit couldn't be made+data EditError+ = -- | the thing to edit isn't in the spec+ NotFound Text+ | -- | it's set on more than one line, such as in both branches of an @%if@+ Ambiguous Text [Span]+ | -- | it's there but can't be edited safely, with a message+ CantEdit Text+ deriving stock (Eq, Show)++-- | a message for the user+describeEditError :: EditError -> Text+describeEditError = \case+ NotFound what -> "no " <> what <> " to edit"+ Ambiguous what _ -> what <> " is set in more than one place, so there's no single line to edit"+ CantEdit why -> why++-- | apply edits to text. edits must not overlap.+apply :: [TextEdit] -> Text -> Text+apply edits src = foldl step src (sortOn (Down . posOffset . spanStart . editSpan) edits)+ where+ step t (TextEdit (Span s e) new) = T.take (posOffset s) t <> new <> T.drop (posOffset e) t++-- | apply edits to a tree and parse the result again+applyToTree :: [TextEdit] -> Tree -> Tree+applyToTree edits tree = parse (apply edits (render tree))++-- | span of a tag line's value, after the colon and spacing+tagValueSpan :: Line -> TagLine -> Span+tagValueSpan l TagLine {..} =+ let start = advancePos (spanStart (lineSpan l)) (tagIndent <> tagName <> maybe "" (\q -> qualGap q <> qualRaw q) tagQualifier <> tagSep)+ in Span start (advancePos start (renderFrags tagValue))++-- | span of a @%global@ or @%define@ body+defineBodySpan :: Line -> DefineLine -> Span+defineBodySpan l DefineLine {..} =+ let prefix =+ defIndent+ <> defKeyword+ <> defGap+ <> defName+ <> maybe "" (\o -> "(" <> o <> ")") defOpts+ <> maybe "" (\m -> "<" <> m <> ">") defMods+ <> defSep+ start = advancePos (spanStart (lineSpan l)) prefix+ in Span start (advancePos start (renderFrags defBody))++-- | tag lines before the first section header, so main package tags only+preambleTags :: Tree -> [(Line, TagLine)]+preambleTags tree = go Nothing (treeLines tree)+ where+ go _ [] = []+ go sec (l : ls) = case lineBody l of+ Header h -> go (Just (secKind h)) ls+ Tag t | sec == Nothing -> (l, t) : go sec ls+ _ -> go sec ls++singleMacro :: [Frag] -> Maybe Name+singleMacro = \case+ [Macro (Bare flags n)] | T.all (== '?') flags -> Just n+ [Macro (Braced flags n Nothing)] | T.all (== '?') flags -> Just n+ _ -> Nothing++findTag :: Text -> Tree -> Either EditError (Line, TagLine)+findTag key tree = case [x | x@(_, t) <- preambleTags tree, T.toLower (tagName t) == T.toLower key] of+ [] -> Left (NotFound (key <> " tag"))+ [x] -> Right x+ xs -> Left (Ambiguous key [lineSpan l | (l, _) <- xs])++-- | set a main package tag's value on its own line, even if it's a macro+setTagLiteral :: Text -> Text -> Tree -> Either EditError [TextEdit]+setTagLiteral key value tree = do+ (l, t) <- findTag key tree+ Right [TextEdit (tagValueSpan l t) value]++-- | set a main package tag. if the value is just a macro the spec defines,+-- like @Version: %{ver}@, the definition is changed instead.+setTag :: Text -> Text -> Tree -> Either EditError [TextEdit]+setTag key value tree = do+ (l, t) <- findTag key tree+ case singleMacro (tagValue t) of+ Just n | Map.member n (definitions tree) -> setMacro n value tree+ _ -> Right [TextEdit (tagValueSpan l t) value]++-- | set a @%global@ or @%define@ body. if the body is just another macro+-- the spec defines, that one is changed instead.+setMacro :: Name -> Text -> Tree -> Either EditError [TextEdit]+setMacro n value tree = go (8 :: Int) n+ where+ defs = definitions tree+ located = [(l, d) | l@Line {lineBody = Define d} <- treeLines tree, defKind d `elem` [DefGlobal, DefDefine]]+ go fuel name' = case [x | x@(_, d) <- located, defName d == name'] of+ [] -> Left (NotFound ("%" <> name' <> " definition"))+ [(l, d)] -> case singleMacro (defBody d) of+ Just inner | fuel > 0, Map.member inner defs -> go (fuel - 1) inner+ _ -> Right [TextEdit (defineBodySpan l d) value]+ xs -> Left (Ambiguous ("%" <> name') [lineSpan l | (l, _) <- xs])++releaseTarget :: Tree -> Either EditError (Span, [Frag])+releaseTarget tree = do+ (l, t) <- findTag "release" tree+ case singleMacro (tagValue t) of+ Just n | Map.member n (definitions tree) -> follow (8 :: Int) n+ _ -> Right (tagValueSpan l t, tagValue t)+ where+ located = [(l, d) | l@Line {lineBody = Define d} <- treeLines tree, defKind d `elem` [DefGlobal, DefDefine]]+ follow fuel n = case [x | x@(_, d) <- located, defName d == n] of+ [(l, d)] -> case singleMacro (defBody d) of+ Just inner | fuel > 0, Map.member inner (definitions tree) -> follow (fuel - 1) inner+ _ -> Right (defineBodySpan l d, defBody d)+ [] -> Left (NotFound ("%" <> n <> " definition"))+ xs -> Left (Ambiguous ("%" <> n) [lineSpan l | (l, _) <- xs])++-- | add 1 to the number at the start of Release, keeping the rest. fails+-- with 'CantEdit' for @%autorelease@ or other non-numeric releases.+bumpRelease :: Tree -> Either EditError [TextEdit]+bumpRelease = editReleaseNumber (+ 1)++editReleaseNumber :: (Integer -> Integer) -> Tree -> Either EditError [TextEdit]+editReleaseNumber f tree = do+ (sp, frags) <- releaseTarget tree+ case frags of+ Lit t : _+ | (digits, _) <- T.span isDigit t,+ not (T.null digits) ->+ let n = read (T.unpack digits) :: Integer+ start = spanStart sp+ in Right [TextEdit (Span start (advancePos start digits)) (T.pack (show (f n)))]+ _ -> Left (CantEdit "Release doesn't start with a number (it may use %autorelease), so it can't be bumped")++-- | set Version and reset Release to 1. Release is left alone if it can't+-- be edited.+setVersion :: Text -> Tree -> Either EditError [TextEdit]+setVersion v tree = do+ versionEdits <- setTag "version" v tree+ let releaseEdits = either (const []) id (editReleaseNumber (const 1) tree)+ Right (versionEdits <> releaseEdits)++-- | a new changelog entry+data ChangelogInput = ChangelogInput+ { ciDate :: !Day,+ -- | name and email, like @Jane Doe \<jane\@example.com\>@+ ciAuthor :: !Text,+ -- | the version-release to show after the author, if any+ ciEvr :: !(Maybe Text),+ -- | the items. a leading dash is added when missing.+ ciItems :: ![Text]+ }+ deriving stock (Eq, Show)++-- | add an entry at the top of @%changelog@, creating the section at the end+-- of the file if there isn't one+addChangelog :: ChangelogInput -> Tree -> Either EditError [TextEdit]+addChangelog ChangelogInput {..} tree =+ let entry = renderEntry ciDate ciAuthor ciEvr ciItems+ headers = [l | l@Line {lineBody = Header h} <- treeLines tree, secKind h == SChangelog]+ in case headers of+ [l] ->+ let at = spanEnd (lineFullSpan l)+ rest = [x | x <- treeLines tree, posOffset (spanStart (lineSpan x)) >= posOffset at]+ separator = case rest of+ Line {lineBody = Blank _} : _ -> ""+ [] -> ""+ _ -> "\n"+ newline = if T.null (lineEol l) then "\n" else ""+ in Right [TextEdit (pointSpan at) (newline <> entry <> separator)]+ [] ->+ let src = render tree+ end = advancePos startPos src+ lead = if T.null src || "\n" `T.isSuffixOf` src then "\n" else "\n\n"+ in Right [TextEdit (pointSpan end) (lead <> "%changelog\n" <> entry)]+ many -> Left (Ambiguous "%changelog" (map lineSpan many))
+ src/Rozbir/Eval.hs view
@@ -0,0 +1,743 @@+-- | partial evaluation of rpm macros and conditionals, following rpm's own+-- rules. it never runs a shell or Lua. anything that would need to becomes an+-- 'Opaque' hole, and conditions that can't be decided run every branch and+-- merge the results.+module Rozbir.Eval+ ( module Rozbir.Eval.Types,+ Eval,+ EvalState (..),+ Lookup (..),+ runEval,+ initialState,+ newEnv,+ withTarget,+ withMacroFile,+ expandText,+ expandFrags,+ expandValue,+ expandAt,+ evalCond,+ lookupMacro,+ isDefined,+ pushMacro,+ popMacro,+ defineAuto,+ message,+ atSpan,+ currentSpan,+ getEnv,+ putEnv,+ mergeEnvs,+ maxDepth,+ freeField,+ )+where++import Control.Monad (forM_, when)+import Control.Monad.State.Strict (State, get, gets, modify', runState)+import Data.Char (isSpace)+import Data.List qualified as L+import Data.Map.Merge.Strict qualified as Merge+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe, isJust)+import Data.Text (Text)+import Data.Text qualified as T+import Rozbir.Eval.Builtin+import Rozbir.Eval.LuaPattern (luaGsub)+import Rozbir.Eval.Shell (runShell)+import Rozbir.Eval.Types+import Rozbir.Syntax+import Rozbir.Syntax.Expr (boolify, evalExpr, itemsFromFrags, itemsFromValue, renderExprValue)+import Rozbir.Syntax.Parse (isBlankChar, isNameChar, matchClose, parseFrags)+import Rozbir.Syntax.Render (renderFrags, renderMacro)++-- | evaluator state+data EvalState = EvalState+ { esEnv :: !Env,+ esLevel :: !Int,+ -- | lookups left before giving up with 'DepthLimit'+ esFuel :: !Int,+ -- | messages so far, newest first+ esMessages :: ![EvalMessage],+ esSpan :: !(Maybe Span),+ -- | undefined macros used in a closed env, newest first+ esUndefined :: ![(Name, Span)]+ }+ deriving stock (Show)++-- | the evaluation monad. it's pure, with no IO.+type Eval = State EvalState++-- | the result of looking up a macro name+data Lookup+ = Found MacroDef+ | -- | a builtin, which wins over definitions+ IsBuiltin Builtin+ | -- | definitely not defined+ NotFound+ | -- | might be defined+ Unsure Reason+ deriving stock (Show)++-- | the nesting limit, the same as rpm's+maxDepth :: Int+maxDepth = 64++-- | a fresh state for an environment+initialState :: Env -> EvalState+initialState env = EvalState env 0 2000000 [] Nothing []++-- | run an evaluation+runEval :: EvalState -> Eval a -> (a, EvalState)+runEval st act = runState act st++-- | an environment with only rpm's built-in macros. 'True' makes it closed,+-- meaning system macros are already loaded.+newEnv :: Bool -> Env+newEnv closed = L.foldl' build (L.foldl' add (Env Map.empty closed) preludeMacros) buildTimeMacros+ where+ add env (name, opts, body) = pushDef name (MacroDef opts (BodyRaw body) OriginPrelude 0 False) env+ build env (name, body) = pushDef name (MacroDef Nothing body OriginPrelude 0 False) env++buildTimeMacros :: [(Name, MacroBody)]+buildTimeMacros =+ [ ("buildroot", BodyOpaque (HostDependent "the buildroot")),+ ("builddir", BodyOpaque (HostDependent "the build directory")),+ ("buildsubdir", BodyOpaque (HostDependent "the directory %setup made")),+ ("specpartsdir", BodyOpaque (HostDependent "the build directory")),+ ("_top_builddir", BodyOpaque (HostDependent "the build directory")),+ ("_docdir", BodyRaw "%{_defaultdocdir}"),+ ("_licensedir", BodyRaw "%{_defaultlicensedir}")+ ]++pushDef :: Name -> MacroDef -> Env -> Env+pushDef name def env = env {envMacros = Map.insertWith (<>) name [def] (envMacros env)}++-- | apply a target. its macros replace any existing definitions.+withTarget :: Target -> Env -> Env+withTarget Target {..} env0 = L.foldl' apply env0 (archMacros <> osMacros <> targetMacros)+ where+ archMacros = maybe [] (\a -> [("_target_cpu", Just a), ("_arch", Just a), ("_build_cpu", Just a)]) targetArch+ osMacros = maybe [] (\o -> [("_target_os", Just o), ("_os", Just o), ("_build_os", Just o)]) targetOs+ apply env (name, value) = env {envMacros = Map.insert name [MacroDef Nothing (maybe BodyUndefined BodyRaw value) OriginTarget 0 False] (envMacros env)}++-- | add definitions from a macro file, as name, options, body, file and line+withMacroFile :: [(Name, Maybe Text, Text, FilePath, Int)] -> Env -> Env+withMacroFile defs env0 = L.foldl' (\env (n, o, b, f, l) -> pushDef n (MacroDef o (BodyRaw (macroFileBody b)) (OriginFile f l) 0 False) env) env0 defs++macroFileBody :: Text -> Text+macroFileBody b = case T.uncons b of+ Just ('{', _) | Just (inner, _) <- matchClose '{' '}' b -> inner+ _ -> fst (freeField b)++-- | the current environment+getEnv :: Eval Env+getEnv = gets esEnv++-- | replace the environment+putEnv :: Env -> Eval ()+putEnv env = modify' (\s -> s {esEnv = env})++-- | the source location being evaluated+currentSpan :: Eval (Maybe Span)+currentSpan = gets esSpan++-- | run with a source location, restoring the old one after+atSpan :: Span -> Eval a -> Eval a+atSpan sp act = do+ old <- gets esSpan+ modify' (\s -> s {esSpan = Just sp})+ r <- act+ modify' (\s -> s {esSpan = old})+ pure r++-- | record a message at the current location+message :: Severity -> Text -> Eval ()+message sev txt = do+ sp <- gets esSpan+ modify' (\s -> s {esMessages = EvalMessage sev sp txt : esMessages s})++-- | look up a name. in an open env, a missing name is 'Unsure' unless only the+-- spec could define it, like tags and macro arguments.+lookupMacro :: Name -> Eval Lookup+lookupMacro name+ | Just b <- builtinNamed name = pure (IsBuiltin b)+ | otherwise = do+ EvalState {esEnv = Env macros closed, esLevel = lvl} <- get+ pure $ case Map.lookup name macros of+ Just (m : _)+ | macroAuto m && lvl > macroLevel m -> NotFound+ | otherwise -> case macroBody m of+ BodyUndefined -> NotFound+ BodyMaybe r -> Unsure r+ _ -> Found m+ _+ | closed || isAutoName name || name `elem` closedNames || isKeyword name || any (`T.isPrefixOf` name) closedPrefixes -> NotFound+ | otherwise -> Unsure (Undefined name)++isKeyword :: Name -> Bool+isKeyword n =+ T.toLower n `elem` map fst sectionKinds+ || n `elem` ["if", "ifarch", "ifnarch", "ifos", "ifnos", "elif", "elifarch", "elifos", "else", "endif", "include"]+ || n `elem` ["doc", "docdir", "dir", "ghost", "config", "lang", "attr", "defattr", "exclude", "caps", "verify", "readme", "artifact", "pubkey", "missingok"]++-- | whether a name is defined+isDefined :: Name -> Eval Tri+isDefined name =+ lookupMacro name >>= \case+ Found _ -> pure Yes+ IsBuiltin _ -> pure Yes+ NotFound -> pure No+ Unsure r -> pure (Unknown [r])++-- | add a definition, like @%define@+pushMacro :: Name -> MacroDef -> Eval ()+pushMacro name def = modify' (\s -> s {esEnv = pushDef name def (esEnv s)})++-- | remove the newest definition+popMacro :: Name -> Eval ()+popMacro name = modify' $ \s ->+ let env = esEnv s+ in s {esEnv = env {envMacros = Map.update (\case _ : rest | not (null rest) -> Just rest; _ -> Nothing) name (envMacros env)}}++-- | define a macro with known text at the current depth+defineAuto :: Name -> Text -> Eval ()+defineAuto name body = do+ lvl <- gets esLevel+ sp <- gets esSpan+ pushMacro name (MacroDef Nothing (BodyValue (known body)) (maybe OriginAuto OriginTag sp) lvl False)++-- | merge the environments of branches that couldn't be decided. a macro they+-- disagree on becomes 'Ambiguous', and one only some define becomes maybe+-- defined.+mergeEnvs :: Env -> Env -> Env+mergeEnvs a b =+ Env+ ( Merge.merge+ (Merge.mapMissing (\k s -> conflict k s []))+ (Merge.mapMissing (\k s -> conflict k [] s))+ (Merge.zipWithMatched (\k s1 s2 -> if s1 == s2 then s1 else conflict k s1 s2))+ (envMacros a)+ (envMacros b)+ )+ (envClosed a && envClosed b)+ where+ conflict k s1 s2 =+ let top1 = defined s1+ top2 = defined s2+ rest = drop 1 (if length s1 >= length s2 then s1 else s2)+ template = case s1 <> s2 of+ t : _ -> t+ [] -> MacroDef Nothing BodyUndefined OriginMerged 0 False+ in case (top1, top2) of+ (Just m1, Just m2)+ | macroOpts m1 == macroOpts m2 -> m1 {macroBody = BodyOpaque (Ambiguous k), macroOrigin = OriginMerged} : rest+ _ -> template {macroBody = BodyMaybe (Ambiguous k), macroOrigin = OriginMerged} : rest+ defined = \case+ m : _ | not (isUndefined (macroBody m)) -> Just m+ _ -> Nothing+ isUndefined = \case+ BodyUndefined -> True+ BodyMaybe _ -> True+ _ -> False++luaDefines :: Text -> Eval ()+luaDefines src = mapM_ maybeDefined (luaDefinedNames src)+ where+ maybeDefined n = do+ lvl <- gets esLevel+ pushMacro n (MacroDef Nothing (BodyMaybe RunsLua) OriginAuto lvl False)++luaDefinedNames :: Text -> [Name]+luaDefinedNames src = filter (not . T.null) (defines <> assigns <> indexed)+ where+ defines = [T.takeWhile isNameChar (T.dropWhile (`elem` ['"', '\'', ' ', '(']) (T.drop 10 rest)) | (_, rest) <- T.breakOnAll "rpm.define" src]+ assigns = [n | (_, rest) <- T.breakOnAll "macros." src, let n = T.takeWhile isNameChar (T.drop 7 rest), "=" `T.isPrefixOf` T.stripStart (T.drop (7 + T.length n) rest), not ("==" `T.isPrefixOf` T.stripStart (T.drop (7 + T.length n) rest))]+ indexed = [T.takeWhile isNameChar (T.drop 1 q) | (_, rest) <- T.breakOnAll "macros[" src, let q = T.dropWhile (== ' ') (T.drop 7 rest), Just (c, _) <- [T.uncons q], c == '"' || c == '\'']++noteUndefined :: Int -> Name -> Eval ()+noteUndefined d name = do+ st <- get+ case esSpan st of+ Just sp+ | d == 0,+ envClosed (esEnv st),+ not (isKeyword name),+ not (isAutoName name),+ T.length name > 1,+ name `notElem` ["setup", "patch", "license"] ->+ modify' (\s -> s {esUndefined = (name, sp) : esUndefined s})+ _ -> pure ()++uncertain :: [Reason] -> Eval Value -> Eval Value+uncertain rs act = do+ before <- gets esEnv+ v <- act+ after <- gets esEnv+ putEnv (mergeEnvs before after)+ pure $+ if valueNull v+ then mempty+ else Value [Opaque r Nothing | r <- take 1 (rs <> [Failed "unknown"])]++spend :: Eval Bool+spend = do+ fuel <- gets esFuel+ if fuel <= 0+ then pure False+ else modify' (\s -> s {esFuel = fuel - 1}) >> pure True++-- | expand text, like @rpm --eval@+expandText :: Text -> Eval Value+expandText t = expandAt 0 (parseFrags t)++-- | expand fragments at a depth, attaching the current location to holes+expandAt :: Int -> [Frag] -> Eval Value+expandAt d fs = do+ sp <- gets esSpan+ v <- expandFrags d fs+ pure (attachSpan sp (stripQuoteMarks v))++attachSpan :: Maybe Span -> Value -> Value+attachSpan sp (Value ps) = Value [case p of Opaque r Nothing -> Opaque r sp; _ -> p | p <- ps]++-- | expand fragments at a depth. an undefined macro in a closed env stays as+-- literal text, like rpm.+expandFrags :: Int -> [Frag] -> Eval Value+expandFrags d = go+ where+ go = \case+ [] -> pure mempty+ Lit t : rest -> (known t <>) <$> go rest+ Escape : rest -> (known "%" <>) <$> go rest+ Macro m : rest -> do+ (v, rest') <- expandMacro d m rest+ (v <>) <$> go rest'++-- | expand a value's known text again, like @%{expand:...}@. if a hole might+-- split a macro, the result is just that hole.+expandValue :: Int -> Value -> Eval Value+expandValue d v@(Value ps)+ | not (isKnown v) && any splitsMacro ps = pure (Value [o | o@(Opaque {}) <- take 1 [x | x@(Opaque {}) <- ps]])+ | otherwise = mconcat <$> mapM piece ps+ where+ piece = \case+ Known t -> expandFrags d (parseFrags t)+ o -> pure (Value [o])+ splitsMacro = \case+ Known t -> any unterminated (parseFrags t)+ _ -> False+ unterminated = \case+ Macro (Unterminated _ _) -> True+ _ -> False++expandMacro :: Int -> MacroRef -> [Frag] -> Eval (Value, [Frag])+expandMacro d m rest+ | d > maxDepth = pure (opaque DepthLimit, rest)+ | otherwise = case m of+ Shell fs -> do+ script <- expandFrags (d + 1) fs+ pure $ case knownText (stripQuoteMarks script) >>= either (const Nothing) Just . runShell of+ Just out -> (known out, rest)+ Nothing -> (opaque RunsShell, rest)+ Lua src -> do+ luaDefines src+ pure (opaque RunsLua, rest)+ Unterminated c _ -> do+ message Error ("unterminated %" <> T.singleton c)+ pure (known (renderMacro m), rest)+ Expr fs -> (,rest) <$> expression d True fs+ Bare flags name -> reference d m flags name Nothing True rest+ Braced flags name arg -> reference d m flags name arg False rest++expression :: Int -> Bool -> [Frag] -> Eval Value+expression d expandMode fs = do+ r <- evalExpr expandMode (\ref -> fst <$> expandMacro (d + 1) ref []) (itemsFromFrags fs)+ case r of+ Left e -> do+ message Error ("bad expression: " <> e)+ pure (opaque (Failed e))+ Right v -> pure (renderExprValue v)++reference :: Int -> MacroRef -> Text -> Name -> Maybe MacroArg -> Bool -> [Frag] -> Eval (Value, [Frag])+reference d m flags name arg isBare rest+ | T.null name = pure (known (renderMacro m), rest)+ | otherwise = do+ ok <- spend+ if not ok+ then pure (opaque DepthLimit, rest)+ else do+ look <- lookupMacro name+ let negated = odd (T.count "!" flags)+ checks = T.any (== '?') flags || "-" `T.isPrefixOf` name+ if checks+ then do+ let exists = case look of+ Found _ -> Yes+ IsBuiltin _ -> Yes+ NotFound -> No+ Unsure r -> Unknown [r]+ wanted = if negated then triNot exists else exists+ action = case (arg, look) of+ (Just (ColonArg fs), _) -> expandFrags (d + 1) fs+ (_, Found def) -> callMacro d name def Nothing+ (_, IsBuiltin b) -> fst <$> builtin d b NoArgs []+ (_, Unsure r) | not negated -> pure (opaque r)+ _ -> pure mempty+ v <- case wanted of+ No -> pure mempty+ Yes -> action+ Unknown rs -> uncertain rs action+ pure (v, rest)+ else case look of+ NotFound -> do+ noteUndefined d name+ pure (known (renderMacro m), rest)+ Unsure r -> pure (opaque r, rest)+ Found def+ | macroOpts def == Nothing -> (,rest) <$> callMacro d name def Nothing+ | otherwise -> do+ (args, rest') <- userArgs+ v <- callMacro d name def (Just args)+ pure (v, rest')+ IsBuiltin b -> builtinCall b+ where+ userArgs = case arg of+ Just (ColonArg fs) -> (\v -> ([v], rest)) <$> expandFrags (d + 1) fs+ Just (SpaceArg fs) -> (,rest) . splitArgs <$> expandFrags (d + 1) fs+ Nothing+ | isBare,+ followedByBlank rest -> do+ let (lineFrags, rest') = takeLine rest+ v <- expandFrags (d + 1) lineFrags+ pure (splitArgs v, rest')+ | otherwise -> pure ([], rest)++ builtinCall b = case builtinArgStyle b of+ ParsesRaw -> case arg of+ Just (ColonArg fs) -> builtin d b (RawWhole (renderFrags fs)) rest+ Just (SpaceArg fs) -> builtin d b (RawWhole (T.drop 1 (renderFrags fs))) rest+ Nothing+ | isBare -> builtin d b (RawRest (renderFrags rest)) []+ | otherwise -> builtin d b NoArgs rest+ TakesNoArgs -> builtin d b NoArgs rest+ _ -> do+ (args, rest') <- case arg of+ Just (ColonArg fs) -> (\v -> (Args [v], rest)) <$> expandFrags (d + 1) fs+ Just (SpaceArg fs) -> (,rest) . Args . splitArgs <$> expandFrags (d + 1) fs+ Nothing+ | isBare,+ followedByBlank rest -> do+ let (lineFrags, rest') = takeLine rest+ v <- expandFrags (d + 1) lineFrags+ pure (Args (splitArgs v), rest')+ | otherwise -> pure (NoArgs, rest)+ builtin d b args rest'++followedByBlank :: [Frag] -> Bool+followedByBlank = \case+ Lit t : _ | Just (c, _) <- T.uncons t -> isBlankChar c+ _ -> False++takeLine :: [Frag] -> ([Frag], [Frag])+takeLine = go []+ where+ go acc = \case+ [] -> (reverse acc, [])+ Lit t : rest+ | (pre, post) <- T.break (== '\n') t,+ not (T.null post) ->+ let continued = "\\" `T.isSuffixOf` pre+ remaining = if continued then T.drop 1 post else post+ in (reverse (Lit pre : acc), [Lit remaining | not (T.null remaining)] <> rest)+ f : rest -> go (f : acc) rest++splitArgs :: Value -> [Value]+splitArgs v = case knownText v of+ Just t -> map known (splitQuoted t)+ Nothing -> valueWords (stripQuoteMarks v)++callMacro :: Int -> Name -> MacroDef -> Maybe [Value] -> Eval Value+callMacro d name def margs = case macroBody def of+ BodyLiteral t -> pure (known t)+ BodyOpaque r -> pure (opaque r)+ BodyMaybe r -> pure (opaque r)+ BodyUndefined -> pure (known ("%" <> name))+ BodyRaw t -> withArgs (expandFrags (d + 1) (parseFrags t))+ BodyValue v -> withArgs (expandValue (d + 1) v)+ where+ withArgs body = case margs of+ Nothing -> body+ Just args -> do+ lvl <- (+ 1) <$> gets esLevel+ modify' (\s -> s {esLevel = lvl})+ let auto n b = pushMacro n (MacroDef Nothing b OriginAuto lvl True)+ bodyOf v = maybe (BodyOpaque (headReason v)) BodyLiteral (knownText v)+ placeholders = zip [0 :: Int ..] args+ asText (i, v) = fromMaybe ("\0arg" <> T.pack (show i)) (knownText v)+ textArgs = map asText placeholders+ back t = maybe (known t) snd (lookup t (zip textArgs placeholders))+ auto "0" (BodyLiteral name)+ auto "**" (bodyOf (joinValues args))+ result <- case getopt (fromMaybe "" (macroOpts def)) textArgs of+ Left c -> do+ message Error ("unknown option -" <> T.singleton c <> " for %" <> name)+ pure (opaque (Failed ("unknown option -" <> T.singleton c <> " for %" <> name)))+ Right (GetoptResult opts positional) -> do+ forM_ opts $ \(c, optArg) -> do+ let flag = "-" <> T.singleton c+ auto flag (BodyLiteral (maybe flag (\a -> flag <> " " <> a) optArg))+ forM_ optArg $ \a -> auto (flag <> "*") (bodyOf (back a))+ auto "#" (BodyLiteral (T.pack (show (length positional))))+ forM_ (zip [1 :: Int ..] positional) $ \(i, a) -> auto (T.pack (show i)) (bodyOf (back a))+ auto "*" (bodyOf (joinValues (map back positional)))+ body+ freeLevel lvl+ modify' (\s -> s {esLevel = lvl - 1})+ pure result+ headReason v = case reasons v of+ r : _ -> r+ [] -> Failed "unknown argument"++joinValues :: [Value] -> Value+joinValues = \case+ [] -> mempty+ v : vs -> v <> mconcat (map (known " " <>) vs)++freeLevel :: Int -> Eval ()+freeLevel lvl = modify' $ \s ->+ let env = esEnv s+ prune = dropWhile ((>= lvl) . macroLevel)+ macros' = Map.mapMaybe (\stack -> case prune stack of [] -> Nothing; st -> Just st) (envMacros env)+ in s {esEnv = env {envMacros = macros'}}++data BArgs+ = NoArgs+ | Args [Value]+ | RawWhole Text+ | RawRest Text++builtin :: Int -> Builtin -> BArgs -> [Frag] -> Eval (Value, [Frag])+builtin d b args rest = case b of+ BDefine -> raw (defineRaw False True)+ BGlobal -> raw (defineRaw True False)+ BDnl -> case args of+ RawRest t -> pure (mempty, parseFrags (T.drop 1 (T.dropWhile (/= '\n') t)))+ _ -> done mempty+ BLua -> case args of+ RawRest t -> do+ let (script, after) = T.break (== '\n') t+ luaDefines script+ pure (opaque RunsLua, parseFrags after)+ RawWhole t -> luaDefines t >> done (opaque RunsLua)+ _ -> done (opaque RunsLua)+ BVerbose -> case args of+ RawRest t -> pure (known "0", parseFrags t)+ _ -> done mempty+ BUndefine -> do+ forM_ (take 1 argList) $ \v -> forM_ (knownText v) undefine+ done mempty+ BP -> sourceRef "%PATCH"+ BS -> sourceRef "%SOURCE"+ BBasename -> unary posixBasename+ BDirname -> unary posixDirname+ BSuffix -> unary suffix+ BShrink -> unary shrink+ BU2p -> unary urlPath+ BUrl2path -> unary urlPath+ BSpan -> done (firstArg)+ BQuote -> done (mapKnown (\t -> "\x1f" <> t <> "\x1f") (joinValues argList))+ BShescape -> strings (Just . shescape)+ BExpand -> expandValue (d + 1) firstArg >>= done+ BExprFn -> do+ r <- evalExpr False (\_ -> pure mempty) (itemsFromValue firstArg)+ case r of+ Left e -> message Error ("bad %{expr}: " <> e) >> done (opaque (Failed e))+ Right v -> done (renderExprValue v)+ BGetenv -> done (opaque ReadsEnv)+ BXdg -> done (opaque ReadsEnv)+ BExists -> done (opaque ReadsFilesystem)+ BLoad -> done (opaque ReadsFilesystem)+ BGetncpus -> done (opaque (HostDependent "cpu count"))+ BRpmversion -> done (opaque (HostDependent "rpm version"))+ BGetconfdir -> done (known "/usr/lib/rpm")+ BDump -> done mempty+ BTrace -> done mempty+ BEcho -> say Info >> done mempty+ BWarn -> say Warn >> done mempty+ BError -> do+ say Error+ done (opaque (Failed ("%{error:" <> showValue firstArg <> "}")))+ BLen -> strings (\case a : _ -> Just (luaLen a); [] -> Nothing)+ BUpper -> strings (\case a : _ -> Just (asciiUpper a); [] -> Nothing)+ BLower -> strings (\case a : _ -> Just (asciiLower a); [] -> Nothing)+ BReverse -> strings (\case a : _ -> Just (luaReverse a); [] -> Nothing)+ BRep -> luaStrings luaRep+ BSub -> luaStrings luaSub+ BGsub -> case traverse knownText argList of+ Just ts -> done (either (const (opaque RunsLua)) known (luaGsub ts))+ Nothing -> done (opaque (headReason (mconcat argList)))+ BMacrobody -> case knownText firstArg of+ Just n -> do+ look <- lookupMacro n+ case look of+ Found def -> done $ case macroBody def of+ BodyRaw t -> known t+ BodyValue v -> v+ BodyLiteral t -> known t+ BodyOpaque r -> opaque r+ BodyMaybe r -> opaque r+ BodyUndefined -> mempty+ Unsure r -> done (opaque r)+ _ -> message Error ("no such macro: " <> n) >> done (opaque (Failed ("no such macro: " <> n)))+ Nothing -> done (opaque (headReason firstArg))+ BUncompress -> do+ cmd <- expandText "%__rpmuncompress "+ done (cmd <> firstArg)+ where+ done v = pure (v, rest)+ argList = case args of+ Args vs -> vs+ _ -> []+ firstArg = case argList of+ v : _ -> v+ [] -> mempty+ headReason v = case reasons v of+ r : _ -> r+ [] -> Failed "unknown"+ unary f = done (maybe (opaque (headReason firstArg)) (known . f) (knownText firstArg))+ strings f = case traverse knownText argList of+ Just ts -> done (maybe mempty known (f ts))+ Nothing -> done (opaque (headReason (mconcat argList)))+ luaStrings f = case traverse knownText argList of+ Just ts -> done (maybe (opaque RunsLua) known (f ts))+ Nothing -> done (opaque (headReason (mconcat argList)))+ say sev = message sev (showValue (joinValues argList))+ sourceRef prefix = case knownText firstArg of+ Just n -> (,rest) <$> expandFrags (d + 1) (parseFrags (prefix <> n))+ Nothing -> done (opaque (headReason firstArg))+ raw f = case args of+ RawRest t -> do+ remaining <- f False t+ pure (mempty, parseFrags remaining)+ RawWhole t -> f True t >> done mempty+ _ -> done mempty+ defineRaw isGlobal handleOpts whole t = define d isGlobal handleOpts whole t++undefine :: Name -> Eval ()+undefine name = do+ look <- gets (Map.lookup name . envMacros . esEnv)+ closed <- gets (envClosed . esEnv)+ case look of+ Just [_] | not closed -> popMacro name >> pushMacro name (MacroDef Nothing BodyUndefined OriginAuto 0 False)+ Just (_ : _) -> popMacro name+ _ -> when (not closed) (pushMacro name (MacroDef Nothing BodyUndefined OriginAuto 0 False))++define :: Int -> Bool -> Bool -> Bool -> Text -> Eval Text+define d isGlobal handleOpts whole t0 = do+ let (flagExpand, flagGlobal, t1) = if handleOpts then options False False t0 else (False, False, t0)+ expandBody = isGlobal || flagExpand+ t2 = T.dropWhile isBlankChar t1+ (name, t3) = T.span isNameChar t2+ (opts, t4) = delimited '(' ')' t3+ (mods, t5) = delimited '<' '>' t4+ afterWs = T.dropWhile isBlankChar t5+ (bodyText, remaining)+ | whole = (afterWs, "")+ | Just ('{', _) <- T.uncons afterWs, Just (inner, after) <- matchClose '{' '}' afterWs = (inner, after)+ | otherwise = freeField afterWs+ remaining' = T.dropWhile (\c -> c == '\n' || c == '\r') remaining+ literal = maybe False (T.elem 'l') mods+ validName = case T.uncons name of+ Just (c, more) -> (c /= '_' && not (isNameDigit c)) || (c == '_' && not (T.null more))+ Nothing -> False+ if+ | not validName -> message Error ("macro %" <> name <> " has an illegal name") >> pure remaining'+ | isJust (builtinNamed name) -> message Error ("macro %" <> name <> " is a built-in") >> pure remaining'+ | T.null bodyText -> message Error ("macro %" <> name <> " has an empty body") >> pure remaining'+ | otherwise -> do+ lvl <- gets esLevel+ sp <- gets esSpan+ let origin = maybe OriginAuto OriginSpec sp+ level = if isGlobal || flagGlobal then 0 else lvl+ body <-+ if+ | literal -> pure (BodyLiteral bodyText)+ | expandBody -> BodyValue . stripQuoteMarks <$> expandFrags (d + 1) (parseFrags bodyText)+ | otherwise -> pure (BodyRaw bodyText)+ pushMacro name (MacroDef opts body origin level False)+ pure remaining'+ where+ isNameDigit c = c >= '0' && c <= '9'+ options e g t =+ let t' = T.dropWhile isBlankChar t+ in case T.uncons t' of+ Just ('-', more) ->+ let (letters, after) = T.span (not . isSpace) more+ in if T.null letters then (e, g, t') else options (e || T.elem 'e' letters) (g || T.elem 'g' letters) after+ _ -> (e, g, t')+ delimited open close t = case T.uncons t of+ Just (c, more) | c == open, (inner, after) <- T.break (== close) more, not (T.null after) -> (Just inner, T.drop 1 after)+ _ -> (Nothing, t)++-- | split a free-form macro body from the rest, like rpm. backslashes escape+-- the next character and are dropped.+freeField :: Text -> (Text, Text)+freeField t = go (0 :: Int) (0 :: Int) (0 :: Int) [] (T.unpack t)+ where+ finish acc rest = (T.dropWhileEnd (\c -> isBlankChar c || c == '\n' || c == '\r') (T.pack (reverse acc)), T.pack rest)+ go bc pc xc acc = \case+ [] -> finish acc []+ s@(c : cs)+ | c == '\n' && bc == 0 && pc == 0 -> finish acc s+ | c == '\\' -> case cs of+ [] -> finish (c : acc) []+ x : cs' -> go bc pc xc (x : acc) cs'+ | c == '%' -> case cs of+ '{' : cs' -> go (bc + 1) pc xc ('{' : '%' : acc) cs'+ '(' : cs' -> go bc (pc + 1) xc ('(' : '%' : acc) cs'+ '[' : cs' -> go bc pc (xc + 1) ('[' : '%' : acc) cs'+ '%' : cs' -> go bc pc xc ('%' : '%' : acc) cs'+ _ -> go bc pc xc (c : acc) cs+ | c == '{' && bc > 0 -> go (bc + 1) pc xc (c : acc) cs+ | c == '}' && bc > 0 -> go (bc - 1) pc xc (c : acc) cs+ | c == '(' && pc > 0 -> go bc (pc + 1) xc (c : acc) cs+ | c == ')' && pc > 0 -> go bc (pc - 1) xc (c : acc) cs+ | c == '[' && xc > 0 -> go bc pc (xc + 1) (c : acc) cs+ | c == ']' && xc > 0 -> go bc pc (xc - 1) (c : acc) cs+ | otherwise -> go bc pc xc (c : acc) cs++-- | evaluate an @%if@, @%ifarch@ or @%ifos@ line. a bad expression records an+-- error and gives 'Unknown'.+evalCond :: CondLine -> Eval Tri+evalCond CondLine {..} = case condKind of+ CElse -> pure Yes+ CEndif -> pure Yes+ k+ | k `elem` [CIf, CElif] -> do+ v <- expandAt 0 args+ r <- evalExpr False (\_ -> pure mempty) (itemsFromValue v)+ case r of+ Left e -> do+ message Error ("bad " <> condKeyword <> " condition: " <> e)+ pure (Unknown [Failed e])+ Right ev -> pure (boolify ev)+ | k `elem` [CIfArch, CElifArch] -> matchTarget "_target_cpu"+ | k == CIfNArch -> triNot <$> matchTarget "_target_cpu"+ | k `elem` [CIfOs, CElifOs] -> matchTarget "_target_os"+ | otherwise -> triNot <$> matchTarget "_target_os"+ where+ args = map unescapeContinuation condArgs+ unescapeContinuation = \case+ Lit t -> Lit (T.replace "\\\n" " " t)+ f -> f+ matchTarget macro = do+ target <- expandAt 0 [Macro (Braced "" macro Nothing)]+ words' <- valueWords <$> expandAt 0 args+ when (null words') (message Error (condKeyword <> " needs an argument"))+ pure $ case knownText target of+ Nothing -> Unknown (reasons target)+ Just tgt+ | any (\w -> fmap T.toLower (knownText w) == Just (T.toLower tgt)) words' -> Yes+ | any (not . isKnown) words' -> Unknown (concatMap reasons words')+ | otherwise -> No
+ src/Rozbir/Eval/Builtin.hs view
@@ -0,0 +1,365 @@+-- | rpm's builtin macros and the pure string helpers behind them, plus the+-- macros rozbir copies from rpm's @macros.in@. nothing here runs a shell or Lua.+module Rozbir.Eval.Builtin+ ( Builtin (..),+ builtinNamed,+ builtinNames,+ ArgStyle (..),+ builtinArgStyle,+ preludeMacros,+ closedPrefixes,+ closedNames,+ isAutoName,+ posixBasename,+ posixDirname,+ shrink,+ shescape,+ suffix,+ urlPath,+ luaLen,+ asciiUpper,+ asciiLower,+ luaRep,+ luaSub,+ luaReverse,+ splitQuoted,+ getopt,+ GetoptResult (..),+ )+where++import Data.ByteString qualified as BS+import Data.Char (isAsciiLower, isAsciiUpper, isDigit, toLower, toUpper)+import Data.List (find)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding (decodeUtf8Lenient, encodeUtf8)+import Text.Read (readMaybe)++-- | a builtin macro from rpm's @builtinmacros[]@+data Builtin+ = -- | @%{P:n}@, the same as @%PATCHn@+ BP+ | -- | @%{S:n}@, the same as @%SOURCEn@+ BS+ | BBasename+ | BDefine+ | BDirname+ | -- | @%dnl@, which drops the rest of the line+ BDnl+ | -- | @%dump@, which expands to nothing+ BDump+ | -- | @%{echo:...}@, which records an info message+ BEcho+ | -- | @%{error:...}@, which records an error and gives a 'Failed' hole+ BError+ | -- | @%{exists:...}@, which reads the filesystem+ BExists+ | BExpand+ | BExprFn+ | -- | @%{getconfdir}@, always @\/usr\/lib\/rpm@+ BGetconfdir+ | -- | @%{getenv:...}@, which reads the environment+ BGetenv+ | -- | @%{getncpus}@, which depends on the build host+ BGetncpus+ | BGlobal+ | -- | @%{gsub:...}@, using Lua patterns+ BGsub+ | -- | @%{len:...}@, the length in bytes+ BLen+ | -- | @%{load:...}@, which reads the filesystem+ BLoad+ | BLower+ | -- | @%{lua:...}@, which is never run+ BLua+ | BMacrobody+ | BQuote+ | BRep+ | BReverse+ | -- | @%{rpmversion}@, which depends on the build host+ BRpmversion+ | BShrink+ | BSpan+ | BSub+ | BSuffix+ | -- | @%trace@, which expands to nothing+ BTrace+ | BU2p+ | BShescape+ | -- | @%{uncompress:...}@, which expands to the uncompress command+ BUncompress+ | BUndefine+ | BUpper+ | BUrl2path+ | BVerbose+ | -- | @%{warn:...}@, which records a warning+ BWarn+ | -- | @%{xdg:...}@, which reads the environment+ BXdg+ deriving stock (Eq, Show, Enum, Bounded)++builtinTable :: [(Text, Builtin)]+builtinTable =+ [ ("P", BP),+ ("S", BS),+ ("basename", BBasename),+ ("define", BDefine),+ ("dirname", BDirname),+ ("dnl", BDnl),+ ("dump", BDump),+ ("echo", BEcho),+ ("error", BError),+ ("exists", BExists),+ ("expand", BExpand),+ ("expr", BExprFn),+ ("getconfdir", BGetconfdir),+ ("getenv", BGetenv),+ ("getncpus", BGetncpus),+ ("global", BGlobal),+ ("gsub", BGsub),+ ("len", BLen),+ ("load", BLoad),+ ("lower", BLower),+ ("lua", BLua),+ ("macrobody", BMacrobody),+ ("quote", BQuote),+ ("rep", BRep),+ ("reverse", BReverse),+ ("rpmversion", BRpmversion),+ ("shrink", BShrink),+ ("span", BSpan),+ ("sub", BSub),+ ("suffix", BSuffix),+ ("trace", BTrace),+ ("u2p", BU2p),+ ("shescape", BShescape),+ ("uncompress", BUncompress),+ ("undefine", BUndefine),+ ("upper", BUpper),+ ("url2path", BUrl2path),+ ("verbose", BVerbose),+ ("warn", BWarn),+ ("xdg", BXdg)+ ]++-- | the builtin with this name, if there is one+builtinNamed :: Text -> Maybe Builtin+builtinNamed n = snd <$> find ((== n) . fst) builtinTable++-- | every builtin name+builtinNames :: [Text]+builtinNames = map fst builtinTable++-- | how a builtin takes its arguments+data ArgStyle+ = -- | ignores arguments+ TakesNoArgs+ | -- | takes expanded arguments+ TakesArgs+ | -- | takes expanded arguments, but works without any+ TakesOptionalArgs+ | -- | reads the unexpanded text itself, like @%define@+ ParsesRaw+ deriving stock (Eq, Show)++-- | how a builtin takes its arguments+builtinArgStyle :: Builtin -> ArgStyle+builtinArgStyle = \case+ BDefine -> ParsesRaw+ BGlobal -> ParsesRaw+ BDnl -> ParsesRaw+ BLua -> ParsesRaw+ BVerbose -> ParsesRaw+ BDump -> TakesNoArgs+ BGetconfdir -> TakesNoArgs+ BRpmversion -> TakesNoArgs+ BTrace -> TakesNoArgs+ BGetncpus -> TakesOptionalArgs+ _ -> TakesArgs++-- | macros copied from rpm's @macros.in@ that every env starts with, like+-- @%with@ and @%bcond@, as name, options and body+preludeMacros :: [(Text, Maybe Text, Text)]+preludeMacros =+ [ ("nil", Nothing, "%{!?nil}"),+ ("defined", Just "", "%{expand:%%{?%{1}:1}%%{!?%{1}:0}}"),+ ("undefined", Just "", "%{expand:%%{?%{1}:0}%%{!?%{1}:1}}"),+ ("bcond_override_default", Just "", "%{expand:%%global bcond_override_default_%{1} %{2}}"),+ ("__bcond_override_default", Just "", "%{expand:%%[\"%%{?bcond_override_default_%{1}}\"||\"%%{2}\"]}"),+ ( "bcond",+ Just "",+ "%[ %{__bcond_override_default %{1} %{2}}\n ? \"%{expand:%%{!?_without_%{1}:%%global with_%{1} 1}}\"\n : \"%{expand:%%{?_with_%{1}:%%global with_%{1} 1}}\"\n]"+ ),+ ("bcond_with", Just "", "%bcond %{1} 0"),+ ("bcond_without", Just "", "%bcond %{1} 1"),+ ("with", Just "", "%{expand:%%{?with_%{1}:1}%%{!?with_%{1}:0}}"),+ ("without", Just "", "%{expand:%%{?with_%{1}:0}%%{!?with_%{1}:1}}")+ ]++-- | name prefixes only a spec can define, like @with_@ and @SOURCE@. these are+-- never left as 'Rozbir.Eval.Types.Undefined' holes.+closedPrefixes :: [Text]+closedPrefixes = ["with_", "_with_", "_without_", "bcond_override_default_", "SOURCE", "PATCH"]++-- | names only a spec can define, like @name@ and @version@+closedNames :: [Text]+closedNames =+ [ "name",+ "version",+ "release",+ "epoch",+ "summary",+ "license",+ "sourcelicense",+ "url",+ "vcs",+ "buildsystem",+ "bugurl",+ "modularitylabel",+ "upstreamreleases"+ ]++-- | whether a name is a macro argument, like @1@, @*@, @#@ or @-f@+isAutoName :: Text -> Bool+isAutoName n = case T.uncons n of+ Just ('-', _) -> True+ Just (c, _) | isDigit c -> True+ _ -> n `elem` ["*", "**", "#"]++-- | the last path component, like POSIX @basename@+posixBasename :: Text -> Text+posixBasename t+ | T.null t = "."+ | T.all (== '/') t = "/"+ | otherwise = T.takeWhileEnd (/= '/') (T.dropWhileEnd (== '/') t)++-- | everything but the last path component, like POSIX @dirname@+posixDirname :: Text -> Text+posixDirname t+ | T.null t = "."+ | T.all (== '/') t = "/"+ | otherwise =+ let trimmed = T.dropWhileEnd (== '/') t+ parent = T.dropWhileEnd (/= '/') trimmed+ in if+ | T.null parent -> "."+ | T.all (== '/') parent -> "/"+ | otherwise -> T.dropWhileEnd (== '/') parent++-- | trim whitespace and squeeze runs of it into single spaces+shrink :: Text -> Text+shrink = T.unwords . T.words++-- | single-quote each argument for a shell and join them with spaces+shescape :: [Text] -> Text+shescape = T.unwords . map (\a -> "'" <> T.replace "'" "'\\''" a <> "'")++-- | the text after the last dot, or empty if there's no dot+suffix :: Text -> Text+suffix t = case T.breakOnEnd "." t of+ ("", _) -> ""+ (_, s) -> s++-- | the path part of a URL, or the text itself if it isn't a URL+urlPath :: Text -> Text+urlPath t = case T.breakOn "://" t of+ (_, "") -> nonEmpty t+ (scheme, rest)+ | isUrlScheme scheme -> nonEmpty (T.dropWhile (/= '/') (T.drop 3 rest))+ | otherwise -> nonEmpty t+ where+ nonEmpty p = if T.null p then "/" else p+ isUrlScheme s = s `elem` ["ftp", "http", "https", "hkp", "file"]++-- | the length in UTF-8 bytes, like Lua's @string.len@+luaLen :: Text -> Text+luaLen = T.pack . show . BS.length . encodeUtf8++-- | Lua's @string.rep@ on the arguments. 'Nothing' for bad arguments.+luaRep :: [Text] -> Maybe Text+luaRep = \case+ [s, n] -> (\k -> T.replicate k s) <$> count n+ [s, n, sep] -> (\k -> T.intercalate sep (replicate k s)) <$> count n+ _ -> Nothing+ where+ count n = max 0 <$> readMaybe (T.unpack n)++-- | Lua's @string.sub@ on the arguments, counting UTF-8 bytes. 'Nothing' for+-- bad arguments.+luaSub :: [Text] -> Maybe Text+luaSub = \case+ [s] -> Just s+ [s, i] -> slice s <$> readMaybe (T.unpack i) <*> pure (-1)+ [s, i, j] -> slice s <$> readMaybe (T.unpack i) <*> readMaybe (T.unpack j)+ _ -> Nothing+ where+ slice s i j =+ let bytes = encodeUtf8 s+ len = BS.length bytes+ norm k = if k < 0 then max 0 (len + k + 1) else k+ start = max 1 (norm i)+ end = min len (norm j)+ in if start > end then "" else decodeUtf8Lenient (BS.take (end - start + 1) (BS.drop (start - 1) bytes))++-- | reverse the UTF-8 bytes, like Lua's @string.reverse@+luaReverse :: Text -> Text+luaReverse = decodeUtf8Lenient . BS.reverse . encodeUtf8++-- | split macro arguments on blanks, keeping @%{quote:...}@ text as one+-- argument+splitQuoted :: Text -> [Text]+splitQuoted = go False "" [] . T.unpack+ where+ go quoted cur acc = \case+ [] -> reverse (flush cur acc)+ '\x1f' : rest -> go (not quoted) cur acc rest+ c : rest+ | not quoted && (c == ' ' || c == '\t') -> go quoted "" (flush cur acc) rest+ | otherwise -> go quoted (c : cur) acc rest+ flush cur acc = if null cur then acc else T.pack (reverse cur) : acc++-- | the result of 'getopt'+data GetoptResult = GetoptResult+ { -- | options in order, with their values+ goOptions :: [(Char, Maybe Text)],+ -- | the remaining arguments+ goArgs :: [Text]+ }+ deriving stock (Eq, Show)++-- | parse macro arguments with a getopt option string, like rpm. options can+-- appear anywhere and @--@ ends them. an unknown option or a missing value+-- gives 'Left' with the option letter.+getopt :: Text -> [Text] -> Either Char GetoptResult+getopt spec args+ | spec == "-" = Right (GetoptResult [] args)+ | otherwise = go [] [] args+ where+ takesArg c = case T.breakOn (T.singleton c) (T.filter (/= '+') spec) of+ (_, rest) | Just (_, after) <- T.uncons rest -> Just ("::" `T.isPrefixOf` after, ":" `T.isPrefixOf` after)+ _ -> Nothing+ go opts pos = \case+ [] -> Right (GetoptResult (reverse opts) (reverse pos))+ "--" : rest -> Right (GetoptResult (reverse opts) (reverse pos <> rest))+ a : rest+ | Just flags <- T.stripPrefix "-" a, not (T.null flags) -> cluster opts pos (T.unpack flags) rest+ | otherwise -> go opts (a : pos) rest+ cluster opts pos [] rest = go opts pos rest+ cluster opts pos (c : cs) rest = case takesArg c of+ Nothing -> Left c+ Just (optional, required)+ | optional -> cluster ((c, if null cs then Nothing else Just (T.pack cs)) : opts) pos [] rest+ | required, not (null cs) -> go ((c, Just (T.pack cs)) : opts) pos rest+ | required -> case rest of+ v : rest' -> go ((c, Just v) : opts) pos rest'+ [] -> Left c+ | otherwise -> cluster ((c, Nothing) : opts) pos cs rest++-- | uppercase ASCII letters, leaving the rest alone+asciiUpper :: Text -> Text+asciiUpper = T.map (\c -> if isAsciiLower c then toUpper c else c)++-- | lowercase ASCII letters, leaving the rest alone+asciiLower :: Text -> Text+asciiLower = T.map (\c -> if isAsciiUpper c then toLower c else c)
+ src/Rozbir/Eval/LuaPattern.hs view
@@ -0,0 +1,154 @@+-- | a pure port of Lua 5.4's pattern matching, just enough for @%{gsub:...}@.+-- captures, @%b@, @%f@ and back-references aren't supported, and no Lua is ever+-- run.+module Rozbir.Eval.LuaPattern+ ( luaGsub,+ )+where++import Data.Char (isAlpha, isAlphaNum, isControl, isDigit, isHexDigit, isLower, isPunctuation, isSpace, isSymbol, isUpper)+import Data.Text (Text)+import Data.Text qualified as T+import Text.Read (readMaybe)++data Class+ = CAny+ | CChar Char+ | CPred (Char -> Bool)++data Item = Item Class Char++data Pattern = Pattern Bool [Item] Bool++parsePattern :: String -> Either Text Pattern+parsePattern s0 =+ let (anchored, s1) = case s0 of+ '^' : rest -> (True, rest)+ _ -> (False, s0)+ in go anchored [] s1+ where+ go anchored acc = \case+ [] -> Right (Pattern anchored (reverse acc) False)+ ['$'] -> Right (Pattern anchored (reverse acc) True)+ '(' : _ -> Left "Lua captures"+ ')' : _ -> Left "Lua captures"+ '%' : 'b' : _ -> Left "%b"+ '%' : 'f' : _ -> Left "%f"+ '%' : d : _ | isDigit d -> Left "Lua back-references"+ s -> do+ (cls, rest) <- single s+ case rest of+ q : rest' | q `elem` ("*+-?" :: String) -> go anchored (Item cls q : acc) rest'+ _ -> go anchored (Item cls '1' : acc) rest+ single = \case+ '.' : rest -> Right (CAny, rest)+ '%' : c : rest -> (,rest) <$> escape c+ '[' : rest -> set rest+ c : rest -> Right (CChar c, rest)+ [] -> Left "empty pattern item"+ escape c = case luaClass c of+ Just p -> Right (CPred p)+ Nothing+ | isAlphaNum c -> Left "unknown Lua class"+ | otherwise -> Right (CChar c)+ set s = do+ let (neg, s1) = case s of+ '^' : r -> (True, r)+ _ -> (False, s)+ (preds, rest) <- members [] True s1+ let p c = any ($ c) preds+ Right (CPred (if neg then not . p else p), rest)+ members acc first = \case+ [] -> Left "unterminated ["+ ']' : rest | not first -> Right (acc, rest)+ '%' : c : rest -> do+ p <- either (const (Right (== c))) Right (maybe (Left ()) Right (luaClass c))+ members (p : acc) False rest+ a : '-' : b : rest | b /= ']' -> members ((\c -> c >= a && c <= b) : acc) False rest+ c : rest -> members ((== c) : acc) False rest++luaClass :: Char -> Maybe (Char -> Bool)+luaClass c = case c of+ 'a' -> Just isAlpha+ 'd' -> Just isDigit+ 'l' -> Just isLower+ 's' -> Just isSpace+ 'u' -> Just isUpper+ 'w' -> Just isAlphaNum+ 'x' -> Just isHexDigit+ 'p' -> Just (\x -> isPunctuation x || isSymbol x)+ 'c' -> Just isControl+ _+ | isUpper c, Just p <- luaClass (toLowerAscii c) -> Just (not . p)+ | otherwise -> Nothing+ where+ toLowerAscii x = toEnum (fromEnum x + 32)++matchesClass :: Class -> Char -> Bool+matchesClass cls c = case cls of+ CAny -> True+ CChar x -> x == c+ CPred p -> p c++matchHere :: [Item] -> Bool -> String -> Maybe String+matchHere items anchoredEnd s = case items of+ [] -> if anchoredEnd && not (null s) then Nothing else Just s+ Item cls q : rest -> case q of+ '1' -> case s of+ c : cs | matchesClass cls c -> matchHere rest anchoredEnd cs+ _ -> Nothing+ '?' -> case s of+ c : cs | matchesClass cls c, Just r <- matchHere rest anchoredEnd cs -> Just r+ _ -> matchHere rest anchoredEnd s+ '-' -> lazy s+ _ ->+ let n = length (takeWhile (matchesClass cls) s)+ minimum' = if q == '+' then 1 else 0+ in firstJust [matchHere rest anchoredEnd (drop k s) | k <- [n, n - 1 .. minimum']]+ where+ lazy str = case matchHere rest anchoredEnd str of+ Just r -> Just r+ Nothing -> case str of+ c : cs | matchesClass cls c -> lazy cs+ _ -> Nothing+ where+ firstJust = \case+ [] -> Nothing+ Just x : _ -> Just x+ Nothing : xs -> firstJust xs++-- | Lua's @string.gsub@ on @[string, pattern, replacement]@ with an optional+-- count, returning the new string. 'Left' names the unsupported feature or bad+-- argument.+luaGsub :: [Text] -> Either Text Text+luaGsub = \case+ [s, p, r] -> run s p r Nothing+ [s, p, r, n] -> maybe (Left "bad count") (run s p r . Just) (readMaybe (T.unpack n))+ _ -> Left "gsub takes 3 or 4 arguments"+ where+ run s p r limit = do+ Pattern anchored items anchoredEnd <- parsePattern (T.unpack p)+ repl <- replacement (T.unpack r)+ Right (T.pack (loop anchored items anchoredEnd repl limit (0 :: Int) Nothing (T.unpack s)))+ loop anchored items anchoredEnd repl limit n lastEnd src+ | maybe False (n >=) limit = src+ | otherwise = case matchHere items anchoredEnd src of+ Just rest+ | Just (length rest) /= lastEnd ->+ repl (take (length src - length rest) src)+ <> if anchored then rest else loop anchored items anchoredEnd repl limit (n + 1) (Just (length rest)) rest+ _ -> case src of+ c : cs+ | anchored -> src+ | otherwise -> c : loop anchored items anchoredEnd repl limit n lastEnd cs+ [] -> []+ replacement = go []+ where+ go acc = \case+ [] -> Right (\m -> concatMap ($ m) (reverse acc))+ '%' : c : rest+ | c == '0' || c == '1' -> go (id : acc) rest+ | isDigit c -> Left "Lua captures"+ | otherwise -> go (const [c] : acc) rest+ ['%'] -> Left "trailing %"+ c : rest -> go (const [c] : acc) rest
+ src/Rozbir/Eval/Shell.hs view
@@ -0,0 +1,578 @@+-- | a pure interpreter for the small subset of sh that specs use in @%(...)@:+-- variable assignments, @echo@, simple @printf@, @${v:o:l}@-style expansions,+-- here-strings, and pipes into @sed@ substitutions, @tr@ and @cut@. it never+-- runs a shell. anything outside the subset is rejected so the caller can+-- leave it opaque.+module Rozbir.Eval.Shell+ ( runShell,+ Unsupported,+ sedScript,+ trText,+ Regex,+ parseRegex,+ matchLongest,+ )+where++import Control.Monad (foldM, unless, when)+import Data.Char (isAlpha, isAlphaNum, isDigit, isLower, isSpace, isUpper)+import Data.List qualified as L+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Text.Read (readMaybe)++-- | why a script was rejected, such as the command or syntax it doesn't support+type Unsupported = Text++data Part+ = PLit !Text Bool+ | PVar !Text !Expansion++data Expansion+ = Plain+ | Substring !Int !(Maybe Int)+ | DropPrefix !Bool !Text+ | DropSuffix !Bool !Text+ | Replace !Bool !Text !Text+ | Length++type Word' = [Part]++data Token = TWord Word' | TPipe | TSep | THere++-- | run a script and return its output with trailing newlines trimmed, like+-- @%(...)@. 'Left' names the first unsupported feature, including reading a+-- variable the script didn't set.+runShell :: Text -> Either Unsupported Text+runShell src = do+ toks <- tokenize (T.unpack src)+ stmts <- statements toks+ (_, out) <- foldM step (Map.empty, "") stmts+ pure (T.dropWhileEnd (\c -> c == '\n' || c == '\r') out)+ where+ step (vars, out) = \case+ Left (name, w) -> do+ v <- expandJoined vars w+ pure (Map.insert name v vars, out)+ Right pipeline -> do+ r <- runPipeline vars pipeline+ pure (vars, out <> r)++type Pipeline = ([[Word']], Maybe Word')++statements :: [Token] -> Either Unsupported [Either (Text, Word') Pipeline]+statements toks = mapM statement (filter (not . null) (splitOn isSep toks))+ where+ isSep = \case+ TSep -> True+ _ -> False+ statement ts = case ts of+ [TWord w] | Just a <- assignment w -> Right (Left a)+ _ -> do+ parsed <- mapM command (splitOn isPipe ts)+ let cmds = map fst parsed+ heres = map snd parsed+ when (any null cmds) (Left "empty command")+ when (any (/= Nothing) (map (fmap (const ())) (drop 1 heres))) (Left "here-strings after a pipe")+ case cmds of+ (w : _) : _ | Just _ <- assignment w -> Left "environment prefixes"+ _ -> pure ()+ pure (Right (cmds, case heres of h : _ -> h; [] -> Nothing))+ isPipe = \case+ TPipe -> True+ _ -> False+ command ts = case break isHere ts of+ (ws, []) -> (,Nothing) <$> mapM word' ws+ (ws, [THere, TWord h]) -> (,Just h) <$> mapM word' ws+ _ -> Left "unsupported here-string"+ isHere = \case+ THere -> True+ _ -> False+ word' = \case+ TWord w -> Right w+ _ -> Left "unexpected operator"++assignment :: Word' -> Maybe (Text, Word')+assignment = \case+ PLit t False : rest+ | (name, eq) <- T.break (== '=') t,+ Just value <- T.stripPrefix "=" eq,+ validName name ->+ Just (name, [PLit value False | not (T.null value)] <> rest)+ _ -> Nothing+ where+ validName n = case T.uncons n of+ Just (c, more) -> (isAlpha c || c == '_') && T.all (\x -> isAlphaNum x || x == '_') more+ Nothing -> False++splitOn :: (a -> Bool) -> [a] -> [[a]]+splitOn p xs = case break p xs of+ (chunk, []) -> [chunk]+ (chunk, _ : rest) -> chunk : splitOn p rest++tokenize :: String -> Either Unsupported [Token]+tokenize = go []+ where+ go acc = \case+ [] -> Right (reverse acc)+ c : cs+ | c == '\n' || c == ';' -> go (TSep : acc) cs+ | c == '|' -> case cs of+ '|' : _ -> Left "||"+ _ -> go (TPipe : acc) cs+ | c == ' ' || c == '\t' -> go acc cs+ | c == '#' -> go acc (dropWhile (/= '\n') cs)+ | c == '<', '<' : '<' : rest <- cs -> go (THere : acc) rest+ | c `elem` ("&<>()`" :: String) -> Left (T.pack ['\'', c, '\''])+ | otherwise -> do+ (w, rest) <- word [] (c : cs)+ go (TWord (mergeParts w) : acc) rest++ word parts = \case+ [] -> Right (reverse parts, [])+ s@(c : cs)+ | c `elem` (" \t\n;|" :: String) -> Right (reverse parts, s)+ | c `elem` ("&<>()`" :: String) -> Left (T.pack ['\'', c, '\''])+ | c == '\'' -> case break (== '\'') cs of+ (inner, _ : rest) -> word (PLit (T.pack inner) True : parts) rest+ _ -> Left "unterminated quote"+ | c == '"' -> do+ (inner, rest) <- doubleQuoted [] cs+ word (reverse inner <> parts) rest+ | c == '\\' -> case cs of+ '\n' : rest -> word parts rest+ x : rest -> word (PLit (T.singleton x) True : parts) rest+ [] -> Left "trailing backslash"+ | c == '$' -> do+ (v, rest) <- dollar cs+ word (v : parts) rest+ | c `elem` ("*?[{}" :: String) -> Left "globs and braces"+ | c == '~' && null parts -> Left "tilde expansion"+ | otherwise -> word (PLit (T.singleton c) False : parts) cs++ doubleQuoted parts = \case+ [] -> Left "unterminated quote"+ '"' : rest -> Right (reverse parts, rest)+ '\\' : x : rest+ | x `elem` ("$`\"\\" :: String) -> doubleQuoted (PLit (T.singleton x) True : parts) rest+ | x == '\n' -> doubleQuoted parts rest+ | otherwise -> doubleQuoted (PLit (T.pack ['\\', x]) True : parts) rest+ '$' : rest -> do+ (v, rest') <- dollar rest+ doubleQuoted (quoteVar v : parts) rest'+ '`' : _ -> Left "command substitution"+ c : rest -> doubleQuoted (PLit (T.singleton c) True : parts) rest++ quoteVar = \case+ PVar n e -> PVar ("\"" <> n) e+ p -> p++ dollar = \case+ '{' : rest -> case break (== '}') rest of+ (inner, _ : after) -> do+ e <- braced inner+ Right (e, after)+ _ -> Left "unterminated ${"+ '(' : _ -> Left "command substitution"+ s@(c : _)+ | isAlpha c || c == '_' ->+ let (name, rest) = span (\x -> isAlphaNum x || x == '_') s+ in Right (PVar (T.pack name) Plain, rest)+ | isDigit c || c `elem` ("@*#?$!-" :: String) -> Left "special parameters"+ rest -> Right (PLit "$" False, rest)++ braced inner = case inner of+ '#' : name | validVar name -> Right (PVar (T.pack name) Length)+ _ ->+ let (name, op) = span (\x -> isAlphaNum x || x == '_') inner+ in if not (validVar name)+ then Left "unsupported ${...}"+ else PVar (T.pack name) <$> operator op+ validVar n = case n of+ c : more -> (isAlpha c || c == '_') && all (\x -> isAlphaNum x || x == '_') more+ [] -> False+ operator = \case+ [] -> Right Plain+ ':' : spec+ | (offT, rest) <- break (== ':') spec ->+ case (readMaybe offT, rest) of+ (Just o, []) | o >= 0 -> Right (Substring o Nothing)+ (Just o, ':' : lenT) | Just l <- readMaybe lenT, o >= 0, l >= 0 -> Right (Substring o (Just l))+ _ -> Left "unsupported substring"+ '#' : '#' : pat -> literal pat (DropPrefix True)+ '#' : pat -> literal pat (DropPrefix False)+ '%' : '%' : pat -> literal pat (DropSuffix True)+ '%' : pat -> literal pat (DropSuffix False)+ '/' : '/' : spec -> replace True spec+ '/' : spec -> replace False spec+ _ -> Left "unsupported ${...}"+ literal pat f+ | any (`elem` ("*?[\\$'\"" :: String)) pat = Left "glob patterns"+ | otherwise = Right (f (T.pack pat))+ replace allOcc spec = case break (== '/') spec of+ (pat, rest)+ | any (`elem` ("*?[\\$'\"#%" :: String)) pat || null pat -> Left "glob patterns"+ | otherwise ->+ let rep = drop 1 rest+ in if any (`elem` ("\\$'\"" :: String)) rep then Left "unsupported replacement" else Right (Replace allOcc (T.pack pat) (T.pack rep))++mergeParts :: [Part] -> [Part]+mergeParts = \case+ PLit a qa : PLit b qb : rest | qa == qb -> mergeParts (PLit (a <> b) qa : rest)+ x : rest -> x : mergeParts rest+ [] -> []++expandVar :: Map Text Text -> Text -> Expansion -> Either Unsupported Text+expandVar vars name0 e = do+ let name = fromMaybe name0 (T.stripPrefix "\"" name0)+ v <- maybe (Left ("$" <> name <> " comes from the environment")) Right (Map.lookup name vars)+ pure $ case e of+ Plain -> v+ Length -> T.pack (show (T.length v))+ Substring o l -> maybe id T.take l (T.drop o v)+ DropPrefix _ p -> fromMaybe v (T.stripPrefix p v)+ DropSuffix _ p -> fromMaybe v (T.stripSuffix p v)+ Replace True p r -> T.replace p r v+ Replace False p r -> case T.breakOn p v of+ (pre, post) | not (T.null post) -> pre <> r <> T.drop (T.length p) post+ _ -> v++expandJoined :: Map Text Text -> Word' -> Either Unsupported Text+expandJoined vars parts = T.concat <$> mapM one parts+ where+ one = \case+ PLit t _ -> Right t+ PVar n e -> expandVar vars n e++expandFields :: Map Text Text -> Word' -> Either Unsupported [Text]+expandFields vars parts = do+ pieces <- mapM one parts+ let fields = L.foldl' glue [] pieces+ pure (if any quotedPart parts then fields else filter (not . T.null) fields)+ where+ one = \case+ PLit t _ -> Right [Left t]+ PVar n e+ | "\"" `T.isPrefixOf` n -> (\v -> [Left v]) <$> expandVar vars n e+ | otherwise -> do+ v <- expandVar vars n e+ when (T.any (`elem` ("*?[" :: String)) v) (Left "glob characters in an expansion")+ Right [Right v]+ quotedPart = \case+ PLit _ True -> True+ PVar n _ -> "\"" `T.isPrefixOf` n+ _ -> False+ glue acc = \case+ [] -> acc+ Left t : more -> glue (appendLast acc t) more+ Right v : more ->+ let ws = T.split isIfs v+ in case ws of+ [] -> glue acc more+ first : others -> glue (appendSplit (appendLast acc first) others) more+ isIfs c = c == ' ' || c == '\t' || c == '\n'+ appendLast acc t = case acc of+ [] -> [t]+ _ -> init acc <> [last acc <> t]+ appendSplit acc others = acc <> others++runPipeline :: Map Text Text -> Pipeline -> Either Unsupported Text+runPipeline vars (cmds, here) = do+ argvs <- mapM (fmap concat . mapM (expandFields vars)) cmds+ start <- traverse (fmap (<> "\n") . expandJoined vars) here+ foldM (\input (i, argv) -> runCommand (i == (0 :: Int) && start == Nothing) input argv) (fromMaybe "" start) (zip [0 ..] argvs)++runCommand :: Bool -> Text -> [Text] -> Either Unsupported Text+runCommand first input = \case+ "echo" : args -> echo args+ "printf" : fmt : args -> printf fmt args+ "sed" : args -> needsInput >> sedArgs args >>= \(ere, scripts) -> sedRun ere scripts input+ "tr" : args -> needsInput >> trArgs args input+ "cut" : args -> needsInput >> cutArgs args input+ cmd : _ -> Left (cmd <> " isn't supported")+ [] -> Left "empty command"+ where+ needsInput = when first (Left "reads stdin")+ echo args = case args of+ "-n" : rest -> Right (T.unwords rest)+ "-E" : rest -> echo rest+ a : _ | "-" `T.isPrefixOf` a, T.length a > 1, T.all (`elem` ['n', 'e', 'E']) (T.drop 1 a) -> Left "echo options"+ _ -> Right (T.unwords args <> "\n")+ printf fmt args+ | fmt == "%s" = Right (T.concat args)+ | fmt == "%s\\n" = Right (T.concat (map (<> "\n") args))+ | not (T.any (`elem` ['%', '\\']) fmt) && null args = Right fmt+ | otherwise = Left "printf formats"++sedArgs :: [Text] -> Either Unsupported (Bool, [Text])+sedArgs = go False []+ where+ go ere scripts = \case+ [] -> if null scripts then Left "sed without a script" else Right (ere, reverse scripts)+ "-E" : rest -> go True scripts rest+ "-r" : rest -> go True scripts rest+ "-e" : s : rest -> go ere (s : scripts) rest+ a : rest+ | "-" `T.isPrefixOf` a -> Left ("sed " <> a)+ | null scripts -> go ere [a] rest+ | otherwise -> Left "sed with files"++sedRun :: Bool -> [Text] -> Text -> Either Unsupported Text+sedRun ere scripts input = do+ cmds <- concat <$> mapM (sedScript ere) scripts+ let ls = T.splitOn "\n" input+ (body, trailing) = if not (null ls) && T.null (last ls) then (init ls, True) else (ls, False)+ out <- mapM (\l -> foldM (\acc c -> c acc) l cmds) body+ pure (T.intercalate "\n" out <> if trailing then "\n" else "")++-- | parse a sed script into one function per command, each applied to a line.+-- only @s@ commands with an optional @g@ flag are supported. 'True' means+-- extended regexes, like @sed -E@.+sedScript :: Bool -> Text -> Either Unsupported [Text -> Either Unsupported Text]+sedScript ere = go . T.unpack+ where+ go = \case+ [] -> Right []+ c : rest | c == ';' || isSpace c -> go rest+ 's' : d : rest | d /= '\\' && d /= '\n' -> do+ (pat, r1) <- part d rest+ (rep, r2) <- part d r1+ let (flags, r3) = span (\x -> x /= ';' && x /= '\n' && x /= '}' && not (isSpace x)) r2+ unless (all (== 'g') flags) (Left ("sed flags " <> T.pack flags))+ re <- parseRegex ere (T.pack (unescapeDelim d pat))+ repl <- replacement (unescapeDelim d rep)+ more <- go r3+ pure (substitute re repl (not (null flags)) : more)+ _ -> Left "only s commands are supported in sed"+ part d = scan []+ where+ scan acc = \case+ [] -> Left "unterminated s command"+ '\\' : x : rest -> scan (x : '\\' : acc) rest+ x : rest+ | x == d -> Right (reverse acc, rest)+ | otherwise -> scan (x : acc) rest+ unescapeDelim d = \case+ '\\' : x : rest | x == d && d /= '&' -> x : unescapeDelim d rest+ '\\' : x : rest -> '\\' : x : unescapeDelim d rest+ x : rest -> x : unescapeDelim d rest+ [] -> []++data ReplPart = RLit Text | RMatch++replacement :: String -> Either Unsupported [ReplPart]+replacement = go+ where+ go = \case+ [] -> Right []+ '&' : rest -> (RMatch :) <$> go rest+ '\\' : x : rest+ | isDigit x -> Left "back-references"+ | x == 'n' -> (RLit "\n" :) <$> go rest+ | x == 't' -> (RLit "\t" :) <$> go rest+ | otherwise -> (RLit (T.singleton x) :) <$> go rest+ x : rest -> (RLit (T.singleton x) :) <$> go rest++substitute :: Regex -> [ReplPart] -> Bool -> Text -> Either Unsupported Text+substitute re repl global line = Right (T.pack (go True (T.unpack line)))+ where+ go atStart s = case findMatch re atStart s of+ Nothing -> s+ Just (pre, matched, post) ->+ let replaced = pre <> concatMap (\case RLit t -> T.unpack t; RMatch -> matched) repl+ in if not global+ then replaced <> post+ else+ if null matched+ then case post of+ [] -> replaced+ x : xs -> replaced <> [x] <> go False xs+ else replaced <> go False post++data Atom+ = AChar Char+ | AAny+ | ASet Bool [Char -> Bool]++data Piece = Piece Atom Int (Maybe Int)++-- | a parsed sed regex. only single characters, @.@, bracket expressions,+-- quantifiers and anchors are supported, without groups, alternation,+-- intervals or back-references.+data Regex = Regex Bool [Piece] Bool++-- | parse a basic regex, or an extended one when the flag is 'True'+parseRegex :: Bool -> Text -> Either Unsupported Regex+parseRegex ere t0 = do+ let s0 = T.unpack t0+ (anchoredStart, s1) = case s0 of+ '^' : rest -> (True, rest)+ _ -> (False, s0)+ (pieces, anchoredEnd) <- go [] s1+ pure (Regex anchoredStart (reverse pieces) anchoredEnd)+ where+ go acc = \case+ [] -> Right (acc, False)+ ['$'] -> Right (acc, True)+ '\\' : x : rest+ | not ere && x == '+' -> quantify acc 1 Nothing rest+ | not ere && x == '?' -> quantify acc 0 (Just 1) rest+ | x `elem` ("(){}|<>bBwWsS'`" :: String) || isDigit x -> Left "regex groups, intervals and classes"+ | x == 'n' -> go (Piece (AChar '\n') 1 (Just 1) : acc) rest+ | x == 't' -> go (Piece (AChar '\t') 1 (Just 1) : acc) rest+ | otherwise -> go (Piece (AChar x) 1 (Just 1) : acc) rest+ '*' : rest+ | null acc -> go (Piece (AChar '*') 1 (Just 1) : acc) rest+ | otherwise -> quantify acc 0 Nothing rest+ '+' : rest | ere -> if null acc then Left "dangling +" else quantify acc 1 Nothing rest+ '?' : rest | ere -> if null acc then Left "dangling ?" else quantify acc 0 (Just 1) rest+ c : _ | ere && c `elem` ("(){}|" :: String) -> Left "regex groups and alternation"+ '.' : rest -> go (Piece AAny 1 (Just 1) : acc) rest+ '[' : rest -> do+ (atom, rest') <- bracket rest+ go (Piece atom 1 (Just 1) : acc) rest'+ '^' : _ -> Left "^ in the middle"+ '$' : rest -> go (Piece (AChar '$') 1 (Just 1) : acc) rest+ c : rest -> go (Piece (AChar c) 1 (Just 1) : acc) rest+ quantify acc lo hi rest = case acc of+ Piece a 1 (Just 1) : more -> go (Piece a lo hi : more) rest+ []+ | not ere, lo == 1 -> go [Piece (AChar '+') 1 (Just 1)] rest+ | not ere -> go [Piece (AChar '?') 1 (Just 1)] rest+ _ -> Left "stacked quantifiers"+ bracket s = do+ let (negated, s1) = case s of+ '^' : r -> (True, r)+ _ -> (False, s)+ (firstLit, s2) = case s1 of+ ']' : r -> ([(== ']')], r)+ _ -> ([], s1)+ (preds, rest) <- members firstLit s2+ Right (ASet negated preds, rest)+ members acc = \case+ [] -> Left "unterminated ["+ ']' : rest -> Right (acc, rest)+ '[' : ':' : rest -> case break (== ':') rest of+ (cls, ':' : ']' : after) -> do+ p <- charClass cls+ members (p : acc) after+ _ -> Left "unsupported bracket expression"+ '[' : x : _ | x == '=' || x == '.' -> Left "unsupported bracket expression"+ a : '-' : b : rest | b /= ']' -> members ((\c -> c >= a && c <= b) : acc) rest+ c : rest -> members ((== c) : acc) rest+ charClass = \case+ "alpha" -> Right isAlpha+ "digit" -> Right isDigit+ "alnum" -> Right isAlphaNum+ "space" -> Right isSpace+ "upper" -> Right isUpper+ "lower" -> Right isLower+ "punct" -> Right (\c -> c `elem` ("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" :: String))+ other -> Left ("[:" <> T.pack other <> ":]")++atomMatches :: Atom -> Char -> Bool+atomMatches a c = case a of+ AChar x -> x == c+ AAny -> c /= '\n'+ ASet neg ps -> (any ($ c) ps) /= neg++matchEnds :: [Piece] -> Bool -> String -> [Int]+matchEnds pieces anchoredEnd = go pieces 0+ where+ go [] n s = [n | not anchoredEnd || null s]+ go (Piece a lo hi : rest) n s =+ let available = length (takeWhile (atomMatches a) (maybe id take hi s))+ counts = [k | k <- [available, available - 1 .. lo], k >= lo]+ in concat [go rest (n + k) (drop k s) | k <- counts]++-- | the length of the longest match at the start of the string, or 'Nothing'.+-- this ignores a @^@ anchor.+matchLongest :: Regex -> String -> Maybe Int+matchLongest (Regex _ pieces anchoredEnd) s = case matchEnds pieces anchoredEnd s of+ [] -> Nothing+ ends -> Just (maximum ends)++findMatch :: Regex -> Bool -> String -> Maybe (String, String, String)+findMatch re@(Regex anchoredStart _ _) atStart = go []+ where+ go pre s+ | anchoredStart && not (atStart && null pre) = Nothing+ | Just n <- matchLongest re s = Just (reverse pre, take n s, drop n s)+ | otherwise = case s of+ [] -> Nothing+ x : xs -> go (x : pre) xs++trArgs :: [Text] -> Text -> Either Unsupported Text+trArgs args input = case args of+ ["-d", set] -> do+ del <- trSet set+ Right (T.filter (`notElem` del) input)+ [a, b] | not ("-" `T.isPrefixOf` a) -> trText a b input+ _ -> Left "tr options"++-- | @tr a b@ on some input. like GNU tr, a short second set repeats its last+-- character.+trText :: Text -> Text -> Text -> Either Unsupported Text+trText a b input = do+ from <- trSet a+ to <- trSet b+ when (null to && not (null from)) (Left "tr with an empty second set")+ let padded = to <> repeat (last to)+ table = Map.fromList (reverse (zip from padded))+ Right (T.map (\c -> Map.findWithDefault c c table) input)++trSet :: Text -> Either Unsupported [Char]+trSet = go . T.unpack+ where+ go = \case+ [] -> Right []+ '[' : ':' : rest | (cls, ':' : ']' : after) <- break (== ':') rest -> do+ cs <- case cls of+ "digit" -> Right ['0' .. '9']+ "lower" -> Right ['a' .. 'z']+ "upper" -> Right ['A' .. 'Z']+ "space" -> Right " \t\n\r\f\v"+ _ -> Left "tr classes"+ (cs <>) <$> go after+ '\\' : x : rest -> (escape x :) <$> go rest+ a : '-' : b : rest | b /= '\\' -> ([a .. b] <>) <$> go rest+ c : rest -> (c :) <$> go rest+ escape = \case+ 'n' -> '\n'+ 't' -> '\t'+ 'r' -> '\r'+ x -> x++cutArgs :: [Text] -> Text -> Either Unsupported Text+cutArgs args input = do+ (delim, list, fields) <- parse' args Nothing Nothing False+ ranges <- mapM range (T.splitOn "," list)+ let ls = T.splitOn "\n" input+ (body, trailing) = if not (null ls) && T.null (last ls) then (init ls, True) else (ls, False)+ pick n = any (\(lo, hi) -> n >= lo && maybe True (n <=) hi) ranges+ d = fromMaybe "\t" delim+ perLine l+ | not fields = T.pack [c | (i, c) <- zip [1 :: Int ..] (T.unpack l), pick i]+ | not (T.isInfixOf d l) = l+ | otherwise = T.intercalate d [f | (i, f) <- zip [1 ..] (T.splitOn d l), pick i]+ Right (T.intercalate "\n" (map perLine body) <> if trailing then "\n" else "")+ where+ parse' as delim list fields = case as of+ [] -> maybe (Left "cut without a list") (\l -> Right (delim, l, fields)) list+ "-d" : d : rest | T.length d == 1 -> parse' rest (Just d) list fields+ "-c" : l : rest -> parse' rest delim (Just l) False+ "-f" : l : rest -> parse' rest delim (Just l) True+ a : rest+ | Just d <- T.stripPrefix "-d" a, T.length d == 1 -> parse' rest (Just d) list fields+ | Just l <- T.stripPrefix "-c" a, not (T.null l) -> parse' rest delim (Just l) False+ | Just l <- T.stripPrefix "-f" a, not (T.null l) -> parse' rest delim (Just l) True+ | otherwise -> Left "cut options"+ range r = case T.splitOn "-" r of+ [n] | Just k <- readMaybe (T.unpack n) -> Right (k, Just k)+ ["", m] | Just k <- readMaybe (T.unpack m) -> Right (1, Just k)+ [n, ""] | Just k <- readMaybe (T.unpack n) -> Right (k, Nothing)+ [n, m] | Just a <- readMaybe (T.unpack n), Just b <- readMaybe (T.unpack m) -> Right (a, Just b)+ _ -> Left "cut ranges"
+ src/Rozbir/Eval/Types.hs view
@@ -0,0 +1,342 @@+-- | values, environments and targets for partial evaluation. a t'Value' is known+-- text mixed with 'Opaque' holes for parts that can't be expanded without+-- running something, and conditions are three-valued ('Tri').+module Rozbir.Eval.Types+ ( Reason (..),+ describeReason,+ Piece (..),+ Value (..),+ known,+ opaque,+ opaqueAt,+ knownText,+ isKnown,+ reasons,+ showValue,+ stripQuoteMarks,+ valueNull,+ mapKnown,+ valueLines,+ valueWords,+ Tri (..),+ triNot,+ triAnd,+ triOr,+ MacroDef (..),+ MacroBody (..),+ Origin (..),+ Env (..),+ Target (..),+ unknownTarget,+ Severity (..),+ EvalMessage (..),+ )+where++import Control.DeepSeq (NFData)+import Data.Aeson (ToJSON (..), object, (.=))+import Data.Char (isSpace)+import Data.Map.Strict (Map)+import Data.Text (Text)+import Data.Text qualified as T+import GHC.Generics (Generic)+import Rozbir.Syntax (Name, Span)++-- | why part of a value couldn't be expanded+data Reason+ = -- | a @%(...)@ the pure shell subset can't handle+ RunsShell+ | -- | Lua code, which is never run+ RunsLua+ | -- | reads environment variables+ ReadsEnv+ | -- | reads the filesystem+ ReadsFilesystem+ | -- | depends on the build host, like the buildroot+ HostDependent Text+ | -- | not defined here, but system macros might define it+ Undefined Name+ | -- | defined differently depending on a condition that can't be decided+ Ambiguous Name+ | -- | nested too deeply or ran out of fuel, usually recursion+ DepthLimit+ | -- | something rozbir doesn't model+ Unsupported Text+ | -- | an error, like a bad expression or @%{error:...}@+ Failed Text+ deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++-- | a short human-readable explanation+describeReason :: Reason -> Text+describeReason = \case+ RunsShell -> "runs a shell command"+ RunsLua -> "runs Lua"+ ReadsEnv -> "reads the environment"+ ReadsFilesystem -> "reads the filesystem"+ HostDependent what -> "depends on the build host (" <> what <> ")"+ Undefined n -> "%" <> n <> " isn't defined here"+ Ambiguous n -> "%" <> n <> " depends on a condition that can't be decided"+ DepthLimit -> "expands too deeply, probably recursion"+ Unsupported what -> what <> " isn't supported"+ Failed why -> why++instance ToJSON Reason where+ toJSON r = toJSON (describeReason r)++-- | one part of a t'Value'+data Piece+ = -- | fully expanded text+ Known !Text+ | -- | a hole, with its source location when known+ Opaque !Reason !(Maybe Span)+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | an expansion result. '<>' joins adjacent known text and drops empty pieces.+newtype Value = Value [Piece]+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++instance Semigroup Value where+ Value a <> Value b = Value (normalize (a <> b))++instance Monoid Value where+ mempty = Value []++instance ToJSON Value where+ toJSON v = case knownText v of+ Just t -> object ["known" .= True, "text" .= t]+ Nothing -> object ["known" .= False, "text" .= showValue v, "reasons" .= reasons v]++normalize :: [Piece] -> [Piece]+normalize = \case+ Known "" : rest -> normalize rest+ Known a : Known b : rest -> normalize (Known (a <> b) : rest)+ x : rest -> x : normalize rest+ [] -> []++-- | a fully known value+known :: Text -> Value+known t = Value (normalize [Known t])++-- | a single hole without a location+opaque :: Reason -> Value+opaque r = Value [Opaque r Nothing]++-- | a single hole at a source location+opaqueAt :: Reason -> Span -> Value+opaqueAt r s = Value [Opaque r (Just s)]++-- | the text, if there are no holes+knownText :: Value -> Maybe Text+knownText (Value ps) = T.concat <$> traverse (\case Known t -> Just t; Opaque {} -> Nothing) ps++-- | whether there are no holes+isKnown :: Value -> Bool+isKnown (Value ps) = all (\case Known _ -> True; _ -> False) ps++-- | the reason for each hole, in order+reasons :: Value -> [Reason]+reasons (Value ps) = [r | Opaque r _ <- ps]++-- | whether the value is empty+valueNull :: Value -> Bool+valueNull (Value ps) = null ps++-- | render for people, with holes as short tags like @‹%version›@+showValue :: Value -> Text+showValue (Value ps) = T.concat (map piece ps)+ where+ piece = \case+ Known t -> t+ Opaque r _ -> "\x2039" <> short r <> "\x203a"+ short = \case+ Undefined n -> "%" <> n+ Ambiguous n -> "%" <> n <> "?"+ RunsShell -> "%(...)"+ RunsLua -> "lua"+ ReadsEnv -> "env"+ ReadsFilesystem -> "fs"+ HostDependent w -> w+ DepthLimit -> "recursion"+ Unsupported w -> w+ Failed _ -> "error"++-- | remove the markers @%{quote:...}@ adds to keep text as one argument+stripQuoteMarks :: Value -> Value+stripQuoteMarks = mapKnown (T.filter (/= '\x1f'))++-- | apply a function to the known text, leaving holes alone+mapKnown :: (Text -> Text) -> Value -> Value+mapKnown f (Value ps) = Value (normalize (map (\case Known t -> Known (f t); o -> o) ps))++-- | split on newlines. empty lines are kept.+valueLines :: Value -> [Value]+valueLines (Value ps) = map (Value . normalize) (go [] ps)+ where+ go acc = \case+ [] -> [reverse acc]+ Known t : rest -> case T.splitOn "\n" t of+ [single] -> go (Known single : acc) rest+ first : more ->+ let (middle, lastOne) = (init more, last more)+ in reverse (Known first : acc) : map (pure . Known) middle <> go [Known lastOne] rest+ [] -> go acc rest+ o : rest -> go (o : acc) rest++-- | split on whitespace, dropping empty words. a hole stays with the word it+-- touches.+valueWords :: Value -> [Value]+valueWords (Value ps) = filter (not . valueNull) (map (Value . normalize) (go [] ps))+ where+ go acc = \case+ [] -> [reverse acc]+ Known t : rest -> case T.split isSpace t of+ [single] -> go (Known single : acc) rest+ first : more ->+ let (middle, lastOne) = (init more, last more)+ in reverse (Known first : acc) : map (pure . Known) middle <> go [Known lastOne] rest+ [] -> go acc rest+ o : rest -> go (o : acc) rest++-- | a yes, no or unknown answer. 'Unknown' says why it couldn't be decided.+data Tri+ = Yes+ | No+ | -- | can't be decided, with the reasons why+ Unknown [Reason]+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | negate. 'Unknown' stays 'Unknown'.+triNot :: Tri -> Tri+triNot = \case+ Yes -> No+ No -> Yes+ u -> u++-- | and. 'No' takes precedence over 'Unknown'.+triAnd :: Tri -> Tri -> Tri+triAnd No _ = No+triAnd _ No = No+triAnd Yes b = b+triAnd a Yes = a+triAnd (Unknown a) (Unknown b) = Unknown (a <> b)++-- | or. 'Yes' takes precedence over 'Unknown'.+triOr :: Tri -> Tri -> Tri+triOr Yes _ = Yes+triOr _ Yes = Yes+triOr No b = b+triOr a No = a+triOr (Unknown a) (Unknown b) = Unknown (a <> b)++-- | what a macro expands to+data MacroBody+ = -- | text expanded each time it's used, like @%define@+ BodyRaw !Text+ | -- | an already expanded value, like @%global@. rpm still expands it again on use.+ BodyValue !Value+ | -- | text used as is, without expanding+ BodyLiteral !Text+ | -- | defined, but the body can't be known+ BodyOpaque !Reason+ | -- | might or might not be defined+ BodyMaybe !Reason+ | -- | explicitly undefined+ BodyUndefined+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | where a definition came from+data Origin+ = -- | a @%define@ or @%global@ in the spec+ OriginSpec !Span+ | -- | a macro file and line+ OriginFile !FilePath !Int+ | -- | the t'Target'+ OriginTarget+ | -- | a tag, like @Version:@ defining @%version@+ OriginTag !Span+ | -- | the evaluator, like macro arguments+ OriginAuto+ | -- | rozbir's copy of rpm's built-in macros+ OriginPrelude+ | -- | merged from branches that couldn't be decided+ OriginMerged+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | one macro definition. equality ignores the origin.+data MacroDef = MacroDef+ { -- | getopt options for a macro that takes arguments+ macroOpts :: !(Maybe Text),+ macroBody :: !MacroBody,+ macroOrigin :: !Origin,+ -- | the call depth it was defined at. 0 is global, others go away when that call returns.+ macroLevel :: !Int,+ -- | a macro argument like @%1@ or @%*@, hidden from nested calls+ macroAuto :: !Bool+ }+ deriving stock (Show, Generic)+ deriving anyclass (NFData)++instance Eq MacroDef where+ a == b =+ macroOpts a == macroOpts b+ && macroBody a == macroBody b+ && macroLevel a == macroLevel b+ && macroAuto a == macroAuto b++-- | the macro environment+data Env = Env+ { -- | a stack of definitions per name, newest first+ envMacros :: !(Map Name [MacroDef]),+ -- | whether system macros are loaded. if not, unknown names become 'Undefined' holes instead of literal text.+ envClosed :: !Bool+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | what to evaluate for. 'Nothing' means unknown.+data Target = Target+ { -- | sets @%_arch@ and @%_target_cpu@+ targetArch :: !(Maybe Text),+ -- | sets @%_os@ and @%_target_os@+ targetOs :: !(Maybe Text),+ -- | macro overrides. 'Nothing' undefines.+ targetMacros :: ![(Name, Maybe Text)]+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | Linux with an unknown arch+unknownTarget :: Target+unknownTarget = Target Nothing (Just "linux") []++-- | how serious a message is+data Severity+ = -- | informational, like @%{echo:...}@+ Info+ | -- | a warning, like @%{warn:...}@+ Warn+ | -- | an error, like @%{error:...}@ or a bad expression+ Error+ deriving stock (Eq, Ord, Show, Enum, Bounded, Generic)+ deriving anyclass (NFData)++instance ToJSON Severity where+ toJSON = \case+ Info -> "info"+ Warn -> "warning"+ Error -> "error"++-- | a message from evaluation, like a bad expression or @%{warn:...}@+data EvalMessage = EvalMessage+ { emSeverity :: !Severity,+ emSpan :: !(Maybe Span),+ emText :: !Text+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)
+ src/Rozbir/IO.hs view
@@ -0,0 +1,112 @@+-- | reading specs and rpm macro files from disk. this is the only module in+-- rozbir that does IO.+module Rozbir.IO+ ( readSpec,+ readSpecText,+ resolveIncludes,+ macroPath,+ loadMacroFiles,+ loadSystemMacros,+ )+where++import Control.Exception (IOException, try)+import Control.Monad (foldM)+import Data.ByteString qualified as BS+import Data.List (isPrefixOf, isSuffixOf, sort)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding (decodeUtf8Lenient)+import Rozbir.Eval (Env, newEnv, withMacroFile)+import Rozbir.MacroFile (parseMacroFile, toDefinitions)+import Rozbir.Syntax+import Rozbir.Syntax.Parse (parse)+import Rozbir.Syntax.Render (renderFrags)+import System.Directory (doesDirectoryExist, doesFileExist, listDirectory)+import System.FilePath (isAbsolute, takeDirectory, takeFileName, (</>))++-- | read a file as UTF-8, replacing invalid bytes+readSpecText :: FilePath -> IO Text+readSpecText path = decodeUtf8Lenient <$> BS.readFile path++-- | read and parse a spec+readSpec :: FilePath -> IO Tree+readSpec path = parse <$> readSpecText path++-- | read the @%include@ files a spec uses, relative to the spec's directory,+-- for 'Rozbir.Spec.roIncludes'. files that are missing, unreadable or named+-- with a macro are left out.+resolveIncludes :: FilePath -> Tree -> IO (Map Text Tree)+resolveIncludes specPath = go (0 :: Int) Map.empty+ where+ dir = takeDirectory specPath+ go depth acc tree+ | depth > 16 = pure acc+ | otherwise = foldM (visit depth) acc (includeArgs tree)+ visit depth acc arg+ | Map.member arg acc || T.any (== '%') arg || T.null arg = pure acc+ | otherwise = do+ let path = T.unpack arg+ full = if isAbsolute path then path else dir </> path+ exists <- doesFileExist full+ if not exists+ then pure acc+ else do+ r <- try (readSpec full) :: IO (Either IOException Tree)+ case r of+ Left _ -> pure acc+ Right tree -> go (depth + 1) (Map.insert arg tree acc) tree+ includeArgs tree = [T.strip (renderFrags fs) | Line {lineBody = Include _ fs} <- treeLines tree]++-- | rpm's macro file search path for a platform like @x86_64-linux@. entries+-- can end in a @*@ glob.+macroPath :: Text -> [FilePath]+macroPath target =+ let t = T.unpack target+ in [ "/usr/lib/rpm/macros",+ "/usr/lib/rpm/macros.d/macros.*",+ "/usr/lib/rpm/platform/" <> t <> "/macros",+ "/usr/lib/rpm/redhat/macros",+ "/etc/rpm/macros.*",+ "/etc/rpm/macros",+ "/etc/rpm/" <> t <> "/macros"+ ]++-- | load macro files on top of an environment, in order. later files win, and+-- missing or unreadable files are skipped.+loadMacroFiles :: [FilePath] -> Env -> IO Env+loadMacroFiles patterns env0 = do+ files <- concat <$> mapM expandGlob patterns+ foldM load env0 files+ where+ load env file = do+ r <- try (BS.readFile file) :: IO (Either IOException BS.ByteString)+ pure $ case r of+ Left _ -> env+ Right bytes -> withMacroFile (toDefinitions file (parseMacroFile (decodeUtf8Lenient bytes))) env++expandGlob :: FilePath -> IO [FilePath]+expandGlob pat+ | '*' `notElem` name = do+ exists <- doesFileExist pat+ pure [pat | exists]+ | otherwise = do+ exists <- doesDirectoryExist dir+ if not exists+ then pure []+ else do+ entries <- sort <$> listDirectory dir+ let (prefix, rest) = break (== '*') name+ suffixPart = drop 1 rest+ pure [dir </> e | e <- entries, prefix `isPrefixOf` e, suffixPart `isSuffixOf` e, not ("~" `isSuffixOf` e), not (".rpmnew" `isSuffixOf` e), not (".rpmsave" `isSuffixOf` e)]+ where+ dir = takeDirectory pat+ name = takeFileName pat++-- | load this system's rpm macros for an arch (default @x86_64@) into a+-- closed environment, where undefined macros stay as text like in rpm+loadSystemMacros :: Maybe Text -> IO Env+loadSystemMacros arch = loadMacroFiles (macroPath (fromMaybe "x86_64" arch <> "-linux")) (newEnv True)
+ src/Rozbir/Lint.hs view
@@ -0,0 +1,142 @@+-- | runs lint rules on a spec and drops findings silenced by ignore comments+-- like @# rozbir: ignore[rule]@. the core and rpmlint rulesets are on by+-- default, terra is opt-in.+module Rozbir.Lint+ ( module Rozbir.Lint.Types,+ allRules,+ rulesFor,+ findRule,+ runLint,+ lintTree,+ Directive (..),+ directives,+ applyFix,+ )+where++import Data.List (nub, sortOn)+import Data.Map.Strict qualified as Map+import Data.Maybe (mapMaybe)+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Text qualified as T+import Rozbir.Edit (apply)+import Rozbir.Eval (Env, Target)+import Rozbir.Lint.Core qualified as Core+import Rozbir.Lint.Rpmlint qualified as Rpmlint+import Rozbir.Lint.Terra qualified as Terra+import Rozbir.Lint.Types+import Rozbir.Spec (ResolveOptions (..), resolveWith)+import Rozbir.Syntax+import Rozbir.Syntax.Render (render, renderFrags)++-- | every rule in every ruleset+allRules :: [Rule]+allRules = Core.rules <> Rpmlint.rules <> Terra.rules <> [unusedIgnoreRule]++unusedIgnoreRule :: Rule+unusedIgnoreRule = Rule "unused-ignore" Core Warn "a rozbir: ignore directive that no longer suppresses anything" (const [])++-- | the rules a config turns on: its rulesets, plus rules given a severity in+-- 'lcOverrides', minus rules overridden to Nothing+rulesFor :: LintConfig -> [Rule]+rulesFor LintConfig {..} =+ [ r+ | r <- allRules,+ ruleSet r `Set.member` lcRuleSets || Map.lookup (ruleId r) lcOverrides `notElem` [Nothing, Just Nothing],+ Map.lookup (ruleId r) lcOverrides /= Just Nothing+ ]++-- | look up a rule by id+findRule :: RuleId -> Maybe Rule+findRule rid = case filter ((== rid) . ruleId) allRules of+ r : _ -> Just r+ [] -> Nothing++-- | a @# rozbir: ignore[...]@ or @# rozbir: ignore-file[...]@ comment+data Directive = Directive+ { dirSpan :: !Span,+ -- | True for @ignore-file@, which covers the whole spec+ dirFile :: !Bool,+ -- | the rule ids it names+ dirRules :: ![RuleId],+ -- | line numbers it covers, its own and the next line's+ dirCovers :: ![Int]+ }+ deriving stock (Eq, Show)++-- | every ignore comment in a tree+directives :: Tree -> [Directive]+directives tree = mapMaybe directive (zip ls (drop 1 (map Just ls) <> [Nothing]))+ where+ ls = treeLines tree+ directive (l, next) = case lineBody l of+ Comment _ fs -> do+ let text = T.strip (T.drop 1 (T.stripStart (renderFrags fs)))+ rest <- T.stripPrefix "rozbir:" text+ let body = T.stripStart rest+ (kw, afterKw) = T.span (\c -> c == '-' || c >= 'a' && c <= 'z') body+ inner <- T.stripPrefix "[" afterKw+ let (names, closing) = T.break (== ']') inner+ _ <- T.stripPrefix "]" closing+ let ruleIds = filter (not . T.null) (map T.strip (T.splitOn "," names))+ here = posLine (spanStart (lineSpan l))+ covered = here : maybe [] (\n -> [posLine (spanStart (lineSpan n)) .. posLine (spanEnd (lineSpan n))]) next+ case kw of+ "ignore" -> Just (Directive (lineSpan l) False ruleIds covered)+ "ignore-file" -> Just (Directive (lineSpan l) True ruleIds [])+ _ -> Nothing+ _ -> Nothing++-- | run the enabled rules and return findings sorted by position. ignore+-- comments that silence nothing or name an unknown rule are reported as+-- @unused-ignore@.+runLint :: LintConfig -> LintInput -> [Diagnostic]+runLint cfg li =+ let active = rulesFor cfg+ raw =+ nub+ [ d {diagSeverity = severityOf r}+ | r <- active,+ d <- ruleCheck r li+ ]+ severityOf r = case Map.lookup (ruleId r) (lcOverrides cfg) of+ Just (Just s) -> s+ _ -> ruleSeverity r+ dirs = directives (liTree li)+ suppressedBy d dir =+ diagRule d `elem` dirRules dir+ && (dirFile dir || posLine (spanStart (diagSpan d)) `elem` dirCovers dir)+ kept = [d | d <- raw, not (any (suppressedBy d) dirs)]+ unusedOn = any ((== "unused-ignore") . ruleId) active+ unused =+ [ diag "unused-ignore" (dirSpan dir) ("this directive doesn't suppress " <> rid <> " anywhere")+ | unusedOn,+ dir <- dirs,+ rid <- dirRules dir,+ ruleIsActive rid,+ not (any (\d -> diagRule d == rid && suppressedBy d dir) raw)+ ]+ ruleIsActive rid = any ((== rid) . ruleId) active+ unknownRule =+ [ diag "unused-ignore" (dirSpan dir) (rid <> " isn't a rozbir rule")+ | unusedOn,+ dir <- dirs,+ rid <- dirRules dir,+ null (findRule rid)+ ]+ in sortOn (\d -> (posOffset (spanStart (diagSpan d)), diagRule d)) (kept <> map (\d -> d {diagSeverity = severityOfId "unused-ignore"}) (unused <> unknownRule))+ where+ severityOfId rid = case Map.lookup rid (lcOverrides cfg) of+ Just (Just s) -> s+ _ -> Warn++-- | resolve a tree for each target and lint it. with no targets, rules that+-- need a resolved spec find nothing.+lintTree :: LintConfig -> Env -> [Target] -> Map.Map Text Tree -> Tree -> [Diagnostic]+lintTree cfg env targets includes tree =+ runLint cfg (LintInput (render tree) tree [(t, resolveWith (ResolveOptions env t includes) tree) | t <- targets])++-- | apply a fix to the source text it was made for+applyFix :: Fix -> Text -> Text+applyFix f = apply (fixEdits f)
+ src/Rozbir/Lint/Core.hs view
@@ -0,0 +1,328 @@+-- | the core ruleset: syntax errors, missing or duplicate tags, bad+-- changelogs, evaluation errors and other things rpm itself trips on. on by+-- default.+module Rozbir.Lint.Core (rules) where++import Data.Char (isDigit)+import Data.List (nub, sortOn)+import Data.Map.Strict qualified as Map+import Data.Maybe (mapMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Rozbir.Changelog (Entry (..), EntryHeader (..))+import Rozbir.Edit (TextEdit (..))+import Rozbir.Eval.Types+import Rozbir.Lint.Types+import Rozbir.Query (splitDeps)+import Rozbir.Spec+import Rozbir.Syntax+import Rozbir.Syntax.Render (lineFrags, macroSpans, renderFrags, renderMacro)++-- | every core rule+rules :: [Rule]+rules =+ syntaxRules+ <> [ Rule "unknown-tag" Core Error "a preamble line looks like a tag but rpm doesn't know it" unknownTag,+ Rule "duplicate-tag" Core Error "a single-valued tag is set twice for the same package" duplicateTag,+ Rule "missing-required-tag" Core Error "a package is missing Name, Version, Release, Summary or License" missingTag,+ Rule "missing-description" Core Error "a package has no %description" missingDescription,+ Rule "section-for-unknown-package" Core Error "%files, %description or a scriptlet names a package no %package declares" unknownPackage,+ Rule "duplicate-source-number" Core Error "two Source or Patch tags share a number" duplicateSource,+ Rule "macro-in-comment" Core Warn "rpm expands macros in comments, so %define in a comment still defines" macroInComment,+ Rule "needs-newer-rpm" Core Warn "uses syntax EL10's rpm 4.19 doesn't understand" newerRpm,+ Rule "patchn-obsolete" Core Error "%patchN was removed in rpm 4.20, use %patch -P N" patchN,+ Rule "changelog-date" Core Warn "a changelog entry has a bad date or the wrong weekday" changelogDate,+ Rule "changelog-order" Core Warn "changelog entries should go newest first" changelogOrder,+ Rule "eval-error" Core Error "a macro or condition fails to evaluate the way rpm would fail" evalError,+ Rule "line-outside-section" Core Error "text after %end that belongs to no section" outsideSection,+ Rule "undefined-macro" Core Warn "a macro stays as literal text because nothing defines it (needs system macros loaded)" undefinedMacro,+ Rule "bcond-unused" Core Warn "a bcond that no %{with} or %{without} ever checks" bcondUnused,+ Rule "duplicate-dependency" Core Warn "the same dependency is listed twice for one package" duplicateDependency+ ]++syntaxRules :: [Rule]+syntaxRules =+ [ syntaxRule "unclosed-if" "an %if without %endif",+ syntaxRule "stray-endif" "an %endif without %if",+ syntaxRule "stray-else" "an %else without %if",+ syntaxRule "stray-elif" "an %elif without %if",+ syntaxRule "branch-after-else" "an %elif or %else after %else",+ syntaxRule "unclosed-macro" "a %{, %( or %[ that's never closed",+ syntaxRule "trailing-backslash" "a line continuation at the end of the file",+ syntaxRule "not-a-tag" "a preamble line that isn't a tag, macro or section"+ ]+ where+ syntaxRule rid doc = Rule rid Core Error doc $ \li ->+ [diag rid (seSpan e) (seMessage e) | e <- treeErrors (liTree li), seCode e == rid]++singleValued :: [Text]+singleValued = ["name", "version", "release", "epoch", "summary", "license", "url", "buildarch", "buildarchitectures", "group", "packager", "vendor", "buildsystem", "sourcelicense"]++unknownTag :: LintInput -> [Diagnostic]+unknownTag li =+ [ diag "unknown-tag" (lineSpan l) ("rpm doesn't know the tag " <> tagName t)+ | (sec, l@Line {lineBody = Tag t}) <- linesWithSection (liTree li),+ preambleLike sec,+ let lower = T.toLower (tagName t)+ base = T.dropWhileEnd isDigit lower,+ lower `notElem` knownTags,+ not (base `elem` ["source", "patch", "nosource", "nopatch"])+ ]++overlapping :: Guard -> Guard -> Bool+overlapping a b = not (any conflicts a)+ where+ conflicts x = any (\y -> assumeIf x == assumeIf y && assumeBranch x /= assumeBranch y) b++duplicateTag :: LintInput -> [Diagnostic]+duplicateTag li =+ nub+ [ diag "duplicate-tag" (locSpan later) (teName (locValue later) <> " is already set on line " <> lineNo (locSpan earlier))+ | spec <- map snd (liSpecs li),+ pkg <- specPackages spec,+ key <- singleValued,+ let entries = sortOn (posOffset . spanStart . locSpan) [e | e <- packageTags key pkg, isRaw e],+ (i, later) <- zip [0 :: Int ..] entries,+ earlier <- take 1 [e | e <- take i entries, overlapping (locGuard e) (locGuard later)]+ ]+ where+ isRaw e = case teRaw (locValue e) of+ Just _ -> True+ Nothing -> False++lineNo :: Span -> Text+lineNo sp = T.pack (show (posLine (spanStart sp) + 1))++missingTag :: LintInput -> [Diagnostic]+missingTag li =+ nub $+ concat+ [ [ diag "missing-required-tag" (anchor pkg) (what pkg <> " has no " <> pretty key <> " tag")+ | key <- required pkg,+ null (packageTags key pkg)+ ]+ | spec <- map snd (liSpecs li),+ pkg <- specPackages spec,+ not (pkgOpaque pkg),+ not (null (pkgTags pkg)) || pkgKey pkg /= MainKey+ ]+ where+ required pkg = if pkgKey pkg == MainKey then ["name", "version", "release", "summary", "license"] else ["summary"]+ pretty k = T.toUpper (T.take 1 k) <> T.drop 1 k+ anchor pkg = maybe startSpan id (pkgHeader pkg)+ startSpan = Span startPos startPos+ what pkg = if pkgKey pkg == MainKey then "the main package" else "%package " <> showValue (pkgName pkg)++missingDescription :: LintInput -> [Diagnostic]+missingDescription li =+ nub+ [ diag "missing-description" (maybe (Span startPos startPos) id (pkgHeader pkg)) (label pkg <> " has no %description")+ | spec <- map snd (liSpecs li),+ not (null (specSections spec)) || not (null (concatMap pkgTags (specPackages spec))),+ pkg <- specPackages spec,+ pkgKey pkg /= MainKey || not (null (pkgTags pkg)),+ not (pkgOpaque pkg),+ not (any (\s -> scKind s == SDescription && scPackage s == pkgKey pkg) (specSections spec))+ ]+ where+ label pkg = if pkgKey pkg == MainKey then "the main package" else "%package " <> showValue (pkgName pkg)++unknownPackage :: LintInput -> [Diagnostic]+unknownPackage li =+ nub+ [ diag "section-for-unknown-package" (scHeader s) ("%" <> sectionName (scKind s) <> " is for " <> showValue (scPackageName s) <> ", but no %package declares it")+ | spec <- map snd (liSpecs li),+ s <- specSections spec,+ scKind s /= SPackage,+ scPackage s /= MainKey,+ not (any ((== scPackage s) . pkgKey) (specPackages spec)),+ isKnown (scPackageName s)+ ]++duplicateSource :: LintInput -> [Diagnostic]+duplicateSource li =+ nub+ [ diag "duplicate-source-number" (locSpan b) (kind b <> show' (srcNumber (locValue b)) <> " is already defined on line " <> lineNo (locSpan a))+ | spec <- map snd (liSpecs li),+ let srcs = specSources spec,+ (i, b) <- zip [0 :: Int ..] srcs,+ a <- take 1 [a | a <- take i srcs, srcPatch (locValue a) == srcPatch (locValue b), srcNumber (locValue a) == srcNumber (locValue b), overlapping (locGuard a) (locGuard b)]+ ]+ where+ kind x = if srcPatch (locValue x) then "Patch" else "Source"+ show' = T.pack . show++macroInComment :: LintInput -> [Diagnostic]+macroInComment li =+ [ (diag "macro-in-comment" sp ("rpm expands " <> renderMacro m <> " even though it's in a comment"))+ { diagFixes = [Fix "escape the macros as %%" [TextEdit (lineSpan l) (escaped indent fs)] True]+ }+ | l@Line {lineBody = Comment indent fs} <- treeLines (liTree li),+ not (isDirective fs),+ (sp, m) <- take 1 [x | (p, fs') <- lineFrags l, x <- macroSpans p fs'],+ hasMacro fs+ ]+ where+ hasMacro = any (\case Macro _ -> True; _ -> False)+ isDirective fs = "rozbir:" `T.isInfixOf` renderFrags fs+ escaped indent fs = indent <> T.concat (map esc fs)+ esc = \case+ Macro m -> "%" <> renderMacro m+ f -> renderFrags [f]++newerRpm :: LintInput -> [Diagnostic]+newerRpm li =+ concat+ [ case lineBody l of+ Header h+ | secKind h == SConf -> [d l "%conf needs rpm 4.20"]+ | isBuildSection (secKind h), any (`elem` ["-a", "-p"]) (T.words (renderFrags (secArgs h))) -> [d l (secKeyword h <> " -a/-p needs rpm 4.20")]+ Tag t+ | preambleLike sec,+ T.toLower (tagName t) `elem` ["buildsystem", "buildoption"] ->+ [d l (tagName t <> " needs rpm 4.20")]+ _ -> []+ | (sec, l) <- linesWithSection (liTree li)+ ]+ where+ d l msg = diag "needs-newer-rpm" (lineSpan l) (msg <> ", but EL10 ships rpm 4.19")++patchN :: LintInput -> [Diagnostic]+patchN li =+ [ (diag "patchn-obsolete" sp ("%patch" <> n <> " was removed in rpm 4.20"))+ { diagFixes = [Fix ("use %patch -P " <> n) [TextEdit sp ("%patch -P " <> n)] True]+ }+ | (Just SPrep, l) <- linesWithSection (liTree li),+ (p, fs) <- lineFrags l,+ (sp, Bare "" name) <- macroSpans p fs,+ Just n <- [T.stripPrefix "patch" name],+ not (T.null n),+ T.all isDigit n+ ]++changelogDate :: LintInput -> [Diagnostic]+changelogDate li =+ nub $+ concat+ [ [diag "changelog-date" sp msg | (sp, msg) <- specChangelogProblems spec]+ <> [ diag "changelog-date" (entrySpan e) ("the date isn't a " <> ehWeekday (entryHeader e))+ | e <- specChangelog spec,+ Just _ <- [ehDate (entryHeader e)],+ not (ehWeekdayMatches (entryHeader e))+ ]+ | spec <- firstSpec li+ ]++changelogOrder :: LintInput -> [Diagnostic]+changelogOrder li =+ [ diag "changelog-order" (entrySpan b) "this entry is newer than the one before it, but entries go newest first"+ | spec <- firstSpec li,+ let dated = mapMaybe (\e -> (,e) <$> ehDate (entryHeader e)) (specChangelog spec),+ ((da, _), (db, b)) <- zip dated (drop 1 dated),+ db > da+ ]++evalError :: LintInput -> [Diagnostic]+evalError li =+ nub+ [ diag "eval-error" sp (emText m)+ | spec <- map snd (liSpecs li),+ m <- specMessages spec,+ emSeverity m == Error,+ Just sp <- [emSpan m]+ ]++outsideSection :: LintInput -> [Diagnostic]+outsideSection li =+ [ diag "line-outside-section" (lineSpan l) "this line comes after %end, so it belongs to no section"+ | (Just SEnd, l) <- linesWithSection (liTree li),+ case lineBody l of+ Blank _ -> False+ Comment _ _ -> False+ Header _ -> False+ Define _ -> False+ Cond _ -> False+ _ -> True+ ]++undefinedMacro :: LintInput -> [Diagnostic]+undefinedMacro li =+ nub+ [ d+ | spec <- map snd (liSpecs li),+ let defined = Map.keys (envMacros (specEnv spec)),+ (n, sp) <- specUndefined spec,+ d <- explain spec defined n (narrow sp n)+ ]+ where+ narrow sp n = case [s | l <- treeLines (liTree li), lineSpan l == sp, (p, fs) <- lineFrags l, (s, m) <- macroSpans p fs, macroName m == Just n] of+ s : _ -> s+ [] -> sp+ tagLines = [(T.toLower (tagName t), lineSpan l) | l@Line {lineBody = Tag t} <- treeLines (liTree li)]+ explain spec defined n sp+ | Just later <- lookup n tagLines,+ posOffset (spanStart later) > posOffset (spanStart sp) =+ [diag "undefined-macro" sp ("%" <> n <> " is used before the tag on line " <> lineNo later <> " defines it, so rpm leaves it as text")]+ | (c : _) <- [x | x <- defined, x /= n, T.toLower x == T.toLower n] =+ [suggest sp n c]+ | T.length n >= 5,+ (c : _) <- [x | x <- defined, T.length x >= 5, oneEdit n x] =+ [suggest sp n c]+ | otherwise = const [] spec+ suggest sp n c =+ (diag "undefined-macro" sp ("%" <> n <> " isn't defined, so rpm leaves it as text. did you mean %" <> c <> "?"))+ { diagFixes = [Fix ("use %" <> c) [TextEdit sp (T.replace n c (renderMacroAt sp))] False]+ }+ renderMacroAt sp = T.take (posOffset (spanEnd sp) - posOffset (spanStart sp)) (T.drop (posOffset (spanStart sp)) (liSource li))++oneEdit :: Text -> Text -> Bool+oneEdit a b+ | a == b = False+ | T.length a == T.length b = let diffs = [(x, y) | (x, y) <- T.zip a b, x /= y] in length diffs == 1 || swapped+ | abs (T.length a - T.length b) == 1 = deletion (T.unpack (longer a b)) (T.unpack (shorter a b))+ | otherwise = False+ where+ longer x y = if T.length x > T.length y then x else y+ shorter x y = if T.length x > T.length y then y else x+ swapped = case [i | (i, (x, y)) <- zip [0 :: Int ..] (T.zip a b), x /= y] of+ [i, j] -> j == i + 1 && T.index a i == T.index b j && T.index a j == T.index b i+ _ -> False+ deletion (x : xs) (y : ys)+ | x == y = deletion xs ys+ | otherwise = xs == (y : ys)+ deletion [_] [] = True+ deletion _ _ = False++bcondUnused :: LintInput -> [Diagnostic]+bcondUnused li =+ [ diag "bcond-unused" (lineSpan l) ("nothing checks %{with " <> defName d <> "}, so the bcond does nothing")+ | l@Line {lineBody = Define d} <- treeLines (liTree li),+ defKind d `elem` [DefBcond, DefBcondWith, DefBcondWithout],+ defName d `notElem` used+ ]+ where+ used = concatMap refs [m | l <- treeLines (liTree li), (p, fs) <- lineFrags l, (_, m) <- macroSpans p fs]+ refs = \case+ Braced _ n (Just (SpaceArg fs)) | n `elem` ["with", "without"] -> [T.strip (renderFrags fs)]+ Bare _ n | Just b <- T.stripPrefix "with_" n -> [b]+ Braced _ n _ | Just b <- T.stripPrefix "with_" n -> [b]+ _ -> []++duplicateDependency :: LintInput -> [Diagnostic]+duplicateDependency li =+ nub+ [ diag "duplicate-dependency" (locSpan b) (label <> " " <> locValue b <> " is already listed on line " <> lineNo (locSpan a))+ | spec <- map snd (liSpecs li),+ pkg <- specPackages spec,+ key <- ["requires", "buildrequires", "provides", "conflicts", "obsoletes", "recommends", "suggests", "buildconflicts"],+ let deps = [(qualOf e, Located dep (locSpan e) (locGuard e)) | e <- packageTags key pkg, Just t <- [knownText (teValue (locValue e))], dep <- splitDeps t],+ (i, (q, b)) <- zip [0 :: Int ..] deps,+ a <- take 1 [a | (q', a) <- take i deps, q' == q, locValue a == locValue b, locSpan a /= locSpan b, overlapping (locGuard a) (locGuard b)],+ let label = maybe (prettyKey key) (\x -> prettyKey key <> x) q+ ]+ where+ qualOf e = teQualifier (locValue e)+ prettyKey k = case k of+ "buildrequires" -> "BuildRequires"+ "buildconflicts" -> "BuildConflicts"+ _ -> T.toUpper (T.take 1 k) <> T.drop 1 k
+ src/Rozbir/Lint/Rpmlint.hs view
@@ -0,0 +1,317 @@+-- | rpmlint's spec checks, run on the parsed spec so they see every @%if@+-- branch. on by default.+module Rozbir.Lint.Rpmlint (rules) where++import Data.Char (isSpace)+import Data.List (nub)+import Data.Maybe (listToMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Rozbir.Edit (TextEdit (..), tagValueSpan)+import Rozbir.Eval.Types+import Rozbir.Lint.Types+import Rozbir.Query (dependencies)+import Rozbir.Spec+import Rozbir.Syntax+import Rozbir.Syntax.Render (lineFrags, macroSpans, renderBody, renderFrags, renderMacro)++-- | every rpmlint rule+rules :: [Rule]+rules =+ [ Rule "deprecated-tag" Rpmlint Warn "BuildRoot, Group, PreReq and BuildPreReq do nothing or have better spellings" deprecatedTag,+ Rule "clean-section" Rpmlint Warn "%clean isn't needed, rpm cleans the buildroot itself" cleanSection,+ Rule "hardcoded-path" Rpmlint Info "a path spelled out where a directory macro exists" hardcodedPath,+ Rule "mixed-tabs-spaces" Rpmlint Warn "the spec aligns with both tabs and spaces" mixedTabs,+ Rule "mixed-buildroot" Rpmlint Warn "both $RPM_BUILD_ROOT and %{buildroot} are used" mixedBuildroot,+ Rule "rpm-buildroot-usage" Rpmlint Error "the buildroot is touched in %prep or %build" buildrootUsage,+ Rule "macro-in-changelog" Rpmlint Warn "rpm expands macros in %changelog, escape them as %%" macroInChangelog,+ Rule "patch-not-applied" Rpmlint Warn "a Patch is declared but %prep never applies it" patchNotApplied,+ Rule "setup-not-quiet" Rpmlint Info "%setup without -q lists every file it unpacks" setupNotQuiet,+ Rule "summary-ended-with-dot" Rpmlint Warn "Summary shouldn't end with a period" summaryDot,+ Rule "summary-too-long" Rpmlint Warn "Summary is longer than 79 characters" summaryLong,+ Rule "description-line-too-long" Rpmlint Warn "a %description line is longer than 79 characters" descriptionLong,+ Rule "make-check-outside-check-section" Rpmlint Warn "make check runs outside %check" makeCheck,+ Rule "use-of-RPM_SOURCE_DIR" Rpmlint Warn "use %{SOURCEn} instead of $RPM_SOURCE_DIR or %{_sourcedir}" sourceDir,+ Rule "unversioned-obsoletes" Rpmlint Warn "an Obsoletes without a version also obsoletes every future release of that package" unversionedObsoletes,+ Rule "defattr" Rpmlint Info "%defattr(-,root,root,-) is the default and can go" defattr,+ Rule "rm-buildroot" Rpmlint Info "rpm cleans the buildroot before %install, so removing it there does nothing" rmBuildroot+ ]++deprecatedTag :: LintInput -> [Diagnostic]+deprecatedTag li =+ [ (diag "deprecated-tag" (lineSpan l) msg) {diagFixes = fixes}+ | (sec, l@Line {lineBody = Tag t}) <- linesWithSection (liTree li),+ preambleLike sec,+ let key = T.toLower (tagName t)+ nameSpan = Span (advancePos (spanStart (lineSpan l)) (tagIndent t)) (advancePos (spanStart (lineSpan l)) (tagIndent t <> tagName t)),+ (msg, fixes) <- case key of+ "buildroot" -> [("BuildRoot is ignored, rpm sets the buildroot itself", [Fix "remove BuildRoot" [TextEdit (lineFullSpan l) ""] True])]+ "group" -> [("Group is ignored by current rpm and Fedora", [Fix "remove Group" [TextEdit (lineFullSpan l) ""] True])]+ "buildprereq" -> [("BuildPreReq is deprecated, use BuildRequires", [Fix "rename to BuildRequires" [TextEdit nameSpan "BuildRequires"] True])]+ "prereq" -> [("PreReq is deprecated, use Requires(pre) or Requires(post)", [Fix "rename to Requires(pre)" [TextEdit nameSpan "Requires(pre)"] False])]+ _ -> []+ ]++cleanSection :: LintInput -> [Diagnostic]+cleanSection li =+ [ diag "clean-section" (lineSpan l) "%clean isn't needed, rpm cleans the buildroot itself"+ | l@Line {lineBody = Header h} <- treeLines (liTree li),+ secKind h == SClean+ ]++pathMacros :: [(Text, Text)]+pathMacros =+ [ ("/usr/share/man", "%{_mandir}"),+ ("/usr/share/info", "%{_infodir}"),+ ("/usr/share/doc", "%{_docdir}"),+ ("/usr/share", "%{_datadir}"),+ ("/usr/bin", "%{_bindir}"),+ ("/usr/sbin", "%{_sbindir}"),+ ("/usr/lib64", "%{_libdir}"),+ ("/usr/libexec", "%{_libexecdir}"),+ ("/usr/include", "%{_includedir}"),+ ("/etc", "%{_sysconfdir}"),+ ("/var/lib", "%{_sharedstatedir}"),+ ("/var", "%{_localstatedir}")+ ]++hardcodedPath :: LintInput -> [Diagnostic]+hardcodedPath li =+ [ (diag "hardcoded-path" sp ("use " <> macro <> " instead of " <> path))+ { diagFixes = [Fix ("replace with " <> macro) [TextEdit sp macro] False]+ }+ | (sec, l) <- linesWithSection (liTree li),+ sec `elem` [Just SFiles, Just SInstall],+ (p, fs) <- lineFrags l,+ (sp, path, macro) <- take 1 (pathHits p fs)+ ]+ where+ pathHits p fs =+ [ (Span s (advancePos s path), path, macro)+ | (Span fragStart _, Lit t) <- fragsWithSpans p fs,+ (offset, path, macro) <- take 1 (findPaths t),+ let s = advancePos fragStart (T.take offset t)+ ]+ findPaths t =+ [ (i, path, macro)+ | i <- candidates t,+ (path, macro) <- take 1 [x | x@(path, _) <- pathMacros, path `T.isPrefixOf` T.drop i t, boundaryAfter (T.drop (i + T.length path) t)]+ ]+ candidates t = [i | (i, c) <- zip [0 ..] (T.unpack t), c == '/', i == 0 || boundaryBefore (T.index t (i - 1))]+ boundaryBefore c = isSpace c || c `elem` ("\"'=" :: String)+ boundaryAfter rest = case T.uncons rest of+ Nothing -> True+ Just (c, _) -> c == '/' || isSpace c || c == '"' || c == '\''++fragsWithSpans :: Pos -> [Frag] -> [(Span, Frag)]+fragsWithSpans p = \case+ [] -> []+ f : fs -> let e = advancePos p (renderFrags [f]) in (Span p e, f) : fragsWithSpans e fs++mixedTabs :: LintInput -> [Diagnostic]+mixedTabs li = case (firstWith '\t', firstWith ' ') of+ (Just (tl, _), Just (sl, _)) ->+ let (later, other, kind) = if posOffset (spanStart (lineSpan tl)) > posOffset (spanStart (lineSpan sl)) then (tl, sl, "tabs") else (sl, tl, "spaces")+ in [diag "mixed-tabs-spaces" (lineSpan later) ("this line aligns with " <> kind <> ", but line " <> lineNo other <> " uses the other")]+ _ -> []+ where+ alignment l = case lineBody l of+ Tag t -> [T.dropWhile (/= ':') (tagSep t)]+ Define d -> [defSep d]+ _ -> []+ firstWith c = listToMaybe [(l, ()) | l <- treeLines (liTree li), w <- alignment l, uses c w]+ uses c w+ | c == '\t' = T.any (== '\t') w+ | otherwise = " " `T.isInfixOf` w+ lineNo l = T.pack (show (posLine (spanStart (lineSpan l)) + 1))++buildrootRefs :: Line -> ([Span], [Span])+buildrootRefs l =+ ( [sp | (p, fs) <- lineFrags l, (sp, m) <- macroSpans p fs, macroName m == Just "buildroot"],+ [ Span s (advancePos s "RPM_BUILD_ROOT")+ | (p, fs) <- lineFrags l,+ (Span fs0 _, Lit t) <- fragsWithSpans p fs,+ (pre, _) <- T.breakOnAll "RPM_BUILD_ROOT" t,+ "$" `T.isSuffixOf` pre || "${" `T.isSuffixOf` pre,+ let s = advancePos fs0 pre+ ]+ )++mixedBuildroot :: LintInput -> [Diagnostic]+mixedBuildroot li =+ let refs = map buildrootRefs (treeLines (liTree li))+ macros = concatMap fst refs+ vars = concatMap snd refs+ in if null macros || null vars+ then []+ else+ let (minority, word) = if length vars <= length macros then (vars, "$RPM_BUILD_ROOT") else (macros, "%{buildroot}")+ in [diag "mixed-buildroot" sp ("the spec mostly uses the other spelling, but this is " <> word) | sp <- take 1 minority]++buildrootUsage :: LintInput -> [Diagnostic]+buildrootUsage li =+ [ diag "rpm-buildroot-usage" sp ("the buildroot shouldn't be touched in %" <> sectionName k)+ | (Just k, l) <- linesWithSection (liTree li),+ k `elem` [SPrep, SBuild],+ let (a, b) = buildrootRefs l,+ sp <- take 1 (a <> b)+ ]++macroInChangelog :: LintInput -> [Diagnostic]+macroInChangelog li =+ [ (diag "macro-in-changelog" sp ("rpm expands " <> renderMacro m <> " in the changelog"))+ { diagFixes = [Fix "escape as %%" [TextEdit sp ("%" <> renderMacro m)] True]+ }+ | (Just SChangelog, l) <- linesWithSection (liTree li),+ case lineBody l of+ Header _ -> False+ Body fs -> not (macroOnly fs)+ _ -> True,+ (p, fs) <- lineFrags l,+ (sp, m) <- [(s, m) | (s, Macro m) <- fragsWithSpans p fs]+ ]++macroOnly :: [Frag] -> Bool+macroOnly fs = case filter (not . blankLit) fs of+ [Macro _] -> True+ _ -> False+ where+ blankLit = \case+ Lit t -> T.all isSpace t+ _ -> False++patchNotApplied :: LintInput -> [Diagnostic]+patchNotApplied li = case firstSpec li of+ [] -> []+ spec : _ ->+ let prepText = T.unlines [renderBody (lineBody l) | (Just SPrep, l) <- linesWithSection (liTree li)]+ ws = T.words (T.map (\c -> if c == '{' || c == '}' then ' ' else c) prepText)+ appliesAll = autosetupApplies ws || any (\w -> "autopatch" `T.isInfixOf` w || "forgeautosetup" `T.isInfixOf` w) ws || "%autosetup" `T.isInfixOf` prepText && not (T.isInfixOf "-N" (autosetupLine prepText))+ applied n = any (`elem` ws) (map (<> T.pack (show n)) ["%patch", "%PATCH", "PATCH", "%P:"]) || explicit n ws || T.isInfixOf ("%{PATCH" <> T.pack (show n) <> "}") prepText+ in if appliesAll || T.null prepText+ then []+ else+ nub+ [ diag "patch-not-applied" (locSpan p) ("Patch" <> T.pack (show n) <> " is never applied in %prep")+ | p <- specSources spec,+ srcPatch (locValue p),+ let n = srcNumber (locValue p),+ not (applied n)+ ]+ where+ autosetupApplies ws = "%autosetup" `elem` ws && "-N" `notElem` ws+ autosetupLine t = T.unwords [l | l <- T.lines t, "%autosetup" `T.isInfixOf` l]+ explicit n ws = any (matches n) (zip ws (drop 1 ws)) || any (\w -> T.stripPrefix "-P" w == Just (T.pack (show n))) ws+ matches n (a, b) = (a == "-P" || a == "%patch") && b == T.pack (show n)++setupNotQuiet :: LintInput -> [Diagnostic]+setupNotQuiet li =+ [ diag "setup-not-quiet" sp "%setup without -q lists every file it unpacks"+ | (Just SPrep, l) <- linesWithSection (liTree li),+ Body fs <- [lineBody l],+ (p, _) <- lineFrags l,+ (sp, Macro (Bare "" "setup")) <- take 1 [x | x@(_, Macro _) <- fragsWithSpans p fs],+ let args = T.words (renderFrags fs),+ not (any (\w -> "-" `T.isPrefixOf` w && not ("--" `T.isPrefixOf` w) && T.any (== 'q') w) args)+ ]++summaries :: LintInput -> [(Line, TagLine, Text)]+summaries li =+ [ (l, t, v)+ | (sec, l@Line {lineBody = Tag t}) <- linesWithSection (liTree li),+ preambleLike sec,+ T.toLower (tagName t) == "summary",+ let v = renderFrags (tagValue t)+ ]++summaryDot :: LintInput -> [Diagnostic]+summaryDot li =+ [ (diag "summary-ended-with-dot" (lineSpan l) "Summary shouldn't end with a period")+ { diagFixes = [Fix "remove the period" [TextEdit (tagValueSpan l t) (T.dropEnd 1 v)] True]+ }+ | (l, t, v) <- summaries li,+ "." `T.isSuffixOf` v,+ not ("..." `T.isSuffixOf` v),+ not (lastWordAbbrev v)+ ]+ where+ lastWordAbbrev v = case reverse (T.words v) of+ w : _ -> T.length w <= 4 && T.count "." w > 1+ [] -> False++summaryLong :: LintInput -> [Diagnostic]+summaryLong li =+ nub+ [ diag "summary-too-long" (locSpan e) ("Summary is " <> T.pack (show (T.length t)) <> " characters, keep it under 80")+ | spec <- map snd (liSpecs li),+ pkg <- specPackages spec,+ e <- packageTags "summary" pkg,+ Just t <- [knownText (teValue (locValue e))],+ T.length t > 79+ ]++descriptionLong :: LintInput -> [Diagnostic]+descriptionLong li =+ nub+ [ diag "description-line-too-long" (locSpan l) ("this line is " <> T.pack (show (T.length t)) <> " characters, wrap it at 79")+ | spec <- map snd (liSpecs li),+ s <- specSections spec,+ scKind s == SDescription,+ l <- scLines s,+ Just t <- [knownText (locValue l)],+ T.length t > 79,+ length (T.words t) > 1+ ]++makeCheck :: LintInput -> [Diagnostic]+makeCheck li =+ [ diag "make-check-outside-check-section" (lineSpan l) ("make check runs in %" <> sectionName k <> ", tests belong in %check")+ | (Just k, l@Line {lineBody = Body fs}) <- linesWithSection (liTree li),+ k /= SCheck,+ isBuildSection k,+ let ws = T.words (renderFrags fs),+ any (\(a, b) -> isMake a && b == "check") (zip ws (drop 1 ws))+ ]+ where+ isMake w = w `elem` ["make", "%make_build", "%{make_build}", "%__make", "%{__make}", "%make"] || "/make" `T.isSuffixOf` w++sourceDir :: LintInput -> [Diagnostic]+sourceDir li =+ [ diag "use-of-RPM_SOURCE_DIR" (lineSpan l) "use %{SOURCEn} instead of reaching into the source directory"+ | (Just k, l) <- linesWithSection (liTree li),+ k /= SPackage,+ let raw = renderBody (lineBody l),+ "$RPM_SOURCE_DIR" `T.isInfixOf` raw || "${RPM_SOURCE_DIR}" `T.isInfixOf` raw || any (\(_, m) -> macroName m == Just "_sourcedir") [x | (p, fs) <- lineFrags l, x <- macroSpans p fs]+ ]++unversionedObsoletes :: LintInput -> [Diagnostic]+unversionedObsoletes li =+ nub+ [ diag "unversioned-obsoletes" (locSpan d) ("Obsoletes: " <> locValue d <> " has no version, so it obsoletes every future " <> locValue d <> " too")+ | spec <- map snd (liSpecs li),+ pkg <- specPackages spec,+ d <- dependencies "obsoletes" pkg,+ not (T.any (`elem` ['<', '>', '=']) (locValue d)),+ not ("(" `T.isPrefixOf` locValue d)+ ]++deleteLine :: Text -> Line -> Fix+deleteLine title l = Fix title [TextEdit (lineFullSpan l) ""] True++defattr :: LintInput -> [Diagnostic]+defattr li =+ [ (diag "defattr" (lineSpan l) "%defattr(-,root,root,-) is already the default") {diagFixes = [deleteLine "remove %defattr" l]}+ | (Just SFiles, l@Line {lineBody = Body fs}) <- linesWithSection (liTree li),+ let t = T.filter (not . isSpace) (renderFrags fs),+ t `elem` ["%defattr(-,root,root,-)", "%defattr(-,root,root)", "%defattr(-,root,root,0755)"]+ ]++rmBuildroot :: LintInput -> [Diagnostic]+rmBuildroot li =+ [ (diag "rm-buildroot" (lineSpan l) "rpm already cleans the buildroot before %install") {diagFixes = [deleteLine "remove the line" l]}+ | (Just SInstall, l@Line {lineBody = Body fs}) <- linesWithSection (liTree li),+ let ws = T.words (T.replace "\"" "" (renderFrags fs)),+ case ws of+ ["rm", flags, target] -> T.all (`elem` ['-', 'r', 'f', 'R']) flags && T.dropWhileEnd (== '/') target `elem` ["%{buildroot}", "%buildroot", "$RPM_BUILD_ROOT", "${RPM_BUILD_ROOT}"]+ _ -> False+ ]
+ src/Rozbir/Lint/Terra.hs view
@@ -0,0 +1,98 @@+-- | Terra's packaging conventions, such as a Packager tag and a Version that+-- @update.rhai@ can change. off unless the terra ruleset is enabled.+module Rozbir.Lint.Terra (rules) where++import Data.Char (isDigit)+import Data.List (nub)+import Data.Map.Strict qualified as Map+import Data.Text qualified as T+import Rozbir.Edit (TextEdit (..), preambleTags, tagValueSpan)+import Rozbir.Lint.Types+import Rozbir.Query (definitions, macroReferences)+import Rozbir.Syntax+import Rozbir.Syntax.Render (lineFrags, macroSpans, renderFrags)++-- | every Terra rule+rules :: [Rule]+rules =+ [ Rule "terra-packager" Terra Info "Terra credits whoever maintains a package with a Packager tag" packager,+ Rule "terra-dist-release" Terra Warn "Release should end in %{?dist} so builds for different releases don't collide" distRelease,+ Rule "terra-define-global" Terra Info "prefer %global to %define outside parametric macros, like Fedora" defineGlobal,+ Rule "terra-version-editable" Terra Warn "update.rhai can only set Version through literal text or a %global in the spec" versionEditable,+ Rule "terra-py3-build" Terra Warn "%py3_build and %py3_install are deprecated, use the pyproject macros" py3Build,+ Rule "terra-insecure-url" Terra Info "a URL or Source uses http:// where https:// probably works" insecureUrl+ ]++packager :: LintInput -> [Diagnostic]+packager li =+ [ diag "terra-packager" sp "the main package has no Packager tag"+ | let tags = preambleTags (liTree li),+ not (null tags),+ not (any (\(_, t) -> T.toLower (tagName t) == "packager") tags),+ (l, _) <- take 1 [x | x@(_, t) <- tags, T.toLower (tagName t) == "name"],+ let sp = lineSpan l+ ]++distRelease :: LintInput -> [Diagnostic]+distRelease li =+ [ (diag "terra-dist-release" (lineSpan l) "Release doesn't include %{?dist}")+ { diagFixes = [Fix "append %{?dist}" [TextEdit (tagValueSpan l t) (v <> "%{?dist}")] True]+ }+ | (l, t) <- preambleTags (liTree li),+ T.toLower (tagName t) == "release",+ let refs = macroReferences (tagValue t)+ v = renderFrags (tagValue t),+ "dist" `notElem` refs,+ "autorelease" `notElem` refs,+ not (any (`Map.member` definitions (liTree li)) refs)+ ]++defineGlobal :: LintInput -> [Diagnostic]+defineGlobal li =+ [ (diag "terra-define-global" (lineSpan l) ("%" <> defName d <> " is defined with %define, use %global"))+ { diagFixes = [Fix "use %global" [TextEdit (Span s (advancePos s (defKeyword d))) "%global"] False]+ }+ | l@Line {lineBody = Define d} <- treeLines (liTree li),+ defKind d == DefDefine,+ defOpts d == Nothing,+ T.null (T.strip (defGap d)),+ let s = advancePos (spanStart (lineSpan l)) (defIndent d)+ ]++versionEditable :: LintInput -> [Diagnostic]+versionEditable li =+ nub+ [ diag "terra-version-editable" (lineSpan l) "Version only uses macros the spec doesn't define with %global, so update.rhai can't change it"+ | (l, t) <- preambleTags (liTree li),+ T.toLower (tagName t) == "version",+ let refs = macroReferences (tagValue t)+ defs = definitions (liTree li)+ hasLiteral = any (\case Lit x -> T.any (`notElem` (" \t" :: String)) x; _ -> False) (tagValue t),+ not hasLiteral,+ not (null refs),+ not (any (\r -> any ((== DefGlobal) . defKind) (Map.findWithDefault [] r defs)) refs)+ ]++py3Build :: LintInput -> [Diagnostic]+py3Build li =+ [ diag "terra-py3-build" sp ("%" <> n <> " is deprecated, use %pyproject_wheel and %pyproject_install")+ | (Just k, l) <- linesWithSection (liTree li),+ k `elem` [SBuild, SInstall],+ (p, fs) <- lineFrags l,+ (sp, m) <- macroSpans p fs,+ Just n <- [macroName m],+ n `elem` ["py3_build", "py3_install", "py_build", "py_install", "py3_build_wheel", "py3_build_egg"]+ ]++insecureUrl :: LintInput -> [Diagnostic]+insecureUrl li =+ [ (diag "terra-insecure-url" sp (tagName t <> " uses http://"))+ { diagFixes = [Fix "use https://" [TextEdit (Span (spanStart sp) (advancePos (spanStart sp) "http")) "https"] False]+ }+ | (sec, l@Line {lineBody = Tag t}) <- linesWithSection (liTree li),+ isPreambleLike sec,+ let key = T.toLower (T.dropWhileEnd isDigit (tagName t)),+ key `elem` ["url", "source", "patch", "bugurl", "vcs"],+ let sp = tagValueSpan l t,+ "http://" `T.isPrefixOf` renderFrags (tagValue t)+ ]
+ src/Rozbir/Lint/Types.hs view
@@ -0,0 +1,160 @@+-- | types shared by the lint rulesets: rules, diagnostics, fixes and config+module Rozbir.Lint.Types+ ( RuleSet (..),+ ruleSetName,+ parseRuleSet,+ RuleId,+ Rule (..),+ Diagnostic (..),+ Fix (..),+ LintInput (..),+ LintConfig (..),+ defaultConfig,+ Severity (..),+ parseSeverity,+ diag,+ linesWithSection,+ preambleLike,+ firstSpec,+ mainPackages,+ )+where++import Data.Aeson (ToJSON (..), object, (.=))+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Set (Set)+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Text qualified as T+import Rozbir.Edit (TextEdit)+import Rozbir.Eval.Types (Severity (..), Target)+import Rozbir.Spec (Package, Spec, mainPackage)+import Rozbir.Syntax++-- | a group of rules turned on together+data RuleSet+ = -- | broken specs and problems rpm itself trips on, on by default+ Core+ | -- | rpmlint's spec checks, on by default+ Rpmlint+ | -- | Terra's packaging conventions, off by default+ Terra+ deriving stock (Eq, Ord, Show, Enum, Bounded)++-- | the name used in config, like @rpmlint@+ruleSetName :: RuleSet -> Text+ruleSetName = \case+ Core -> "core"+ Rpmlint -> "rpmlint"+ Terra -> "terra"++-- | parse a ruleset name, ignoring case and surrounding spaces+parseRuleSet :: Text -> Maybe RuleSet+parseRuleSet t = lookup (T.toLower (T.strip t)) [(ruleSetName r, r) | r <- [minBound .. maxBound]]++-- | parse @info@, @warn@, @warning@ or @error@, ignoring case+parseSeverity :: Text -> Maybe Severity+parseSeverity t = case T.toLower (T.strip t) of+ "info" -> Just Info+ "warn" -> Just Warn+ "warning" -> Just Warn+ "error" -> Just Error+ _ -> Nothing++-- | a rule's id, like @hardcoded-path@+type RuleId = Text++-- | a suggested change that resolves a diagnostic+data Fix = Fix+ { -- | a short label, like @use %global@+ fixTitle :: !Text,+ -- | edits to the original source+ fixEdits :: ![TextEdit],+ -- | True if it's fine to apply without review+ fixSafe :: !Bool+ }+ deriving stock (Eq, Show)++instance ToJSON Fix where+ toJSON Fix {..} = object ["title" .= fixTitle, "edits" .= fixEdits, "safe" .= fixSafe]++-- | one finding+data Diagnostic = Diagnostic+ { diagRule :: !RuleId,+ -- | how serious it is, after config overrides+ diagSeverity :: !Severity,+ diagSpan :: !Span,+ diagMessage :: !Text,+ diagFixes :: ![Fix]+ }+ deriving stock (Eq, Show)++instance ToJSON Diagnostic where+ toJSON Diagnostic {..} =+ object+ [ "rule" .= diagRule,+ "severity" .= diagSeverity,+ "span" .= diagSpan,+ "message" .= diagMessage,+ "fixes" .= diagFixes+ ]++-- | what rules look at+data LintInput = LintInput+ { liSource :: !Text,+ liTree :: !Tree,+ -- | the spec resolved for each target+ liSpecs :: ![(Target, Spec)]+ }++-- | a lint check+data Rule = Rule+ { -- | unique id, used in config and ignore comments+ ruleId :: !RuleId,+ ruleSet :: !RuleSet,+ -- | severity unless config overrides it+ ruleSeverity :: !Severity,+ ruleDoc :: !Text,+ -- | find problems. the severity it sets is replaced by the configured one.+ ruleCheck :: LintInput -> [Diagnostic]+ }++-- | which rules run and how serious they are+data LintConfig = LintConfig+ { lcRuleSets :: !(Set RuleSet),+ -- | per-rule severity. Nothing turns a rule off, and a severity turns it+ -- on even if its ruleset isn't enabled.+ lcOverrides :: !(Map RuleId (Maybe Severity))+ }+ deriving stock (Eq, Show)++-- | core and rpmlint rules, no overrides+defaultConfig :: LintConfig+defaultConfig = LintConfig (Set.fromList [Core, Rpmlint]) Map.empty++-- | a diagnostic without fixes. its severity is replaced by the configured one.+diag :: RuleId -> Span -> Text -> Diagnostic+diag r sp msg = Diagnostic r Warn sp msg []++-- | every line with the section it's in. Nothing is the main preamble, and a+-- header line belongs to its own section.+linesWithSection :: Tree -> [(Maybe SectionKind, Line)]+linesWithSection tree = go Nothing (treeLines tree)+ where+ go _ [] = []+ go sec (l : ls) = case lineBody l of+ Header h -> (Just (secKind h), l) : go (Just (secKind h)) ls+ _ -> (sec, l) : go sec ls++-- | True for the main preamble and @%package@ sections+preambleLike :: Maybe SectionKind -> Bool+preambleLike = isPreambleLike++-- | the spec for the first target, if there is one+firstSpec :: LintInput -> [Spec]+firstSpec li = take 1 (map snd (liSpecs li))++-- | the main package of each target's spec+mainPackages :: LintInput -> [Package]+mainPackages li = [p | (_, s) <- liSpecs li, Just p <- [mainPackage s]]
+ src/Rozbir/MacroFile.hs view
@@ -0,0 +1,74 @@+-- | parse rpm macro files such as the ones in @\/usr\/lib\/rpm\/macros.d@,+-- without reading them from disk.+module Rozbir.MacroFile+ ( MacroFileEntry (..),+ parseMacroFile,+ toDefinitions,+ )+where++import Data.Text (Text)+import Data.Text qualified as T+import Rozbir.Syntax (Name)+import Rozbir.Syntax.Parse (isBlankChar, isNameChar)++-- | one macro definition from a macro file+data MacroFileEntry = MacroFileEntry+ { mfName :: !Name,+ -- | options of a parametric macro, without the parentheses+ mfOpts :: !(Maybe Text),+ -- | the body, unexpanded. continuation lines keep their backslashes and newlines.+ mfBody :: !Text,+ -- | the line the definition starts on, counting from 1+ mfLine :: !Int+ }+ deriving stock (Eq, Show)++-- | find every definition in a macro file. lines that don't start with @%@ are skipped, and so are definitions with an empty body.+parseMacroFile :: Text -> [MacroFileEntry]+parseMacroFile = go 1 . T.splitOn "\n"+ where+ go _ [] = []+ go n (l : ls) =+ let stripped = T.dropWhile isBlankChar l+ in case T.uncons stripped of+ Just ('%', _) ->+ let (taken, rest) = continuation (scan (0, 0, 0) (dropCr l)) [dropCr l] ls+ joined = T.intercalate "\n" taken+ in maybe id (:) (entry n (T.drop 1 (T.dropWhile isBlankChar joined))) (go (n + length taken) rest)+ _ -> go (n + 1) ls+ dropCr t = maybe t id (T.stripSuffix "\r" t)+ continuation st acc ls+ | done st (last acc) = (acc, ls)+ | otherwise = case ls of+ [] -> (acc, [])+ x : xs -> let x' = dropCr x in continuation (scan st x') (acc <> [x']) xs+ done (pc, bc, xc) lastLine = pc == 0 && bc == 0 && xc == 0 && not ("\\" `T.isSuffixOf` lastLine)+ scan st = fst . T.foldl' step (st, False)+ where+ step ((pc, bc, xc), pending) c+ | pending = case c of+ '{' -> ((pc, bc + 1, xc), False)+ '(' -> ((pc + 1, bc, xc), False)+ '[' -> ((pc, bc, xc + 1), False)+ _ -> step ((pc, bc, xc), False) c+ | otherwise = case c of+ '%' -> ((pc, bc, xc), True)+ '{' | bc > 0 -> ((pc, bc + 1, xc), False)+ '}' | bc > 0 -> ((pc, bc - 1 :: Int, xc), False)+ '(' | pc > 0 -> ((pc + 1, bc, xc), False)+ ')' | pc > 0 -> ((pc - 1 :: Int, bc, xc), False)+ '[' | xc > 0 -> ((pc, bc, xc + 1), False)+ ']' | xc > 0 -> ((pc, bc, xc - 1 :: Int), False)+ _ -> ((pc, bc, xc), False)+ entry n t =+ let (name, afterName) = T.span isNameChar t+ (opts, afterOpts) = case T.stripPrefix "(" afterName of+ Just inner | (o, rest) <- T.break (== ')') inner, not (T.null rest) -> (Just o, T.drop 1 rest)+ _ -> (Nothing, afterName)+ body = T.dropWhile isBlankChar afterOpts+ in if T.null name || T.null body then Nothing else Just (MacroFileEntry name opts body n)++-- | turn entries into the tuples 'Rozbir.Eval.withMacroFile' takes, tagged with the file they came from+toDefinitions :: FilePath -> [MacroFileEntry] -> [(Name, Maybe Text, Text, FilePath, Int)]+toDefinitions path = map (\MacroFileEntry {..} -> (mfName, mfOpts, mfBody, path, mfLine))
+ src/Rozbir/Query.hs view
@@ -0,0 +1,203 @@+-- | answers to common questions about a spec: name, EVR, sources, patches,+-- bconds, dependencies and which macros feed @Version:@.+module Rozbir.Query+ ( Resolved (..),+ resolvedToMaybe,+ tagText,+ name,+ evr,+ version,+ versionInputs,+ macroReferences,+ definitions,+ subpackages,+ sources,+ patches,+ bconds,+ buildRequires,+ dependencies,+ splitDeps,+ )+where++import Data.Char (isSpace)+import Data.List (nub)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (isNothing)+import Data.Text (Text)+import Data.Text qualified as T+import GHC.Generics (Generic)+import Rozbir.Eval.Builtin (builtinNames, preludeMacros)+import Rozbir.Eval.Types+import Rozbir.Spec+import Rozbir.Syntax+import Rozbir.Version (EVR (..))+import Text.Read (readMaybe)++-- | an answer, or the reasons it couldn't be worked out+data Resolved a+ = -- | the value is known+ Resolved a+ | -- | the value depends on something rozbir can't evaluate, is missing, or+ -- differs between branches+ Unresolved [Reason]+ deriving stock (Eq, Show, Functor, Generic)++instance Applicative Resolved where+ pure = Resolved+ Resolved f <*> Resolved a = Resolved (f a)+ Unresolved a <*> Unresolved b = Unresolved (a <> b)+ Unresolved a <*> _ = Unresolved a+ _ <*> Unresolved b = Unresolved b++-- | drop the reasons+resolvedToMaybe :: Resolved a -> Maybe a+resolvedToMaybe = \case+ Resolved a -> Just a+ Unresolved _ -> Nothing++-- | a tag's text. 'Unresolved' if it's missing, didn't fully expand, or is+-- set to different values in different branches.+tagText :: Text -> Package -> Resolved Text+tagText key pkg = case packageTags key pkg of+ [] -> Unresolved [Undefined key]+ entries ->+ let values = map (teValue . locValue) entries+ texts = nub [T.strip t | Just t <- map knownText values]+ in case (texts, filter (isNothing . knownText) values) of+ ([t], []) -> Resolved t+ (_, unknowns@(_ : _)) -> Unresolved (concatMap reasons unknowns)+ _ -> Unresolved [Ambiguous key]++-- | the main package's Name+name :: Spec -> Resolved Text+name spec = maybe (Unresolved [Undefined "name"]) (tagText "name") (mainPackage spec)++-- | the main package's Version+version :: Spec -> Resolved Text+version spec = maybe (Unresolved [Undefined "version"]) (tagText "version") (mainPackage spec)++-- | the main package's epoch, version and release. epoch defaults to 0.+evr :: Spec -> Resolved EVR+evr spec = case mainPackage spec of+ Nothing -> Unresolved [Undefined "name"]+ Just pkg ->+ EVR+ <$> epoch pkg+ <*> tagText "version" pkg+ <*> tagText "release" pkg+ where+ epoch pkg = case packageTags "epoch" pkg of+ [] -> Resolved 0+ _ -> tagText "epoch" pkg >>=. \t -> maybe (Unresolved [Failed ("bad epoch " <> t)]) Resolved (readMaybe (T.unpack t))+ r >>=. f = case r of+ Resolved a -> f a+ Unresolved rs -> Unresolved rs++-- | names of macros referenced in fragments, including inside arguments,+-- @%(...)@ and @%[...]@+macroReferences :: [Frag] -> [Name]+macroReferences = concatMap frag+ where+ frag = \case+ Macro m -> ref m+ _ -> []+ ref = \case+ Bare _ n -> [n]+ Braced _ n arg -> n : maybe [] argRefs arg+ Shell fs -> macroReferences fs+ Expr fs -> macroReferences fs+ _ -> []+ argRefs = \case+ ColonArg fs -> macroReferences fs+ SpaceArg fs -> macroReferences fs++-- | every @%global@ and @%define@ by name, in source order+definitions :: Tree -> Map Name [DefineLine]+definitions tree =+ Map.fromListWith+ (flip (<>))+ [ (defName d, [d])+ | Line {lineBody = Define d} <- treeLines tree,+ defKind d `elem` [DefGlobal, DefDefine]+ ]++-- | macros that @Version:@ depends on through @%global@ and @%define@,+-- skipping rpm builtins+versionInputs :: Tree -> [Name]+versionInputs tree = go [] roots+ where+ defs = definitions tree+ roots =+ concat+ [ macroReferences (tagValue t)+ | Line {lineBody = Tag t} <- treeLines tree,+ T.toLower (tagName t) == "version"+ ]+ ignored = builtinNames <> [n | (n, _, _) <- preludeMacros]+ go seen = \case+ [] -> reverse seen+ n : rest+ | n `elem` seen || n `elem` ignored || T.null n -> go seen rest+ | otherwise ->+ let more = concatMap (macroReferences . defBody) (Map.findWithDefault [] n defs)+ in go (n : seen) (rest <> more)++-- | every package except the main one+subpackages :: Spec -> [Package]+subpackages = filter ((/= MainKey) . pkgKey) . specPackages++-- | Source tags+sources :: Spec -> [Located SourceEntry]+sources = filter (not . srcPatch . locValue) . specSources++-- | Patch tags+patches :: Spec -> [Located SourceEntry]+patches = filter (srcPatch . locValue) . specSources++-- | bcond declarations+bconds :: Spec -> [Located Bcond]+bconds = specBconds++-- | one entry per dependency in a tag such as @requires@. values that didn't+-- fully expand are skipped.+dependencies :: Text -> Package -> [Located Text]+dependencies key pkg =+ [ Located dep (locSpan l) (locGuard l)+ | l <- packageTags key pkg,+ Just t <- [knownText (teValue (locValue l))],+ dep <- splitDeps t+ ]++-- | the main package's BuildRequires, one entry per dependency+buildRequires :: Spec -> [Located Text]+buildRequires spec = maybe [] (dependencies "buildrequires") (mainPackage spec)++-- | split a dependency list on spaces and commas, keeping @foo >= 1.0@ and+-- rich dependencies in parentheses together+splitDeps :: Text -> [Text]+splitDeps = join . tokens+ where+ tokens t = case T.uncons (T.dropWhile sepChar t) of+ Nothing -> []+ Just ('(', _) ->+ let (tok, rest) = balanced 0 0 (T.dropWhile sepChar t)+ in tok : tokens rest+ Just _ ->+ let (tok, rest) = T.break sepChar (T.dropWhile sepChar t)+ in tok : tokens rest+ sepChar c = isSpace c || c == ','+ balanced :: Int -> Int -> Text -> (Text, Text)+ balanced depth n t = case T.uncons (T.drop n t) of+ Nothing -> (t, "")+ Just (c, _)+ | c == '(' -> balanced (depth + 1) (n + 1) t+ | c == ')' && depth == 1 -> T.splitAt (n + 1) t+ | c == ')' -> balanced (depth - 1) (n + 1) t+ | otherwise -> balanced depth (n + 1) t+ operators = ["<", "<=", "=", "==", ">=", ">"]+ join = \case+ a : op : b : rest | op `elem` operators -> (a <> " " <> op <> " " <> b) : join rest+ a : rest -> a : join rest+ [] -> []
+ src/Rozbir/Spec.hs view
@@ -0,0 +1,636 @@+-- | the semantic model of a spec for one build target. when an @%if@ can't+-- be decided, both branches end up in the model, tagged with a 'Guard'.+module Rozbir.Spec+ ( Spec (..),+ Package (..),+ PackageKey (..),+ TagEntry (..),+ SectionContent (..),+ SourceEntry (..),+ Bcond (..),+ Condition (..),+ Assumption (..),+ Guard,+ Located (..),+ ResolveOptions (..),+ defaultOptions,+ resolve,+ resolveWith,+ knownTags,+ tagDefinesMacro,+ deprecatedTags,+ mainPackage,+ packageTags,+ packageTag,+ sectionArgWords,+ )+where++import Control.DeepSeq (NFData)+import Control.Monad (unless, when)+import Control.Monad.State.Strict (StateT, execStateT, get, gets, lift, modify', put)+import Data.Char (isDigit)+import Data.List qualified as L+import Data.List.NonEmpty qualified as NE+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe, isJust)+import Data.Text (Text)+import Data.Text qualified as T+import GHC.Generics (Generic)+import Rozbir.Changelog (Entry, parseEntries)+import Rozbir.Eval+import Rozbir.Eval.Builtin (posixBasename)+import Rozbir.Syntax+import Rozbir.Syntax.Parse (parseFrags, parseLines)+import Rozbir.Syntax.Render (renderBody)+import Text.Read (readMaybe)++-- | the item is in one branch of an @%if@ that couldn't be decided+data Assumption = Assumption+ { -- | span of the @%if@ line that opens the block+ assumeIf :: !Span,+ -- | branch index, 0 for the @%if@, then one per @%elif@ or @%else@+ assumeBranch :: !Int+ }+ deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++-- | the undecided @%if@ branches an item is in, innermost first. empty means+-- it always applies.+type Guard = [Assumption]++-- | a value with the source span it came from and the guard it's under+data Located a = Located+ { locValue :: !a,+ -- | span of the line it came from+ locSpan :: !Span,+ -- | the undecided branches it's in+ locGuard :: !Guard+ }+ deriving stock (Eq, Show, Generic, Functor)+ deriving anyclass (NFData)++-- | identifies a package within a t'Spec'+data PackageKey+ = -- | the main package+ MainKey+ | -- | a subpackage, keyed by its full expanded name such as @foo-devel@+ SubKey !Text+ deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++-- | a preamble tag after macro expansion+data TagEntry = TagEntry+ { -- | lowercase name without a Source or Patch number, so @Source0@ is+ -- @source@+ teKey :: !Text,+ -- | the tag name as written+ teName :: !Text,+ -- | the qualifier as written, such as @(post)@ in @Requires(post)@+ teQualifier :: !(Maybe Text),+ -- | the expanded value+ teValue :: !Value,+ -- | the original line, or Nothing when a macro expanded to this tag+ teRaw :: !(Maybe TagLine)+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | the main package or a @%package@ subpackage with its preamble tags+data Package = Package+ { pkgKey :: !PackageKey,+ -- | the expanded name+ pkgName :: !Value,+ -- | span of the @%package@ line, Nothing for the main package+ pkgHeader :: !(Maybe Span),+ -- | the guard of the @%package@ line+ pkgGuard :: !Guard,+ -- | tags in source order+ pkgTags :: ![Located TagEntry],+ -- | True when a preamble line didn't fully expand, so some tags may be+ -- missing from 'pkgTags'+ pkgOpaque :: !Bool+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | a section such as @%prep@, @%files@ or a scriptlet, with its expanded body+data SectionContent = SectionContent+ { scKind :: !SectionKind,+ -- | the package the section belongs to+ scPackage :: !PackageKey,+ -- | the expanded name of that package+ scPackageName :: !Value,+ -- | the expanded arguments after the section keyword+ scArgs :: !Value,+ -- | span of the header line+ scHeader :: !Span,+ -- | the guard of the header line+ scGuard :: !Guard,+ -- | expanded body lines in source order+ scLines :: ![Located Value],+ -- | the CST lines behind 'scLines', in source order+ scRaw :: ![Line]+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | a numbered Source or Patch tag+data SourceEntry = SourceEntry+ { -- | True for Patch, False for Source+ srcPatch :: !Bool,+ -- | the number, or the one rpm assigns when the tag has none+ srcNumber :: !Int,+ -- | whether the number was written in the tag name+ srcExplicit :: !Bool,+ -- | the expanded URL or file name+ srcValue :: !Value+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | a @%bcond@, @%bcond_with@ or @%bcond_without@ declaration+data Bcond = Bcond+ { -- | the name, @foo@ in @%bcond foo 1@+ bcName :: !Text,+ -- | whether the bcond is on, 'Unknown' if that depends on unknown macros+ bcEnabled :: !Tri+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | the result of evaluating one conditional line+data Condition = Condition+ { -- | span of the conditional line+ condLineSpan :: !Span,+ -- | the condition's own result, ignoring earlier branches+ condResult :: !Tri+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | everything rozbir knows about a spec for one target+data Spec = Spec+ { -- | the main package first, then subpackages in declaration order+ specPackages :: ![Package],+ -- | sections in source order+ specSections :: ![SectionContent],+ -- | Source and Patch tags in source order+ specSources :: ![Located SourceEntry],+ -- | bcond declarations in source order+ specBconds :: ![Located Bcond],+ -- | parsed @%changelog@ entries in the order written+ specChangelog :: ![Entry],+ -- | @%changelog@ lines that didn't parse, with a message+ specChangelogProblems :: ![(Span, Text)],+ -- | conditional lines that were evaluated. lines after a branch known to+ -- be taken are skipped.+ specConditions :: ![Condition],+ -- | the expanded argument of each @%include@+ specIncludes :: ![Located Value],+ -- | the macro environment at the end of the spec+ specEnv :: !Env,+ -- | evaluation warnings and errors, including @%include@ files not read+ specMessages :: ![EvalMessage],+ -- | macros nothing defined. only collected when system macros are loaded.+ specUndefined :: ![(Name, Span)]+ }+ deriving stock (Show, Generic)++-- | inputs to 'resolveWith'+data ResolveOptions = ResolveOptions+ { -- | the starting macros, from 'newEnv' or 'Rozbir.IO.loadSystemMacros'+ roEnv :: !Env,+ roTarget :: !Target,+ -- | @%include@ trees keyed by the argument as written. a missing include+ -- leaves what it defines unknown.+ roIncludes :: !(Map Text Tree)+ }++-- | an open environment without system macros, 'unknownTarget' and no includes+defaultOptions :: ResolveOptions+defaultOptions = ResolveOptions (newEnv False) unknownTarget Map.empty++-- | every preamble tag rpm accepts, as lowercase keys+knownTags :: [Text]+knownTags =+ [ "name",+ "version",+ "release",+ "epoch",+ "summary",+ "license",+ "sourcelicense",+ "distribution",+ "disturl",+ "vendor",+ "group",+ "packager",+ "url",+ "vcs",+ "source",+ "patch",+ "nosource",+ "nopatch",+ "excludearch",+ "exclusivearch",+ "excludeos",+ "exclusiveos",+ "icon",+ "provides",+ "requires",+ "recommends",+ "suggests",+ "supplements",+ "enhances",+ "prereq",+ "conflicts",+ "obsoletes",+ "prefixes",+ "prefix",+ "buildroot",+ "buildarchitectures",+ "buildarch",+ "buildconflicts",+ "buildoption",+ "buildprereq",+ "buildrequires",+ "buildsystem",+ "autoreqprov",+ "autoreq",+ "autoprov",+ "docdir",+ "disttag",+ "bugurl",+ "translationurl",+ "upstreamreleases",+ "orderwithrequires",+ "removepathpostfixes",+ "modularitylabel"+ ]++-- | whether a tag also defines a macro, like @Version:@ defines @%version@+tagDefinesMacro :: Text -> Bool+tagDefinesMacro k =+ k+ `elem` [ "name",+ "version",+ "release",+ "epoch",+ "summary",+ "license",+ "sourcelicense",+ "distribution",+ "disturl",+ "vendor",+ "group",+ "packager",+ "url",+ "vcs",+ "prefixes",+ "prefix",+ "buildsystem",+ "disttag",+ "bugurl",+ "translationurl",+ "upstreamreleases",+ "removepathpostfixes",+ "modularitylabel"+ ]++-- | tags current rpm ignores or has replaced+deprecatedTags :: [Text]+deprecatedTags = ["prereq", "buildprereq", "buildroot", "group", "packager", "vendor", "distribution"]++canonicalTag :: Text -> (Text, Maybe Int)+canonicalTag raw =+ let lower = T.toLower raw+ digits = T.takeWhileEnd isDigit lower+ base = T.dropEnd (T.length digits) lower+ in if base `elem` ["source", "patch", "nosource", "nopatch"]+ then (base, if T.null digits then Nothing else readMaybe (T.unpack digits))+ else (lower, Nothing)++-- | the main package. 'resolve' always creates one.+mainPackage :: Spec -> Maybe Package+mainPackage = L.find ((== MainKey) . pkgKey) . specPackages++-- | every tag with the given lowercase key, in source order+packageTags :: Text -> Package -> [Located TagEntry]+packageTags key = filter ((== key) . teKey . locValue) . pkgTags++-- | the first tag with the given lowercase key+packageTag :: Text -> Package -> Maybe (Located TagEntry)+packageTag key = L.find ((== key) . teKey . locValue) . pkgTags++data Current = Current+ { curKind :: !(Maybe SectionKind),+ curPackage :: !PackageKey,+ curIndex :: !(Maybe Int)+ }++data RS = RS+ { rsCurrent :: !Current,+ rsGuard :: !Guard,+ rsPackages :: ![Package],+ rsSections :: ![SectionContent],+ rsSources :: ![Located SourceEntry],+ rsBconds :: ![Located Bcond],+ rsConditions :: ![Condition],+ rsIncludes :: ![Located Value],+ rsAutoSource :: !Int,+ rsAutoPatch :: !Int,+ rsIncludeMap :: !(Map Text Tree),+ rsIncludeDepth :: !Int+ }++type R = StateT RS Eval++-- | resolve a tree for one target, without @%include@ files. it never fails.+-- unknown values come back 'Opaque'.+resolve :: Env -> Target -> Tree -> Spec+resolve env target = resolveWith (ResolveOptions env target Map.empty)++-- | like 'resolve', but takes @%include@ trees too+resolveWith :: ResolveOptions -> Tree -> Spec+resolveWith ResolveOptions {..} tree =+ let env0 = withTarget roTarget roEnv+ start =+ RS+ { rsCurrent = Current Nothing MainKey Nothing,+ rsGuard = [],+ rsPackages = [Package MainKey mempty Nothing [] [] False],+ rsSections = [],+ rsSources = [],+ rsBconds = [],+ rsConditions = [],+ rsIncludes = [],+ rsAutoSource = -1,+ rsAutoPatch = -1,+ rsIncludeMap = roIncludes,+ rsIncludeDepth = 0+ }+ (rs, st) = runEval (initialState env0) (execStateT (nodes (treeNodes tree)) start)+ sections = reverse (map finishSection (rsSections rs))+ changelogLines =+ [ (lineSpan l, renderBody (lineBody l))+ | s <- sections,+ scKind s == SChangelog,+ l <- scRaw s,+ not (macroLine l)+ ]+ macroLine l = case lineBody l of+ Body (Macro _ : _) -> True+ _ -> False+ (entries, problems) = parseEntries changelogLines+ in Spec+ { specPackages = map finishPackage (reverse (rsPackages rs)),+ specSections = sections,+ specSources = reverse (rsSources rs),+ specBconds = reverse (rsBconds rs),+ specChangelog = entries,+ specChangelogProblems = problems,+ specConditions = reverse (rsConditions rs),+ specIncludes = reverse (rsIncludes rs),+ specEnv = esEnv st,+ specMessages = reverse (esMessages st),+ specUndefined = reverse (esUndefined st)+ }+ where+ finishPackage p = p {pkgTags = reverse (pkgTags p)}+ finishSection s = s {scLines = reverse (scLines s), scRaw = reverse (scRaw s)}++nodes :: [Node] -> R ()+nodes = mapM_ node++node :: Node -> R ()+node = \case+ NLine l -> line l+ NSection s -> line (sectionLine s) >> nodes (sectionNodes s)+ NCond block -> conditional block++conditional :: CondBlock -> R ()+conditional (CondBlock branches _) = do+ env0 <- lift getEnv+ guard0 <- gets rsGuard+ let ifSpan = lineSpan (branchLine (NE.head branches))+ let go _ collected [] = finish collected True+ go prior collected ((i, Branch {..}) : more) = do+ lift (putEnv env0)+ t <- lift (atSpan (lineSpan branchLine) (evalCond branchCond))+ modify' (\rs -> rs {rsConditions = Condition (lineSpan branchLine) t : rsConditions rs})+ let active = triAnd (triNot prior) t+ case active of+ No -> go prior collected more+ Yes -> do+ nodes branchNodes+ env <- lift getEnv+ finish (env : collected) False+ Unknown _ -> do+ modify' (\rs -> rs {rsGuard = Assumption ifSpan i : guard0})+ nodes branchNodes+ modify' (\rs -> rs {rsGuard = guard0})+ env <- lift getEnv+ go (triOr prior t) (env : collected) more+ finish collected noneMayRun = do+ let candidates = if noneMayRun then env0 : collected else collected+ case candidates of+ [] -> lift (putEnv env0)+ e : es -> lift (putEnv (L.foldl' mergeEnvs e es))+ go No [] (zip [0 ..] (NE.toList branches))++line :: Line -> R ()+line l = do+ rs <- get+ let cur = rsCurrent rs+ sp = lineSpan l+ case lineBody l of+ Blank t -> record l (known t)+ Comment indent fs -> do+ v <- lift (atSpan sp (expandAt 0 fs))+ when (keepsComments (curKind cur)) (record l (known indent <> v))+ Tag t -> tag l t Nothing+ Define d -> do+ v <- lift (atSpan sp (expandAt 0 (parseFrags (renderBody (Define d)))))+ when (defKind d `elem` [DefBcond, DefBcondWith, DefBcondWithout]) $ do+ enabled <- lift (isDefined ("with_" <> defName d))+ g <- gets rsGuard+ modify' (\s -> s {rsBconds = Located (Bcond (defName d) enabled) sp g : rsBconds s})+ unless (valueNull v) (record l v)+ Cond _ -> pure ()+ Header h -> header l h+ Include _ fs -> include l fs+ Body fs -> do+ v <- lift (atSpan sp (expandAt 0 fs))+ if isPreambleLike (curKind cur) || producesHeader v+ then reclassify l v+ else record l v+ Bogus _ -> pure ()++producesHeader :: Value -> Bool+producesHeader v+ | "\n" `T.isInfixOf` t || "%" `T.isPrefixOf` t = any isHeader (fst (parseLines (Just SBuild) t))+ | otherwise = False+ where+ t = showValue v+ isHeader x = case lineBody x of+ Header _ -> True+ _ -> False++keepsComments :: Maybe SectionKind -> Bool+keepsComments = \case+ Just k -> isBuildSection k || isScriptSection k+ Nothing -> False++record :: Line -> Value -> R ()+record l v = do+ rs <- get+ case curIndex (rsCurrent rs) of+ Nothing -> pure ()+ Just _ -> case rsSections rs of+ s : rest -> put rs {rsSections = s {scLines = Located v (lineSpan l) (rsGuard rs) : scLines s, scRaw = l : scRaw s} : rest}+ [] -> pure ()++reclassify :: Line -> Value -> R ()+reclassify l v = mapM_ one (valueLines v)+ where+ one lv+ | T.all (`elem` [' ', '\t', '\r']) (showValue lv) = pure ()+ | otherwise = do+ cur <- gets rsCurrent+ when (not (isKnown lv) && isPreambleLike (curKind cur)) markOpaque+ case fst (parseLines (curKind cur) (showValue lv)) of+ x : _ -> case lineBody x of+ Tag tl -> case dropKnownPrefix (T.length (tagPrefix tl)) lv of+ Just value -> tag l tl (Just (trimValue value))+ Nothing -> markOpaque+ Header h -> header l h+ Body _ -> record l lv+ _ -> pure ()+ [] -> pure ()+ markOpaque = do+ pkgK <- gets (curPackage . rsCurrent)+ modify' (\s -> s {rsPackages = map (\p -> if pkgKey p == pkgK then p {pkgOpaque = True} else p) (rsPackages s)})+ tagPrefix TagLine {..} = tagIndent <> tagName <> maybe "" (\q -> qualGap q <> qualRaw q) tagQualifier <> tagSep+ trimValue = mapKnown T.stripEnd++dropKnownPrefix :: Int -> Value -> Maybe Value+dropKnownPrefix n (Value ps) = go n ps+ where+ go 0 rest = Just (Value rest)+ go k (Known t : rest)+ | T.length t > k = Just (Value (Known (T.drop k t) : rest))+ | otherwise = go (k - T.length t) rest+ go _ _ = Nothing++tag :: Line -> TagLine -> Maybe Value -> R ()+tag l t@TagLine {..} expandedFrom = do+ let sp = lineSpan l+ (key, number) = canonicalTag tagName+ value <- case expandedFrom of+ Just v -> pure v+ Nothing -> lift (atSpan sp (expandAt 0 tagValue))+ rs <- get+ let entry = TagEntry key tagName (qualRaw <$> tagQualifier) value (if isJust expandedFrom then Nothing else Just t)+ located = Located entry sp (rsGuard rs)+ pkgK = curPackage (rsCurrent rs)+ put rs {rsPackages = map (\p -> if pkgKey p == pkgK then p {pkgTags = located : pkgTags p} else p) (rsPackages rs)}+ when (tagDefinesMacro key) $ lift $ atSpan sp $ do+ let def = MacroDef Nothing (BodyValue value) (OriginTag sp) 0 False+ pushMacro key def+ when (key == "name" && pkgK == MainKey) $+ modify' (\s -> s {rsPackages = map (\p -> if pkgKey p == MainKey then p {pkgName = value} else p) (rsPackages s)})+ when (key `elem` ["source", "patch"]) (source sp key number value)++source :: Span -> Text -> Maybe Int -> Value -> R ()+source sp key number value = do+ rs <- get+ let isPatch = key == "patch"+ auto = if isPatch then rsAutoPatch rs else rsAutoSource rs+ n = fromMaybe (auto + 1) number+ auto' = max auto n+ prefix = if isPatch then "PATCH" else "SOURCE"+ body = case knownText value of+ Just t -> BodyRaw ("%{_sourcedir}/" <> posixBasename (T.strip t))+ Nothing -> BodyOpaque (case reasons value of r : _ -> r; [] -> Failed "unknown")+ put+ rs+ { rsSources = Located (SourceEntry isPatch n (isJust number) value) sp (rsGuard rs) : rsSources rs,+ rsAutoSource = if isPatch then rsAutoSource rs else auto',+ rsAutoPatch = if isPatch then auto' else rsAutoPatch rs+ }+ lift (pushMacro (prefix <> T.pack (show n)) (MacroDef Nothing body (OriginTag sp) 0 False))+ lift (pushMacro (prefix <> T.pack (show n) <> "_URL") (MacroDef Nothing (BodyValue value) (OriginTag sp) 0 False))++-- | the package name in a section header's arguments. the 'Bool' is True for a+-- full @-n@ name and False for a suffix to the main package's name.+sectionArgWords :: SectionKind -> [Value] -> (Maybe Value, Bool)+sectionArgWords kind = go Nothing False+ where+ withValue = case kind of+ SFiles -> ["-f"]+ SDescription -> ["-l"]+ k | isScriptSection k -> ["-p", "-P"]+ _ -> []+ is w = knownText w+ go name absolute = \case+ [] -> (name, absolute)+ w : _ | is w == Just "--" -> (name, absolute)+ w : n : rest | is w == Just "-n" -> go (Just n) True rest+ w : _ : rest | Just o <- is w, o `elem` withValue -> go name absolute rest+ w : rest | Just o <- is w, "-" `T.isPrefixOf` o -> go name absolute rest+ w : rest -> case name of+ Nothing -> go (Just w) False rest+ Just _ -> go name absolute rest++header :: Line -> SectionHeader -> R ()+header l h = do+ let sp = lineSpan l+ kind = secKind h+ expandedArgs <- lift (atSpan sp (expandAt 0 (secArgs h)))+ let (args, extraLines) = case valueLines expandedArgs of+ firstLine : more -> (firstLine, more)+ [] -> (mempty, [])+ mainName <- lift (atSpan sp (expandText "%{name}"))+ rs <- get+ let ws = valueWords args+ (named, absolute) =+ if isBuildSection kind || kind `elem` [SChangelog, SPatchlist, SSourcelist, SEnd]+ then (Nothing, False)+ else sectionArgWords kind ws+ pkgValue = case named of+ Nothing -> mainName+ Just n+ | absolute -> n+ | otherwise -> mainName <> known "-" <> n+ pkgK = case named of+ Nothing -> MainKey+ Just _+ | isKnown pkgValue && pkgValue == mainName -> MainKey+ | otherwise -> SubKey (showValue pkgValue)+ section = SectionContent kind pkgK pkgValue args sp (rsGuard rs) [] []+ exists = any ((== pkgK) . pkgKey) (rsPackages rs)+ packages+ | kind == SPackage && not exists = Package pkgK pkgValue (Just sp) (rsGuard rs) [] False : rsPackages rs+ | otherwise = rsPackages rs+ put+ rs+ { rsCurrent = Current (Just kind) pkgK (Just (length (rsSections rs))),+ rsSections = section : rsSections rs,+ rsPackages = packages+ }+ mapM_ (record l) extraLines++include :: Line -> [Frag] -> R ()+include l fs = do+ let sp = lineSpan l+ v <- lift (atSpan sp (expandAt 0 fs))+ rs <- get+ put rs {rsIncludes = Located v sp (rsGuard rs) : rsIncludes rs}+ case knownText v >>= (\k -> Map.lookup (T.strip k) (rsIncludeMap rs)) of+ Just tree | rsIncludeDepth rs < 16 -> do+ modify' (\s -> s {rsIncludeDepth = rsIncludeDepth s + 1})+ nodes (treeNodes tree)+ modify' (\s -> s {rsIncludeDepth = rsIncludeDepth s - 1})+ _ -> lift (atSpan sp (message Warn ("%include " <> showValue v <> " wasn't read, so whatever it defines is unknown")))
+ src/Rozbir/Syntax.hs view
@@ -0,0 +1,493 @@+-- | the lossless syntax tree for spec files. every character of the input,+-- whitespace and line endings included, lives somewhere in a t'Tree', so+-- rendering it gives back the exact source.+module Rozbir.Syntax+ ( Name,+ Pos (..),+ Span (..),+ startPos,+ advancePos,+ pointSpan,+ spanContains,+ Line (..),+ LineBody (..),+ Frag (..),+ MacroRef (..),+ MacroArg (..),+ TagLine (..),+ Qualifier (..),+ DefineLine (..),+ DefineKind (..),+ CondLine (..),+ CondKind (..),+ isIfKind,+ isElifKind,+ SectionHeader (..),+ SectionKind (..),+ sectionKinds,+ sectionName,+ isScriptSection,+ isBuildSection,+ isPreambleLike,+ Node (..),+ Section (..),+ CondBlock (..),+ Branch (..),+ Tree (..),+ SyntaxError (..),+ treeLines,+ nodeLines,+ linesOfNodes,+ lineText,+ lineFullSpan,+ macroName,+ macroFlags,+ )+where++import Control.DeepSeq (NFData)+import Data.Aeson (ToJSON (..), object, (.=))+import Data.List.NonEmpty (NonEmpty)+import Data.Text (Text)+import Data.Text qualified as T+import GHC.Generics (Generic)++-- | a macro or tag name as written in the spec+type Name = Text++-- | a position in the source+data Pos = Pos+ { -- | offset from the start of the text, in characters+ posOffset :: !Int,+ -- | line number, starting at 0+ posLine :: !Int,+ -- | column in characters, starting at 0+ posCol :: !Int+ }+ deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++-- | a range of source text+data Span = Span+ { -- | the first character+ spanStart :: !Pos,+ -- | just past the last character+ spanEnd :: !Pos+ }+ deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON Pos where+ toJSON (Pos o l c) = object ["offset" .= o, "line" .= l, "column" .= c]++instance ToJSON Span where+ toJSON (Span s e) = object ["start" .= s, "end" .= e]++-- | the start of the text+startPos :: Pos+startPos = Pos 0 0 0++-- | move a position past some text+advancePos :: Pos -> Text -> Pos+advancePos = T.foldl' step+ where+ step (Pos o l c) = \case+ '\n' -> Pos (o + 1) (l + 1) 0+ _ -> Pos (o + 1) l (c + 1)++-- | an empty span at a position+pointSpan :: Pos -> Span+pointSpan p = Span p p++-- | whether a position is inside a span. both ends count, so a cursor right after the span is inside.+spanContains :: Span -> Pos -> Bool+spanContains (Span s e) p = posOffset s <= posOffset p && posOffset p <= posOffset e++-- | a piece of text that may contain macros+data Frag+ = Lit !Text+ | -- | @%%@, a literal percent sign+ Escape+ | Macro !MacroRef+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | a macro reference, kept exactly as written+data MacroRef+ = -- | @%name@ with its @?@ and @!@ flags. also covers arguments like @%1@, @%*@, @%#@ and @%-f@.+ Bare !Text !Name+ | -- | @%{name}@ with its flags and an optional argument+ Braced !Text !Name !(Maybe MacroArg)+ | -- | @%(...)@, a shell command+ Shell ![Frag]+ | -- | @%[...]@, an expression+ Expr ![Frag]+ | -- | @%{lua:...}@ with the raw Lua source+ Lua !Text+ | -- | a @%{@, @%(@ or @%[@ that is never closed, with the opening character and the rest of the text+ Unterminated !Char !Text+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | the argument of a braced macro+data MacroArg+ = -- | the text after the colon in @%{name:arg}@+ ColonArg ![Frag]+ | -- | the text after the name in @%{name arg}@, leading space included+ SpaceArg ![Frag]+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | the macro's name, @lua@ for Lua blocks. 'Nothing' for shell, expression and unterminated macros.+macroName :: MacroRef -> Maybe Name+macroName = \case+ Bare _ n -> Just n+ Braced _ n _ -> Just n+ Lua _ -> Just "lua"+ _ -> Nothing++-- | the @?@ and @!@ flags, empty when there are none+macroFlags :: MacroRef -> Text+macroFlags = \case+ Bare f _ -> f+ Braced f _ _ -> f+ _ -> ""++-- | one logical line. continuations and unclosed macros can make it span several physical lines.+data Line = Line+ { lineBody :: !LineBody,+ -- | the line ending, empty on a last line without one+ lineEol :: !Text,+ -- | where the body is, without the line ending+ lineSpan :: !Span+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | the kind of a line, with all of its text+data LineBody+ = -- | an empty or whitespace-only line+ Blank !Text+ | -- | a @#@ comment and its indentation. rpm expands macros in comments, so they are parsed.+ Comment !Text ![Frag]+ | -- | a preamble tag such as @Name:@+ Tag !TagLine+ | -- | @%global@, @%define@, @%undefine@ or a bcond+ Define !DefineLine+ | -- | a conditional such as @%if@ or @%endif@+ Cond !CondLine+ | -- | a section header such as @%build@+ Header !SectionHeader+ | -- | @%include@, with the indentation and keyword first+ Include !Text ![Frag]+ | -- | any other line, such as shell, a file list entry or a macro call in the preamble+ Body ![Frag]+ | -- | a preamble line that is none of the above. it also gets a @not-a-tag@ error.+ Bogus !Text+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | a tag line, split up so it can be rendered back exactly+data TagLine = TagLine+ { -- | whitespace before the name+ tagIndent :: !Text,+ -- | the name as written. rpm ignores case.+ tagName :: !Text,+ -- | a qualifier such as @(post)@+ tagQualifier :: !(Maybe Qualifier),+ -- | the colon and the whitespace around it+ tagSep :: !Text,+ tagValue :: ![Frag],+ -- | trailing whitespace+ tagTrailing :: !Text+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | a tag qualifier such as @Requires(post)@+data Qualifier = Qualifier+ { -- | whitespace between the tag name and the parenthesis+ qualGap :: !Text,+ -- | the qualifier with both parentheses+ qualRaw :: !Text+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | which keyword a define line uses+data DefineKind+ = DefGlobal+ | DefDefine+ | DefUndefine+ | DefBcond+ | DefBcondWith+ | DefBcondWithout+ deriving stock (Eq, Ord, Show, Enum, Bounded, Generic)+ deriving anyclass (NFData)++-- | a define line, split up so it can be rendered back exactly+data DefineLine = DefineLine+ { -- | whitespace before the keyword+ defIndent :: !Text,+ defKind :: !DefineKind,+ -- | the keyword as written, with the @%@+ defKeyword :: !Text,+ -- | whitespace before the name. for @%define@ it also holds dash options.+ defGap :: !Text,+ -- | the macro or bcond name+ defName :: !Name,+ -- | options of a parametric macro, without the parentheses. only for @%global@ and @%define@.+ defOpts :: !(Maybe Text),+ -- | the text in angle brackets after the name, without the brackets. only for @%global@ and @%define@.+ defMods :: !(Maybe Text),+ -- | whitespace between the name and the body+ defSep :: !Text,+ -- | the body, unexpanded+ defBody :: ![Frag],+ -- | trailing whitespace+ defTrailing :: !Text+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | which conditional keyword a line uses+data CondKind+ = CIf+ | CIfArch+ | CIfNArch+ | CIfOs+ | CIfNOs+ | CElif+ | CElifArch+ | CElifOs+ | CElse+ | CEndif+ deriving stock (Eq, Ord, Show, Enum, Bounded, Generic)+ deriving anyclass (NFData)++-- | whether the keyword opens a new block+isIfKind :: CondKind -> Bool+isIfKind k = k `elem` [CIf, CIfArch, CIfNArch, CIfOs, CIfNOs]++-- | whether the keyword is one of the @%elif@ forms+isElifKind :: CondKind -> Bool+isElifKind k = k `elem` [CElif, CElifArch, CElifOs]++-- | a conditional line+data CondLine = CondLine+ { -- | whitespace before the keyword+ condIndent :: !Text,+ condKind :: !CondKind,+ -- | the keyword as written, with the @%@+ condKeyword :: !Text,+ -- | everything after the keyword, leading whitespace included+ condArgs :: ![Frag]+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | the sections rpm knows+data SectionKind+ = SPackage+ | SDescription+ | SPrep+ | -- | @%conf@, new in rpm 4.18+ SConf+ | SGenerateBuildRequires+ | SBuild+ | SInstall+ | SCheck+ | SClean+ | SFiles+ | SChangelog+ | SPre+ | SPost+ | SPreun+ | SPostun+ | SPretrans+ | SPosttrans+ | SPreuntrans+ | SPostuntrans+ | SVerifyscript+ | STriggerprein+ | -- | @%triggerin@, also written @%trigger@+ STriggerin+ | STriggerun+ | STriggerpostun+ | -- | @%filetriggerin@, also written @%filetrigger@+ SFiletriggerin+ | SFiletriggerun+ | SFiletriggerpostun+ | -- | @%transfiletriggerin@, also written @%transfiletrigger@+ STransfiletriggerin+ | STransfiletriggerun+ | STransfiletriggerpostun+ | SSepolicy+ | SPatchlist+ | SSourcelist+ | SEnd+ deriving stock (Eq, Ord, Show, Enum, Bounded, Generic)+ deriving anyclass (NFData)++-- | section keywords without the @%@, aliases included. the parser matches them ignoring case.+sectionKinds :: [(Text, SectionKind)]+sectionKinds =+ [ ("package", SPackage),+ ("description", SDescription),+ ("prep", SPrep),+ ("conf", SConf),+ ("generate_buildrequires", SGenerateBuildRequires),+ ("build", SBuild),+ ("install", SInstall),+ ("check", SCheck),+ ("clean", SClean),+ ("files", SFiles),+ ("changelog", SChangelog),+ ("pre", SPre),+ ("post", SPost),+ ("preun", SPreun),+ ("postun", SPostun),+ ("pretrans", SPretrans),+ ("posttrans", SPosttrans),+ ("preuntrans", SPreuntrans),+ ("postuntrans", SPostuntrans),+ ("verifyscript", SVerifyscript),+ ("triggerprein", STriggerprein),+ ("triggerin", STriggerin),+ ("trigger", STriggerin),+ ("triggerun", STriggerun),+ ("triggerpostun", STriggerpostun),+ ("filetriggerin", SFiletriggerin),+ ("filetrigger", SFiletriggerin),+ ("filetriggerun", SFiletriggerun),+ ("filetriggerpostun", SFiletriggerpostun),+ ("transfiletriggerin", STransfiletriggerin),+ ("transfiletrigger", STransfiletriggerin),+ ("transfiletriggerun", STransfiletriggerun),+ ("transfiletriggerpostun", STransfiletriggerpostun),+ ("sepolicy", SSepolicy),+ ("patchlist", SPatchlist),+ ("sourcelist", SSourcelist),+ ("end", SEnd)+ ]++-- | the main keyword for a section, without the @%@+sectionName :: SectionKind -> Text+sectionName k = maybe "" fst (lookupFirst k sectionKinds)+ where+ lookupFirst x = \case+ [] -> Nothing+ (n, y) : rest+ | y == x -> Just (n, y)+ | otherwise -> lookupFirst x rest++-- | whether the section is a scriptlet or trigger, from @%pre@ to @%transfiletriggerpostun@+isScriptSection :: SectionKind -> Bool+isScriptSection k = k >= SPre && k <= STransfiletriggerpostun++-- | whether the section is a build step, from @%prep@ to @%clean@+isBuildSection :: SectionKind -> Bool+isBuildSection k = k `elem` [SPrep, SConf, SGenerateBuildRequires, SBuild, SInstall, SCheck, SClean]++-- | whether tags are allowed here, which is before any section or inside @%package@+isPreambleLike :: Maybe SectionKind -> Bool+isPreambleLike = \case+ Nothing -> True+ Just SPackage -> True+ Just _ -> False++-- | a section header line+data SectionHeader = SectionHeader+ { secKind :: !SectionKind,+ -- | the keyword as written, with the @%@+ secKeyword :: !Text,+ -- | everything after the keyword, such as @ -n foo@+ secArgs :: ![Frag]+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | a node of the tree+data Node+ = NLine !Line+ | -- | an @%if@ block. it can wrap whole sections or sit inside one.+ NCond !CondBlock+ | NSection !Section+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | a section, which runs until the next header at the same nesting level+data Section = Section+ { sectionLine :: !Line,+ -- | the parsed header, same as the one in 'sectionLine'+ sectionHeader :: !SectionHeader,+ sectionNodes :: ![Node]+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | an @%if@ block with its @%elif@ and @%else@ branches+data CondBlock = CondBlock+ { -- | the branches in order, starting with the @%if@+ condBranches :: !(NonEmpty Branch),+ -- | the @%endif@ line. 'Nothing' when the block is never closed.+ condEnd :: !(Maybe Line)+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | one branch of a conditional block+data Branch = Branch+ { -- | the @%if@, @%elif@ or @%else@ line+ branchLine :: !Line,+ -- | the parsed condition, same as the one in 'branchLine'+ branchCond :: !CondLine,+ branchNodes :: ![Node]+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | a problem found while parsing. parsing still succeeds.+data SyntaxError = SyntaxError+ { -- | a short code such as @unclosed-if@, which lint uses as the rule id+ seCode :: !Text,+ -- | where the problem is+ seSpan :: !Span,+ seMessage :: !Text+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | a parsed spec file+data Tree = Tree+ { treeNodes :: ![Node],+ -- | syntax errors, in source order+ treeErrors :: ![SyntaxError]+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | every line of the tree in source order+treeLines :: Tree -> [Line]+treeLines = linesOfNodes . treeNodes++-- | every line of some nodes in source order+linesOfNodes :: [Node] -> [Line]+linesOfNodes = concatMap nodeLines++-- | every line of a node in source order+nodeLines :: Node -> [Line]+nodeLines = \case+ NLine l -> [l]+ NSection s -> sectionLine s : linesOfNodes (sectionNodes s)+ NCond c -> concatMap (\b -> branchLine b : linesOfNodes (branchNodes b)) (foldr (:) [] (condBranches c)) <> maybe [] pure (condEnd c)++-- | the source text of a line without its ending. the text must be the one the line was parsed from.+lineText :: Text -> Line -> Text+lineText src l =+ let Span s e = lineSpan l+ in T.take (posOffset e - posOffset s) (T.drop (posOffset s) src)++-- | the span of a line including its ending+lineFullSpan :: Line -> Span+lineFullSpan l = let Span s e = lineSpan l in Span s (advancePos e (lineEol l))
+ src/Rozbir/Syntax/Expr.hs view
@@ -0,0 +1,382 @@+-- | rpm's expression language, used by @%if@, @%[...]@ and @%{expr:...}@.+-- values that aren't known make the result unknown, unless the rest of the+-- expression decides it anyway, like @0 && x@.+module Rozbir.Syntax.Expr+ ( Item (..),+ ExprValue (..),+ itemsFromValue,+ itemsFromFrags,+ evalExpr,+ boolify,+ renderExprValue,+ )+where++import Control.Monad (unless, when)+import Control.Monad.Except (ExceptT, runExceptT, throwError)+import Control.Monad.State.Strict (StateT, evalStateT, get, gets, lift, modify', put)+import Data.Char (isAlpha, isAlphaNum, isDigit, isSpace)+import Data.Text (Text)+import Data.Text qualified as T+import Rozbir.Eval.Types+import Rozbir.Syntax (Frag (..), MacroRef)+import Rozbir.Version (compareVersionLiteral, parseVersionLiteral)+import Text.Read (readMaybe)++-- | one unit of expression input+data Item+ = IChar !Char+ | -- | a part of the input that isn't known+ IOpaque !Reason+ | -- | a macro that hasn't been expanded yet+ IMacro !MacroRef++-- | input from an expanded value+itemsFromValue :: Value -> [Item]+itemsFromValue (Value ps) = concatMap piece ps+ where+ piece = \case+ Known t -> map IChar (T.unpack t)+ Opaque r _ -> [IOpaque r]++-- | input from unexpanded text, with macros kept for later+itemsFromFrags :: [Frag] -> [Item]+itemsFromFrags = concatMap $ \case+ Lit t -> map IChar (T.unpack t)+ Escape -> [IChar '%', IChar '%']+ Macro m -> [IMacro m]++-- | the result of an expression+data ExprValue+ = EInt !Integer+ | -- | a string from @\"...\"@+ EStr !Text+ | -- | a version from @v\"...\"@+ EVer !Text+ | -- | a value that isn't known, with why+ EUnknown ![Reason]+ deriving stock (Eq, Show)++-- | turn a result back into text, the way rpm prints it+renderExprValue :: ExprValue -> Value+renderExprValue = \case+ EInt i -> known (T.pack (show i))+ EStr s -> known s+ EVer v -> known v+ EUnknown rs -> Value [Opaque r Nothing | r <- take 1 (rs <> [Failed "unknown"])]++-- | whether a result counts as true. zero and empty strings are false.+boolify :: ExprValue -> Tri+boolify = \case+ EInt i -> if i /= 0 then Yes else No+ EStr s -> if T.null s then No else Yes+ EVer v -> if T.null v then No else Yes+ EUnknown rs -> Unknown rs++data Tok m+ = TInt (m Value)+ | TStr Bool (m Value)+ | TUnknown [Reason]+ | TFunc Text+ | TOp Text+ | TEOF++tokenize :: (Monad m) => Bool -> (MacroRef -> m Value) -> [Item] -> Either Text [Tok m]+tokenize expand expandRef = go+ where+ go items = case dropWhile isSpaceItem items of+ [] -> Right [TEOF]+ IOpaque r : rest -> let (more, rest') = span intItem rest in (TUnknown (r : opaqueIn more) :) <$> go rest'+ IChar 'v' : IChar '"' : rest -> string True rest+ IChar '"' : rest -> string False rest+ items'@(i : _) | startsInt i -> let (tok, rest) = span intItem items' in (TInt (valueOf tok) :) <$> go rest+ IMacro _ : _ -> Left "macros can't be expanded here"+ IChar c : rest+ | isAlpha c -> case span funcChar (IChar c : rest) of+ (name, IChar '(' : rest') -> (TFunc (T.pack [x | IChar x <- name]) :) <$> go rest'+ _ -> Left "bare words are no longer supported, please use \"...\""+ | otherwise -> operator c rest++ isSpaceItem = \case+ IChar c -> isSpace c+ _ -> False+ startsInt = \case+ IChar c -> isDigit c+ IMacro _ -> expand+ _ -> False+ intItem = \case+ IChar c -> isDigit c+ IMacro _ -> expand+ IOpaque _ -> True+ funcChar = \case+ IChar c -> isAlphaNum c || c == '_' || c == '.' || c == ':'+ _ -> False+ opaqueIn xs = [r | IOpaque r <- xs]++ valueOf items = mconcat <$> mapM itemValue items+ itemValue = \case+ IChar c -> pure (known (T.singleton c))+ IOpaque r -> pure (opaque r)+ IMacro m -> expandRef m++ string isVersion rest = case break isQuote rest of+ (inner, _ : rest') -> (TStr isVersion (valueOf inner) :) <$> go rest'+ (_, []) -> Left "unterminated string in expression"+ isQuote = \case+ IChar '"' -> True+ _ -> False++ operator c rest = case (c, rest) of+ ('=', IChar '=' : r) -> (TOp "==" :) <$> go r+ ('!', IChar '=' : r) -> (TOp "!=" :) <$> go r+ ('<', IChar '=' : r) -> (TOp "<=" :) <$> go r+ ('>', IChar '=' : r) -> (TOp ">=" :) <$> go r+ ('&', IChar '&' : r) -> (TOp "&&" :) <$> go r+ ('|', IChar '|' : r) -> (TOp "||" :) <$> go r+ _+ | c `elem` ("+-*/()<>!?:," :: String) -> (TOp (T.singleton c) :) <$> go rest+ | otherwise -> Left ("parse error in expression at '" <> T.singleton c <> "'")++type P m = StateT ([Tok m], Bool) (ExceptT Text m)++-- | evaluate an expression. 'Left' is a syntax or type error, with rpm's message.+-- when the flag is set, macros are expanded with the function only if they are needed, like rpm does for @%[...]@. otherwise a macro in the input is an error.+evalExpr :: (Monad m) => Bool -> (MacroRef -> m Value) -> [Item] -> m (Either Text ExprValue)+evalExpr expand expandRef items = case tokenize expand expandRef items of+ Left e -> pure (Left e)+ Right toks -> runExceptT (evalStateT top (toks, False))+ where+ top = do+ v <- ternary+ peek >>= \case+ TEOF -> pure v+ _ -> throwError "syntax error in expression"++peek :: (Monad m) => P m (Tok m)+peek =+ gets fst >>= \case+ t : _ -> pure t+ [] -> pure TEOF++advance :: (Monad m) => P m ()+advance = modify' (\(ts, d) -> (drop 1 ts, d))++isOp :: Text -> Tok m -> Bool+isOp o = \case+ TOp o' -> o == o'+ _ -> False++discarding :: (Monad m) => Bool -> P m a -> P m a+discarding on act+ | not on = act+ | otherwise = do+ (ts, d) <- get+ put (ts, True)+ r <- act+ modify' (\(ts', _) -> (ts', d))+ pure r++ternary :: (Monad m) => P m ExprValue+ternary = do+ v1 <- logical+ t <- peek+ if not (isOp "?" t)+ then pure v1+ else do+ advance+ let cond = boolify v1+ a <- discarding (cond == No) ternary+ t' <- peek+ unless (isOp ":" t') (throwError "syntax error in expression")+ advance+ b <- discarding (cond == Yes) ternary+ checkTypes a b+ pure $ case cond of+ Yes -> a+ No -> b+ Unknown rs -> if a == b then a else EUnknown rs++logical :: (Monad m) => P m ExprValue+logical = relational >>= loop+ where+ loop v1 = do+ t <- peek+ if+ | isOp "&&" t -> step v1 True+ | isOp "||" t -> step v1 False+ | otherwise -> pure v1+ step v1 isAnd = do+ advance+ let b1 = boolify v1+ short = if isAnd then b1 == No else b1 == Yes+ v2 <- discarding short relational+ checkTypes v1 v2+ loop $ case (b1, isAnd) of+ (No, True) -> v1+ (Yes, True) -> v2+ (Yes, False) -> v1+ (No, False) -> v2+ (Unknown rs, True) -> if boolify v2 == No then v2 else EUnknown rs+ (Unknown rs, False) -> if boolify v2 == Yes then v2 else EUnknown rs++relational :: (Monad m) => P m ExprValue+relational = addSub >>= loop+ where+ ops = ["==", "!=", "<", "<=", ">", ">="]+ loop v1 =+ peek >>= \case+ TOp o | o `elem` ops -> do+ advance+ v2 <- addSub+ checkTypes v1 v2+ loop (compareWith o v1 v2)+ _ -> pure v1+ compareWith o v1 v2 = case ordering v1 v2 of+ Left rs -> EUnknown rs+ Right ord -> EInt (if test o ord then 1 else 0)+ ordering a b = case (a, b) of+ (EUnknown r1, EUnknown r2) -> Left (r1 <> r2)+ (EUnknown r, _) -> Left r+ (_, EUnknown r) -> Left r+ (EInt x, EInt y) -> Right (compare x y)+ (EStr x, EStr y) -> Right (compare x y)+ (EVer x, EVer y) -> case (parseVersionLiteral x, parseVersionLiteral y) of+ (Just vx, Just vy) -> Right (compareVersionLiteral vx vy)+ _ -> Left [Failed "invalid version"]+ _ -> Left [Failed "types must match"]+ test o ord = case o of+ "==" -> ord == EQ+ "!=" -> ord /= EQ+ "<" -> ord == LT+ "<=" -> ord /= GT+ ">" -> ord == GT+ _ -> ord /= LT++addSub :: (Monad m) => P m ExprValue+addSub = mulDiv >>= loop+ where+ loop v1 =+ peek >>= \case+ TOp o | o == "+" || o == "-" -> do+ advance+ v2 <- mulDiv+ checkTypes v1 v2+ r <- case (v1, v2) of+ (EUnknown a, EUnknown b) -> pure (EUnknown (a <> b))+ (EUnknown a, _) -> pure (EUnknown a)+ (_, EUnknown b) -> pure (EUnknown b)+ (EInt x, EInt y) -> pure (EInt (if o == "+" then x + y else x - y))+ (EStr x, EStr y) | o == "+" -> pure (EStr (x <> y))+ (EStr _, _) -> throwError "- not supported for strings"+ _ -> throwError "+ and - not supported for versions"+ loop r+ _ -> pure v1++mulDiv :: (Monad m) => P m ExprValue+mulDiv = primary >>= loop+ where+ loop v1 =+ peek >>= \case+ TOp o | o == "*" || o == "/" -> do+ advance+ v2 <- primary+ checkTypes v1 v2+ d <- gets snd+ r <- case (v1, v2) of+ (EUnknown a, _) -> pure (EUnknown a)+ (_, EUnknown b) -> pure (EUnknown b)+ (EInt x, EInt y)+ | d -> pure v1+ | o == "*" -> pure (EInt (x * y))+ | y == 0 -> throwError "division by zero"+ | otherwise -> pure (EInt (x `quot` y))+ (EVer _, _) -> throwError "* and / not supported for versions"+ _ -> throwError "* and / not supported for strings"+ loop r+ _ -> pure v1++primary :: (Monad m) => P m ExprValue+primary =+ peek >>= \case+ TFunc name -> do+ advance+ args <- funcArgs+ if "lua:" `T.isPrefixOf` name+ then pure (EUnknown (RunsLua : concat [rs | EUnknown rs <- args]))+ else throwError "unsupported function"+ TOp "(" -> do+ advance+ v <- ternary+ t <- peek+ unless (isOp ")" t) (throwError "unmatched (")+ advance+ pure v+ TInt act -> do+ advance+ value act >>= \case+ Left rs -> pure (EUnknown rs)+ Right t -> case wellFormed t of+ Just i -> pure (EInt i)+ Nothing+ | Just (c, _) <- T.uncons t, isAlpha c -> throwError "macro expansion returned a bare word, please use \"...\""+ | otherwise -> throwError "macro expansion did not return an integer"+ TStr isVersion act -> do+ advance+ value act >>= \case+ Left rs -> pure (EUnknown rs)+ Right t+ | isVersion -> do+ d <- gets snd+ when (not d && parseVersionLiteral t == Nothing) (throwError "invalid version")+ pure (EVer t)+ | otherwise -> pure (EStr t)+ TUnknown rs -> advance >> pure (EUnknown rs)+ TOp "-" -> do+ advance+ primary >>= \case+ EInt i -> pure (EInt (negate i))+ EUnknown rs -> pure (EUnknown rs)+ _ -> throwError "- only on numbers"+ TOp "!" -> do+ advance+ v <- primary+ pure $ case boolify v of+ Yes -> EInt 0+ No -> EInt 1+ Unknown rs -> EUnknown rs+ TEOF -> throwError "unexpected end of expression"+ _ -> throwError "syntax error in expression"+ where+ value act = do+ d <- gets snd+ if d+ then pure (Right "0")+ else do+ v <- lift (lift act)+ pure (maybe (Left (reasons v)) Right (knownText (stripQuoteMarks v)))+ wellFormed t+ | T.null t = Just 0+ | Just digits <- T.stripPrefix "-" t, not (T.null digits), T.all isDigit digits = negate <$> readMaybe (T.unpack digits)+ | T.all isDigit t = readMaybe (T.unpack t)+ | otherwise = Nothing+ funcArgs = do+ t <- peek+ if isOp ")" t+ then advance >> pure []+ else collect []+ collect acc = do+ v <- ternary+ t <- peek+ if+ | isOp ")" t -> advance >> pure (reverse (v : acc))+ | isOp "," t -> advance >> collect (v : acc)+ | otherwise -> throwError "syntax error in expression"++checkTypes :: (Monad m) => ExprValue -> ExprValue -> P m ()+checkTypes a b = case (a, b) of+ (EUnknown _, _) -> pure ()+ (_, EUnknown _) -> pure ()+ (EInt _, EInt _) -> pure ()+ (EStr _, EStr _) -> pure ()+ (EVer _, EVer _) -> pure ()+ _ -> throwError "types must match"
+ src/Rozbir/Syntax/Parse.hs view
@@ -0,0 +1,438 @@+-- | the spec parser. it never fails and loses nothing, so @render (parse s) == s@+-- for any text. problems end up in 'treeErrors' instead.+module Rozbir.Syntax.Parse+ ( parse,+ parseLines,+ parseFrags,+ classifyLine,+ matchClose,+ isNameChar,+ isHSpace,+ isBlankChar,+ splitTrailing,+ )+where++import Data.Char (isAsciiLower, isAsciiUpper, isDigit, isSpace)+import Data.List.NonEmpty qualified as NE+import Data.Maybe (isJust)+import Data.Text (Text)+import Data.Text qualified as T+import Rozbir.Syntax++-- | parse a whole spec into a tree+parse :: Text -> Tree+parse src =+ let (ls, lineErrs) = parseLines Nothing src+ (nodes, treeErrs) = buildTree ls+ in Tree (groupSections nodes) (lineErrs <> treeErrs)++-- | split text into lines without building the tree. the section decides whether lines can be tags, and positions start at 'startPos'.+parseLines :: Maybe SectionKind -> Text -> ([Line], [SyntaxError])+parseLines sec0 src = go sec0 startPos (logicalLines src)+ where+ go _ _ [] = ([], [])+ go sec pos (LogicalLine {..} : rest) =+ let body = classifyLine sec llBody+ end = advancePos pos llBody+ sp = Span pos end+ next = advancePos end llEol+ sec' = case body of+ Header h -> Just (secKind h)+ _ -> sec+ errs =+ [SyntaxError code sp msg | Just (code, msg) <- [llProblem]]+ <> [SyntaxError "not-a-tag" sp "this line isn't a tag, a macro or a section header" | Bogus _ <- [body]]+ (ls, es) = go sec' next rest+ in (Line body llEol sp : ls, errs <> es)++data LogicalLine = LogicalLine+ { llBody :: Text,+ llEol :: Text,+ llProblem :: Maybe (Text, Text)+ }++data Scan = Scan !Int !Int !Int !Bool++logicalLines :: Text -> [LogicalLine]+logicalLines = assemble . physicalLines+ where+ assemble [] = []+ assemble phys@(first : _) = case collect (continuesWithBackslash first) (Scan 0 0 0 False) [] phys of+ Right (taken, rest) -> finish (T.concat taken) Nothing : assemble rest+ Left problem -> finish first (Just problem) : assemble (drop 1 phys)++ collect joinable st acc = \case+ [] -> Left (unclosed st)+ p : ps ->+ let st'@(Scan pc bc xc nc) = scanText st p+ acc' = p : acc+ in if pc == 0 && bc == 0 && xc == 0 && not (joinable && nc)+ then Right (reverse acc', ps)+ else collect joinable st' acc' ps++ unclosed (Scan pc bc xc _)+ | pc + bc + xc > 0 = ("unclosed-macro", "this macro is never closed, so rpm reads the rest of the file into it")+ | otherwise = ("trailing-backslash", "the last line ends in a backslash with nothing to continue onto")++ finish t problem+ | Just b <- T.stripSuffix "\r\n" t = LogicalLine b "\r\n" problem+ | Just b <- T.stripSuffix "\n" t = LogicalLine b "\n" problem+ | otherwise = LogicalLine t "" problem++continuesWithBackslash :: Text -> Bool+continuesWithBackslash line =+ let rest = T.dropWhile isHSpace line+ in isDefine rest || isJust (condLine "" rest) || isJust (keywordWithArg "%include" rest)+ where+ isDefine t = case T.stripPrefix "%" t of+ Just after ->+ let (word, more) = T.span isNameChar after+ in isJust (lookup word defineKeywords) && maybe False (isBlankChar . fst) (T.uncons more)+ Nothing -> False++physicalLines :: Text -> [Text]+physicalLines t+ | T.null t = []+ | otherwise = case T.break (== '\n') t of+ (pre, rest)+ | T.null rest -> [pre]+ | otherwise -> (pre <> "\n") : physicalLines (T.drop 1 rest)++data Mode = Normal | AfterBackslash | AfterPercent++scanText :: Scan -> Text -> Scan+scanText st0 = fst . T.foldl' step (st0, Normal)+ where+ step (s@(Scan pc bc xc nc), mode) c = case mode of+ AfterBackslash+ | c == '\n' -> (Scan pc bc xc True, Normal)+ | otherwise -> (s, Normal)+ AfterPercent -> case c of+ '{' -> (Scan pc (bc + 1) xc nc, Normal)+ '(' -> (Scan (pc + 1) bc xc nc, Normal)+ '[' -> (Scan pc bc (xc + 1) nc, Normal)+ '%' -> (s, Normal)+ _ -> step (s, Normal) c+ Normal -> case c of+ '\\' -> (s, AfterBackslash)+ '\n' -> (Scan pc bc xc False, Normal)+ '%' -> (s, AfterPercent)+ '{' | bc > 0 -> (Scan pc (bc + 1) xc nc, Normal)+ '}' | bc > 0 -> (Scan pc (bc - 1) xc nc, Normal)+ '(' | pc > 0 -> (Scan (pc + 1) bc xc nc, Normal)+ ')' | pc > 0 -> (Scan (pc - 1) bc xc nc, Normal)+ '[' | xc > 0 -> (Scan pc bc (xc + 1) nc, Normal)+ ']' | xc > 0 -> (Scan pc bc (xc - 1) nc, Normal)+ _ -> (s, Normal)++-- | whitespace other than a newline+isHSpace :: Char -> Bool+isHSpace c = c /= '\n' && isSpace c++-- | a space or a tab+isBlankChar :: Char -> Bool+isBlankChar c = c == ' ' || c == '\t'++-- | a character allowed in a macro name, which is an ASCII letter, digit or underscore+isNameChar :: Char -> Bool+isNameChar c = isAsciiLower c || isAsciiUpper c || isDigit c || c == '_'++isAsciiAlpha :: Char -> Bool+isAsciiAlpha c = isAsciiLower c || isAsciiUpper c++-- | split off trailing whitespace+splitTrailing :: Text -> (Text, Text)+splitTrailing t = let tr = T.takeWhileEnd isHSpace t in (T.dropEnd (T.length tr) t, tr)++-- | work out what one line is, given the section it is in. the text must not include the line ending.+classifyLine :: Maybe SectionKind -> Text -> LineBody+classifyLine sec body+ | T.null rest = Blank body+ | "#" `T.isPrefixOf` rest = Comment indent (parseFrags rest)+ | Just c <- condLine indent rest = Cond c+ | T.null indent, Just h <- headerLine rest = Header h+ | Just d <- defineLine indent rest = Define d+ | Just after <- keywordWithArg "%include" rest = Include (indent <> "%include") (parseFrags after)+ | isPreambleLike sec, Just t <- tagLine indent rest = Tag t+ | isPreambleLike sec, not ("%" `T.isPrefixOf` rest) = Bogus body+ | otherwise = Body (parseFrags body)+ where+ (indent, rest) = T.span isHSpace body++keywordWithArg :: Text -> Text -> Maybe Text+keywordWithArg kw t = do+ after <- T.stripPrefix kw t+ case T.uncons after of+ Nothing -> Just after+ Just (c, _) | isBlankChar c -> Just after+ _ -> Nothing++keywordAlone :: Text -> Text -> Maybe Text+keywordAlone kw t = do+ after <- T.stripPrefix kw t+ case T.uncons after of+ Just (c, _) | isAsciiAlpha c -> Nothing+ _ -> Just after++condLine :: Text -> Text -> Maybe CondLine+condLine indent rest = firstJust candidates+ where+ candidates =+ [ (CEndif, "%endif", keywordAlone),+ (CElse, "%else", keywordAlone),+ (CIf, "%if", keywordWithArg),+ (CIfArch, "%ifarch", keywordWithArg),+ (CIfNArch, "%ifnarch", keywordWithArg),+ (CIfOs, "%ifos", keywordWithArg),+ (CIfNOs, "%ifnos", keywordWithArg),+ (CElifArch, "%elifarch", keywordWithArg),+ (CElifOs, "%elifos", keywordWithArg),+ (CElif, "%elif", keywordWithArg)+ ]+ firstJust = \case+ [] -> Nothing+ (kind, kw, match) : more -> case match kw rest of+ Just after -> Just (CondLine indent kind kw (parseFrags after))+ Nothing -> firstJust more++headerLine :: Text -> Maybe SectionHeader+headerLine t = do+ after <- T.stripPrefix "%" t+ let (word, more) = T.span isNameChar after+ kind <- lookup (T.toLower word) sectionKinds+ case T.uncons more of+ Just (c, _) | not (isSpace c) -> Nothing+ _ -> Just (SectionHeader kind ("%" <> word) (parseFrags more))++defineKeywords :: [(Text, DefineKind)]+defineKeywords =+ [ ("global", DefGlobal),+ ("define", DefDefine),+ ("undefine", DefUndefine),+ ("bcond", DefBcond),+ ("bcond_with", DefBcondWith),+ ("bcond_without", DefBcondWithout)+ ]++defineLine :: Text -> Text -> Maybe DefineLine+defineLine indent t = do+ after <- T.stripPrefix "%" t+ let (word, more) = T.span isNameChar after+ kind <- lookup word defineKeywords+ (c, _) <- T.uncons more+ if not (isBlankChar c)+ then Nothing+ else do+ let (gap, afterGap) = defineGap kind more+ (name, afterName) = T.span isNameChar afterGap+ if T.null name+ then Nothing+ else do+ (opts, afterOpts) <- delimitedOpt '(' ')' afterName kind+ (mods, afterMods) <- delimitedOpt '<' '>' afterOpts kind+ let (sep, bodyText) = T.span isHSpace afterMods+ (bodyCore, trailing) = splitTrailing bodyText+ Just+ DefineLine+ { defIndent = indent,+ defKind = kind,+ defKeyword = "%" <> word,+ defGap = gap,+ defName = name,+ defOpts = opts,+ defMods = mods,+ defSep = sep,+ defBody = parseFrags bodyCore,+ defTrailing = trailing+ }+ where+ delimitedOpt open close s kind+ | kind `notElem` [DefGlobal, DefDefine] = Just (Nothing, s)+ | Just inner <- T.stripPrefix (T.singleton open) s = case T.break (== close) inner of+ (o, rest) | not (T.null rest) -> Just (Just o, T.drop 1 rest)+ _ -> Nothing+ | otherwise = Just (Nothing, s)++defineGap :: DefineKind -> Text -> (Text, Text)+defineGap kind s0+ | kind == DefDefine = options s0+ | otherwise = T.span isBlankChar s0+ where+ options s =+ let (ws, rest) = T.span isBlankChar s+ in case T.uncons rest of+ Just ('-', more) ->+ let (letters, rest') = T.span (not . isSpace) more+ (ws2, rest'') = options rest'+ in if T.null letters then (ws, rest) else (ws <> "-" <> letters <> ws2, rest'')+ _ -> (ws, rest)++tagLine :: Text -> Text -> Maybe TagLine+tagLine indent t = do+ (c, _) <- T.uncons t+ if not (isAsciiAlpha c)+ then Nothing+ else do+ let (name, afterName) = T.span isNameChar t+ (gap, afterGap) = T.span isHSpace afterName+ (qualifier, afterQual) <- case T.uncons afterGap of+ Just ('(', _) -> case T.break (== ')') afterGap of+ (q, rest) | not (T.null rest) -> Just (Just (Qualifier gap (q <> ")")), T.drop 1 rest)+ _ -> Nothing+ _ -> Just (Nothing, afterName)+ let (preColon, afterPre) = T.span isHSpace afterQual+ afterColon <- T.stripPrefix ":" afterPre+ let (postColon, valueText) = T.span isHSpace afterColon+ (valueCore, trailing) = splitTrailing valueText+ Just+ TagLine+ { tagIndent = indent,+ tagName = name,+ tagQualifier = qualifier,+ tagSep = preColon <> ":" <> postColon,+ tagValue = parseFrags valueCore,+ tagTrailing = trailing+ }++-- | split text into literal text and macros. an unclosed macro takes the rest of the text.+parseFrags :: Text -> [Frag]+parseFrags = mergeLits . go+ where+ go t = case T.break (== '%') t of+ (pre, rest)+ | T.null rest -> lit pre []+ | otherwise -> lit pre (percent (T.drop 1 rest))+ lit p xs = if T.null p then xs else Lit p : xs+ percent r = case T.uncons r of+ Nothing -> [Lit "%"]+ Just ('%', r') -> Escape : go r'+ Just ('(', _) -> delimited '(' ')' Shell r+ Just ('[', _) -> delimited '[' ']' Expr r+ Just ('{', _) -> braced r+ _ -> bare r+ delimited open close ctor r = case matchClose open close r of+ Just (inner, after) -> Macro (ctor (go inner)) : go after+ Nothing -> [Macro (Unterminated open (T.drop 1 r))]+ braced r = case matchClose '{' '}' r of+ Nothing -> [Macro (Unterminated '{' (T.drop 1 r))]+ Just (inner, after) -> Macro (bracedRef inner) : go after+ bracedRef inner =+ let (flags, i1) = T.span (`elem` ['?', '!']) inner+ (name, i2) = T.break (`elem` [' ', ':', '}']) i1+ in case T.uncons i2 of+ Nothing -> Braced flags name Nothing+ Just (':', a)+ | T.null flags && name == "lua" -> Lua a+ | otherwise -> Braced flags name (Just (ColonArg (mergeLits (go a))))+ Just (' ', _) -> Braced flags name (Just (SpaceArg (mergeLits (go i2))))+ Just _ -> Braced flags i1 Nothing+ bare r =+ let (flags, r1) = T.span (`elem` ['?', '!']) r+ (dash, r2) = maybe ("", r1) ("-",) (T.stripPrefix "-" r1)+ (nm, r3) = T.span isNameChar r2+ (suffix, r4)+ | "**" `T.isPrefixOf` r3 = ("**", T.drop 2 r3)+ | Just (c, more) <- T.uncons r3, c == '*' || c == '#' = (T.singleton c, more)+ | otherwise = ("", r3)+ name = dash <> nm <> suffix+ in if T.null name && T.null flags+ then Lit "%" : go r+ else Macro (Bare flags name) : go r4++mergeLits :: [Frag] -> [Frag]+mergeLits = \case+ Lit a : Lit b : rest -> mergeLits (Lit (a <> b) : rest)+ Macro m : rest -> Macro (inner m) : mergeLits rest+ x : rest -> x : mergeLits rest+ [] -> []+ where+ inner = \case+ Braced f n (Just (ColonArg fs)) -> Braced f n (Just (ColonArg (mergeLits fs)))+ Braced f n (Just (SpaceArg fs)) -> Braced f n (Just (SpaceArg (mergeLits fs)))+ Shell fs -> Shell (mergeLits fs)+ Expr fs -> Expr (mergeLits fs)+ m -> m++-- | for text starting with an opening character, return what is inside the matching close and what comes after it.+-- nesting and backslash escapes are respected. 'Nothing' when it is never closed.+matchClose :: Char -> Char -> Text -> Maybe (Text, Text)+matchClose open close t = go (0 :: Int) 0 (T.unpack t)+ where+ go _ _ [] = Nothing+ go lvl i (c : cs)+ | c == '\\' = case cs of+ [] -> Nothing+ _ : cs' -> go lvl (i + 2) cs'+ | c == close =+ if lvl - 1 <= 0+ then Just (T.take (i - 1) (T.drop 1 t), T.drop (i + 1) t)+ else go (lvl - 1) (i + 1) cs+ | c == open = go (lvl + 1) (i + 1) cs+ | otherwise = go lvl (i + 1) cs++data Frame = Frame+ { frDone :: [Branch],+ frLine :: Line,+ frCond :: CondLine,+ frNodes :: [Node]+ }++buildTree :: [Line] -> ([Node], [SyntaxError])+buildTree = go [] [] []+ where+ go :: [Frame] -> [Node] -> [SyntaxError] -> [Line] -> ([Node], [SyntaxError])+ go stack top errs [] = closeAll stack top errs+ go stack top errs (l : ls) = case lineBody l of+ Cond c+ | isIfKind (condKind c) -> go (Frame [] l c [] : stack) top errs ls+ | otherwise -> case stack of+ [] -> go stack (NLine l : top) (stray c l : errs) ls+ fr : frs+ | condKind c == CEndif ->+ let block = NCond (CondBlock (branchesOf fr) (Just l))+ in push frs top errs block ls+ | otherwise ->+ let errs' = [afterElse c l | condKind (frCond fr) == CElse] <> errs+ in go (Frame (closeBranch fr : frDone fr) l c [] : frs) top errs' ls+ _ -> push stack top errs (NLine l) ls++ push [] top errs n ls = go [] (n : top) errs ls+ push (fr : frs) top errs n ls = go (fr {frNodes = n : frNodes fr} : frs) top errs ls++ closeBranch fr = Branch (frLine fr) (frCond fr) (reverse (frNodes fr))+ branchesOf fr = NE.fromList (reverse (closeBranch fr : frDone fr))++ closeAll [] top errs = (reverse top, reverse errs)+ closeAll (fr : frs) top errs =+ let block = NCond (CondBlock (branchesOf fr) Nothing)+ err = SyntaxError "unclosed-if" (lineSpan (firstLine fr)) (condKeyword (firstCond fr) <> " is never closed with %endif")+ in case frs of+ [] -> closeAll [] (block : top) (err : errs)+ parent : rest -> closeAll (parent {frNodes = block : frNodes parent} : rest) top (err : errs)++ firstBranch fr = NE.head (branchesOf fr)+ firstLine = branchLine . firstBranch+ firstCond = branchCond . firstBranch++ stray c l = SyntaxError (strayCode c) (lineSpan l) (condKeyword c <> " has no %if to belong to")+ strayCode c = case condKind c of+ CEndif -> "stray-endif"+ CElse -> "stray-else"+ _ -> "stray-elif"+ afterElse c l = SyntaxError "branch-after-else" (lineSpan l) (condKeyword c <> " comes after %else, so it can never be reached")++groupSections :: [Node] -> [Node]+groupSections = \case+ [] -> []+ NLine l@(Line (Header h) _ _) : rest ->+ let (body, rest') = break isHeader rest+ in NSection (Section l h (map deep body)) : groupSections rest'+ n : rest -> deep n : groupSections rest+ where+ isHeader = \case+ NLine (Line (Header _) _ _) -> True+ _ -> False+ deep = \case+ NCond (CondBlock bs end) -> NCond (CondBlock (fmap (\b -> b {branchNodes = groupSections (branchNodes b)}) bs) end)+ n -> n
+ src/Rozbir/Syntax/Render.hs view
@@ -0,0 +1,171 @@+-- | turn the syntax tree back into text, exactly as it was parsed. it also maps+-- fragments back to their source spans.+module Rozbir.Syntax.Render+ ( render,+ renderNodes,+ renderLine,+ renderBody,+ renderFrags,+ renderFrag,+ renderMacro,+ renderTagValue,+ renderDefineBody,+ renderCondArgs,+ renderSectionArgs,+ fragSpans,+ macroSpans,+ lineFrags,+ )+where++import Data.Text (Text)+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder (Builder, fromText, singleton, toLazyText)+import Rozbir.Syntax++-- | the original source of a tree+render :: Tree -> Text+render = renderNodes . treeNodes++-- | the source of some nodes, line endings included+renderNodes :: [Node] -> Text+renderNodes = TL.toStrict . toLazyText . foldMap lineB . linesOfNodes++lineB :: Line -> Builder+lineB l = bodyB (lineBody l) <> fromText (lineEol l)++-- | the source of a line, its ending included+renderLine :: Line -> Text+renderLine = TL.toStrict . toLazyText . lineB++-- | the source of a line without its ending+renderBody :: LineBody -> Text+renderBody = TL.toStrict . toLazyText . bodyB++-- | the source of some fragments+renderFrags :: [Frag] -> Text+renderFrags = TL.toStrict . toLazyText . fragsB++-- | the source of a fragment+renderFrag :: Frag -> Text+renderFrag = TL.toStrict . toLazyText . fragB++-- | the source of a macro reference+renderMacro :: MacroRef -> Text+renderMacro = TL.toStrict . toLazyText . macroB++-- | a tag's value as written, unexpanded+renderTagValue :: TagLine -> Text+renderTagValue = renderFrags . tagValue++-- | a define's body as written, unexpanded+renderDefineBody :: DefineLine -> Text+renderDefineBody = renderFrags . defBody++-- | the condition after the keyword, leading whitespace included+renderCondArgs :: CondLine -> Text+renderCondArgs = renderFrags . condArgs++-- | the arguments after a section keyword, leading whitespace included+renderSectionArgs :: SectionHeader -> Text+renderSectionArgs = renderFrags . secArgs++bodyB :: LineBody -> Builder+bodyB = \case+ Blank t -> fromText t+ Comment indent fs -> fromText indent <> fragsB fs+ Tag TagLine {..} ->+ fromText tagIndent+ <> fromText tagName+ <> maybe mempty (\q -> fromText (qualGap q) <> fromText (qualRaw q)) tagQualifier+ <> fromText tagSep+ <> fragsB tagValue+ <> fromText tagTrailing+ Define DefineLine {..} ->+ fromText defIndent+ <> fromText defKeyword+ <> fromText defGap+ <> fromText defName+ <> maybe mempty (\o -> singleton '(' <> fromText o <> singleton ')') defOpts+ <> maybe mempty (\m -> singleton '<' <> fromText m <> singleton '>') defMods+ <> fromText defSep+ <> fragsB defBody+ <> fromText defTrailing+ Cond CondLine {..} -> fromText condIndent <> fromText condKeyword <> fragsB condArgs+ Header SectionHeader {..} -> fromText secKeyword <> fragsB secArgs+ Include prefix fs -> fromText prefix <> fragsB fs+ Body fs -> fragsB fs+ Bogus t -> fromText t++fragsB :: [Frag] -> Builder+fragsB = foldMap fragB++fragB :: Frag -> Builder+fragB = \case+ Lit t -> fromText t+ Escape -> fromText "%%"+ Macro m -> macroB m++macroB :: MacroRef -> Builder+macroB = \case+ Bare flags name -> singleton '%' <> fromText flags <> fromText name+ Braced flags name arg ->+ fromText "%{"+ <> fromText flags+ <> fromText name+ <> maybe mempty argB arg+ <> singleton '}'+ Shell fs -> fromText "%(" <> fragsB fs <> singleton ')'+ Expr fs -> fromText "%[" <> fragsB fs <> singleton ']'+ Lua t -> fromText "%{lua:" <> fromText t <> singleton '}'+ Unterminated c t -> singleton '%' <> singleton c <> fromText t+ where+ argB = \case+ ColonArg fs -> singleton ':' <> fragsB fs+ SpaceArg fs -> fragsB fs++-- | pair each fragment with its span, given where the first one starts+fragSpans :: Pos -> [Frag] -> [(Span, Frag)]+fragSpans p = \case+ [] -> []+ f : fs -> let e = advancePos p (renderFrag f) in (Span p e, f) : fragSpans e fs++-- | every macro in some fragments with its span, given where they start. macros nested in arguments, @%(...)@ and @%[...]@ are included after the macro that holds them.+macroSpans :: Pos -> [Frag] -> [(Span, MacroRef)]+macroSpans p fs = concat [(sp, m) : inner sp m | (sp, Macro m) <- fragSpans p fs]+ where+ inner (Span s _) = \case+ Braced fl n (Just a) ->+ let s' = advancePos s ("%{" <> fl <> n)+ in case a of+ ColonArg xs -> macroSpans (advancePos s' ":") xs+ SpaceArg xs -> macroSpans s' xs+ Shell xs -> macroSpans (advancePos s "%(") xs+ Expr xs -> macroSpans (advancePos s "%[") xs+ _ -> []++-- | the fragments of a line with where they start. blank and bogus lines have none.+lineFrags :: Line -> [(Pos, [Frag])]+lineFrags l = case lineBody l of+ Comment indent fs -> [(at indent, fs)]+ Tag TagLine {..} -> [(at (tagIndent <> tagName <> maybe "" (\q -> qualGap q <> qualRaw q) tagQualifier <> tagSep), tagValue)]+ Define DefineLine {..} ->+ [ ( at+ ( defIndent+ <> defKeyword+ <> defGap+ <> defName+ <> maybe "" (\o -> "(" <> o <> ")") defOpts+ <> maybe "" (\m -> "<" <> m <> ">") defMods+ <> defSep+ ),+ defBody+ )+ ]+ Cond CondLine {..} -> [(at (condIndent <> condKeyword), condArgs)]+ Header SectionHeader {..} -> [(at secKeyword, secArgs)]+ Include prefix fs -> [(at prefix, fs)]+ Body fs -> [(at "", fs)]+ _ -> []+ where+ at prefix = advancePos (spanStart (lineSpan l)) prefix
+ src/Rozbir/Version.hs view
@@ -0,0 +1,125 @@+-- | rpm versions: epoch, version and release, and rpm's rules for comparing them+module Rozbir.Version+ ( EVR (..),+ parseEVR,+ renderEVR,+ rpmvercmp,+ compareEVR,+ VersionLiteral (..),+ parseVersionLiteral,+ compareVersionLiteral,+ )+where++import Control.DeepSeq (NFData)+import Data.Aeson (FromJSON, ToJSON)+import Data.Char (isAsciiLower, isAsciiUpper, isDigit)+import Data.Text (Text)+import Data.Text qualified as T+import GHC.Generics (Generic)+import Text.Read (readMaybe)++-- | an epoch, version and release. 'compare' uses rpm's rules, while '==' compares the text.+data EVR = EVR+ { -- | the epoch, 0 when there is none+ evrEpoch :: !Int,+ evrVersion :: !Text,+ evrRelease :: !Text+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (ToJSON, FromJSON, NFData)++instance Ord EVR where+ compare = compareEVR++-- | parse @[epoch:]version-release@. an epoch of @(none)@ counts as 0.+-- 'Nothing' when the epoch isn't a number or the version or release is missing.+parseEVR :: Text -> Maybe EVR+parseEVR raw = do+ let (epochPart, rest) = case T.breakOn ":" raw of+ (vr, "") -> ("0", vr)+ (e, r) -> (e, T.drop 1 r)+ epoch <- if epochPart == "(none)" then Just 0 else readMaybe (T.unpack epochPart)+ let (verDash, rel) = T.breakOnEnd "-" rest+ ver <- T.stripSuffix "-" verDash+ if T.null ver || T.null rel then Nothing else Just (EVR epoch ver rel)++-- | print an t'EVR', leaving out an epoch of 0+renderEVR :: EVR -> Text+renderEVR (EVR 0 v r) = v <> "-" <> r+renderEVR (EVR e v r) = T.pack (show e) <> ":" <> v <> "-" <> r++-- | compare by epoch, then version, then release+compareEVR :: EVR -> EVR -> Ordering+compareEVR (EVR e1 v1 r1) (EVR e2 v2 r2) =+ compare e1 e2 <> rpmvercmp v1 v2 <> rpmvercmp r1 r2++-- | a port of rpm's @rpmvercmp@. @~@ sorts before anything, even the end of the string, and @^@ sorts after the end but before anything else.+rpmvercmp :: Text -> Text -> Ordering+rpmvercmp a b+ | a == b = EQ+ | otherwise = go a b+ where+ go one0 two0+ | T.null one0 && T.null two0 = EQ+ | otherwise =+ let one = T.dropWhile isSep one0+ two = T.dropWhile isSep two0+ in case (T.uncons one, T.uncons two) of+ (Just ('~', one'), Just ('~', two')) -> go one' two'+ (Just ('~', _), _) -> LT+ (_, Just ('~', _)) -> GT+ (Just ('^', one'), Just ('^', two')) -> go one' two'+ (Nothing, Just ('^', _)) -> LT+ (Just ('^', _), Nothing) -> GT+ (Just ('^', _), Just _) -> LT+ (Just _, Just ('^', _)) -> GT+ (Nothing, Nothing) -> EQ+ (Just _, Nothing) -> GT+ (Nothing, Just _) -> LT+ (Just (c, _), Just _)+ | isDigit c -> segment True (T.span isDigit one) (T.span isDigit two)+ | otherwise -> segment False (T.span isAlpha one) (T.span isAlpha two)++ segment isNum (seg1, rest1) (seg2, rest2)+ | T.null seg2 = if isNum then GT else LT+ | isNum =+ let n1 = T.dropWhile (== '0') seg1+ n2 = T.dropWhile (== '0') seg2+ in compare (T.length n1) (T.length n2) <> compare n1 n2 <> go rest1 rest2+ | otherwise = compare seg1 seg2 <> go rest1 rest2++ isAlpha c = isAsciiLower c || isAsciiUpper c+ isSep c = not (isDigit c || isAlpha c || c == '~' || c == '^')++-- | a version from a @v\"...\"@ literal in an expression+data VersionLiteral = VersionLiteral+ { -- | the epoch, if one was given+ vlEpoch :: !(Maybe Integer),+ vlVersion :: !Text,+ -- | the release, if one was given+ vlRelease :: !(Maybe Text)+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | parse @[epoch:]version[-release]@. 'Nothing' when the version is empty.+parseVersionLiteral :: Text -> Maybe VersionLiteral+parseVersionLiteral raw = do+ let (digits, afterDigits) = T.span isDigit raw+ (epoch, rest) = case T.uncons afterDigits of+ Just (':', more) | not (T.null digits) -> (readMaybe (T.unpack digits), more)+ _ -> (Nothing, raw)+ (version, release) = case T.breakOnEnd "-" rest of+ ("", _) -> (rest, Nothing)+ (verDash, rel) -> (T.dropEnd 1 verDash, Just rel)+ if T.null version then Nothing else Just (VersionLiteral epoch version release)++-- | compare like rpm does in expressions. a missing epoch counts as 0, and releases are only compared when both sides have one.+compareVersionLiteral :: VersionLiteral -> VersionLiteral -> Ordering+compareVersionLiteral a b =+ compare (maybe 0 id (vlEpoch a)) (maybe 0 id (vlEpoch b))+ <> rpmvercmp (vlVersion a) (vlVersion b)+ <> case (vlRelease a, vlRelease b) of+ (Just r1, Just r2) -> rpmvercmp r1 r2+ _ -> EQ
+ test/Arbitrary.hs view
@@ -0,0 +1,33 @@+module Arbitrary (SpecText (..), AnyText (..)) where++import Data.Text (Text)+import Data.Text qualified as T+import Test.QuickCheck++newtype SpecText = SpecText Text+ deriving stock (Show)++newtype AnyText = AnyText Text+ deriving stock (Show)++instance Arbitrary AnyText where+ arbitrary = AnyText . T.pack <$> listOf (elements "%{}()[]\\\n\r\t :?!#*-ab1\"'")+ shrink (AnyText t) = AnyText . T.pack <$> shrink (T.unpack t)++instance Arbitrary SpecText where+ arbitrary = SpecText . T.concat <$> listOf piece+ shrink (SpecText t) = SpecText . T.pack <$> shrink (T.unpack t)++piece :: Gen Text+piece =+ frequency+ [ (4, elements ["Name: foo", "Version:\t%{ver}", "Release: 1%{?dist}", "Requires(post): bar", "BuildRequires: pkgconfig(x) >= 1.0"]),+ (3, elements ["\n", "\r\n", " \\\n", "\n\n"]),+ (3, elements ["%global ver 1.2.3", "%define foo(a:) %{-a*}", "%undefine foo", "%bcond tests 1", "%bcond_without docs"]),+ (3, elements ["%if 0%{?fedora} >= 40", "%ifarch x86_64 %{arm}", "%else", "%elif %{with docs}", "%endif", " %endif"]),+ (3, elements ["%package devel", "%description -n foo", "%files -f list", "%prep", "%build -a", "%changelog", "%post -p /sbin/ldconfig"]),+ (3, elements ["%{name}", "%{?foo:bar}", "%{!?x:%{error:y}}", "%(echo hi)", "%[1 + 2]", "%{lua: print(1)}", "%%", "%", "%{", "%(", "%[", "%{expand:%%{a}}"]),+ (2, elements ["%(c=%{commit}; echo ${c:0:7})", "%(echo %{ver} | sed 's/-/~/g;s/^v//')", "%(echo x | tr -d 'x')", "%(echo a | sed -E 's/(a|b)+/x/')", "%(v='a b'; echo ${v//a/} | cut -d' ' -f2)", "%(echo $HOME)", "%(sed 's/[/x/')"]),+ (2, elements ["# comment %{x}", "* Mon Jan 01 2024 A <a@b> - 1-1", "- item", "make %{?_smp_mflags}"]),+ (2, T.pack <$> listOf1 (elements "abc {}()[]:%\\#"))+ ]
+ test/EditSpec.hs view
@@ -0,0 +1,40 @@+module EditSpec (spec) where++import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Calendar (fromGregorian)+import Rozbir.Edit+import Rozbir.Syntax.Parse (parse)+import Test.Hspec++applyEdit :: Text -> Either EditError [TextEdit] -> Either EditError Text+applyEdit src = fmap (`apply` src)++spec :: Spec+spec = describe "Rozbir.Edit" $ do+ let src = T.unlines ["%global ver 1.2.3", "Name: foo", "Version:\t%{ver}", "Release: 4%{?dist}", "", "%changelog", "* Mon Jan 05 2026 A <a@b> - 1.2.3-4", "- x"]+ tree = parse src+ it "follows Version to its %global" $+ applyEdit src (setTag "version" "2.0" tree) `shouldBe` Right (T.replace "%global ver 1.2.3" "%global ver 2.0" src)+ it "sets a tag literally when asked" $+ applyEdit src (setTagLiteral "Version" "2.0" tree) `shouldBe` Right (T.replace "Version:\t%{ver}" "Version:\t2.0" src)+ it "keeps the alignment of a plain tag" $+ applyEdit src (setTag "name" "bar" tree) `shouldBe` Right (T.replace "Name: foo" "Name: bar" src)+ it "bumps Release" $+ applyEdit src (bumpRelease tree) `shouldBe` Right (T.replace "Release: 4" "Release: 5" src)+ it "resets Release when setting Version" $+ applyEdit src (setVersion "9" tree) `shouldBe` Right (T.replace "Release: 4" "Release: 1" (T.replace "ver 1.2.3" "ver 9" src))+ it "refuses %autorelease" $+ bumpRelease (parse "Release: %autorelease\n") `shouldSatisfy` either (const True) (const False)+ it "refuses a value set in two branches" $+ case setTag "version" "2" (parse "%if 1\nVersion: 1\n%else\nVersion: 2\n%endif\n") of+ Left (Ambiguous _ spans) -> length spans `shouldBe` 2+ other -> expectationFailure (show other)+ it "adds a changelog entry on top" $+ applyEdit src (addChangelog (ChangelogInput (fromGregorian 2026 11 20) "B <b@c>" (Just "2.0-1") ["new"]) tree)+ `shouldBe` Right (T.replace "%changelog\n" "%changelog\n* Fri Nov 20 2026 B <b@c> - 2.0-1\n- new\n\n" src)+ it "creates %changelog when missing" $+ applyEdit "Name: x\n" (addChangelog (ChangelogInput (fromGregorian 2026 11 20) "B" Nothing ["y"]) (parse "Name: x\n"))+ `shouldBe` Right "Name: x\n\n%changelog\n* Fri Nov 20 2026 B\n- y\n"+ it "keeps %define when editing a macro" $+ applyEdit "%define v 1\nVersion: %v\n" (setTag "version" "2" (parse "%define v 1\nVersion: %v\n")) `shouldBe` Right "%define v 2\nVersion: %v\n"
+ test/EvalSpec.hs view
@@ -0,0 +1,98 @@+module EvalSpec (spec) where++import Data.Text (Text)+import Rozbir.Eval+import Rozbir.Syntax+import Rozbir.Syntax.Parse (parse)+import Test.Hspec++expandIn :: Env -> [Text] -> Value+expandIn env ts = fst (runEval (initialState env) (last <$> mapM expandText ts))++open, closed :: [Text] -> Value+open = expandIn (newEnv False)+closed = expandIn (newEnv True)++spec :: Spec+spec = describe "Rozbir.Eval" $ do+ describe "definitions" $ do+ it "expands %global eagerly" $+ open ["%global a 1", "%global b %{a}", "%global a 2", "%{b}"] `shouldBe` known "1"+ it "expands %define lazily" $+ open ["%global a 1", "%define b %{a}", "%global a 2", "%{b}"] `shouldBe` known "2"+ it "pops with %undefine" $+ closed ["%global a 1", "%global a 2", "%undefine a", "%{a}"] `shouldBe` known "1"+ it "groups a braced body" $+ open ["%global a {x y}", "%{a}"] `shouldBe` known "x y"+ it "keeps continuation lines" $+ open ["%global a x \\\ny", "%{a}"] `shouldBe` known "x \ny"+ it "unescapes the body like rpm" $+ open ["%global a 1\\\\2 \\\\\\\n3", "%{a}"] `shouldBe` known "1\\2 \\\n3"+ it "defines from inside a conditional macro" $+ closed ["%{!?a:%global a 3}", "%{a}"] `shouldBe` known "3"+ it "can't tell whether a conditional definition ran in an open environment" $+ open ["%{!?a:%global a 3}", "%{a}"] `shouldBe` opaque (Ambiguous "a")+ describe "references" $ do+ it "leaves undefined macros alone in a closed environment" $+ closed ["%{nope} %nope"] `shouldBe` known "%{nope} %nope"+ it "is opaque about unknown macros in an open one" $+ open ["x%{?dist}"] `shouldBe` (known "x" <> opaque (Undefined "dist"))+ it "knows %{?with_x} is off without a bcond" $+ open ["a%{?with_x:b}"] `shouldBe` known "a"+ it "handles %{!?x:...}" $+ closed ["%{!?x:none}"] `shouldBe` known "none"+ it "escapes %%" $+ open ["100%%"] `shouldBe` known "100%"+ it "is opaque about shell and Lua" $ do+ open ["%(date)"] `shouldBe` opaque RunsShell+ open ["%{lua: print(1)}"] `shouldBe` opaque RunsLua+ it "stops runaway recursion" $+ open ["%define a %{a}", "%{a}"] `shouldBe` opaque DepthLimit+ describe "parametric macros" $ do+ it "passes positional arguments" $+ open ["%define p() [%1|%2|%#|%*]", "%p a b"] `shouldBe` known "[a|b|2|a b]"+ it "parses options" $+ open ["%define p(n:v) %{-n*}%{?-v:V}", "%p -n x -v"] `shouldBe` known "xV"+ it "takes arguments in braces" $+ open ["%define p() <%1>", "%{p z}"] `shouldBe` known "<z>"+ it "stops arguments at the end of the line" $+ open ["%define p() <%*>", "%p a\nb"] `shouldBe` known "<a>\nb"+ it "scopes %define to the call" $+ closed ["%define p() %{expand:%%define inner 1}", "%p", "%{inner}"] `shouldBe` known "%{inner}"+ describe "builtins" $ do+ it "computes basename and dirname" $+ open ["%{basename:/a/b.tar.gz} %{dirname:/a/b} %{suffix:x.tar.gz}"] `shouldBe` known "b.tar.gz /a gz"+ it "expands twice with %{expand}" $+ open ["%global a 1", "%{expand:%%{a}}"] `shouldBe` known "1"+ it "evaluates %[...]" $+ open ["%[1 + 1]"] `shouldBe` known "2"+ it "evaluates %[...] with macros" $+ open ["%global a 3", "%[%{a} * 2]"] `shouldBe` known "6"+ it "does string functions" $+ open ["%{upper:abc}%{len:abc}%{reverse:ab}%{rep a 3}"] `shouldBe` known "ABC3baaaa"+ it "is opaque about the environment" $+ open ["%{getenv:HOME}"] `shouldBe` opaque ReadsEnv+ it "reports %{shrink}" $+ open ["%{shrink: a b }"] `shouldBe` known "a b"+ describe "bconds" $ do+ it "turns on %bcond_without" $ open ["%bcond_without docs", "%{with docs}"] `shouldBe` known "1"+ it "leaves %bcond_with off" $ open ["%bcond_with docs", "%{with docs}"] `shouldBe` known "0"+ it "reads a %bcond default" $ open ["%bcond tests 1", "%{with tests}%{without tests}"] `shouldBe` known "10"+ describe "conditions" $ do+ let cond env t = case map lineBody (treeLines (parse t)) of+ [Cond c] -> fst (runEval (initialState env) (evalCond c))+ other -> error (show other)+ x86 = withTarget (Target (Just "x86_64") (Just "linux") [("fedora", Just "44")]) (newEnv False)+ it "is three-valued for unknown macros" $+ cond (newEnv False) "%if 0%{?fedora} >= 40" `shouldBe` Unknown [Undefined "fedora"]+ it "decides with a target" $+ cond x86 "%if 0%{?fedora} >= 40" `shouldBe` Yes+ it "matches %ifarch against the target" $ do+ cond x86 "%ifarch aarch64 x86_64" `shouldBe` Yes+ cond x86 "%ifnarch x86_64" `shouldBe` No+ it "doesn't know %ifarch without an arch" $+ cond (newEnv False) "%ifarch x86_64" `shouldBe` Unknown [Undefined "_target_cpu"]+ it "joins a continued condition" $+ cond x86 "%if 1 && \\\n 0\n" `shouldBe` No+ it "uses target overrides" $+ expandIn (withTarget (Target (Just "aarch64") Nothing [("fedora", Just "44")]) (newEnv False)) ["%{fedora} %{_target_cpu}"] `shouldBe` known "44 aarch64"
+ test/ExprSpec.hs view
@@ -0,0 +1,40 @@+module ExprSpec (spec) where++import Data.Functor.Identity (runIdentity)+import Data.Text (Text)+import Rozbir.Eval.Types+import Rozbir.Syntax.Expr+import Test.Hspec++run :: Text -> Either Text ExprValue+run t = runIdentity (evalExpr False (\_ -> pure mempty) (itemsFromValue (known t)))++runWith :: Value -> Either Text ExprValue+runWith v = runIdentity (evalExpr False (\_ -> pure mempty) (itemsFromValue v))++spec :: Spec+spec = describe "Rozbir.Syntax.Expr" $ do+ it "does arithmetic" $ run "1 + 2 * 3" `shouldBe` Right (EInt 7)+ it "divides like C" $ run "-7 / 2" `shouldBe` Right (EInt (-3))+ it "compares integers" $ run "044 >= 40" `shouldBe` Right (EInt 1)+ it "compares strings" $ run "\"a\" < \"b\"" `shouldBe` Right (EInt 1)+ it "compares versions with rpmvercmp" $ run "v\"1.10\" > v\"1.9\"" `shouldBe` Right (EInt 1)+ it "treats && and || alike, left to right" $ run "1 || 0 && 0" `shouldBe` Right (EInt 0)+ it "returns an operand from &&" $ run "2 && 3" `shouldBe` Right (EInt 3)+ it "supports the ternary operator" $ run "0 ? 1 : 2" `shouldBe` Right (EInt 2)+ it "negates" $ run "!0" `shouldBe` Right (EInt 1)+ it "rejects bare words" $ run "foo" `shouldSatisfy` either (const True) (const False)+ it "rejects mixed types" $ run "1 == \"1\"" `shouldBe` Left "types must match"+ it "rejects an empty expression" $ run "" `shouldBe` Left "unexpected end of expression"+ it "rejects trailing junk" $ run "1 2" `shouldBe` Left "syntax error in expression"+ it "rejects division by zero" $ run "1 / 0" `shouldBe` Left "division by zero"+ describe "with unknown values" $ do+ let fedora = known "0" <> opaque (Undefined "fedora")+ it "is unknown when it depends on one" $+ fmap boolify (runWith (fedora <> known " >= 40")) `shouldBe` Right (Unknown [Undefined "fedora"])+ it "short-circuits &&" $+ fmap boolify (runWith (known "0 && " <> fedora)) `shouldBe` Right No+ it "short-circuits ||" $+ fmap boolify (runWith (known "1 || " <> fedora)) `shouldBe` Right Yes+ it "decides && when the other side is false" $+ fmap boolify (runWith (fedora <> known " && 0")) `shouldBe` Right No
+ test/LintSpec.hs view
@@ -0,0 +1,118 @@+module LintSpec (spec) where++import Data.Map.Strict qualified as Map+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Text qualified as T+import Rozbir.Edit (apply)+import Rozbir.Eval (newEnv, unknownTarget)+import Rozbir.Lint+import Rozbir.Syntax.Parse (parse)+import Test.Hspec++everything :: LintConfig+everything = defaultConfig {lcRuleSets = Set.fromList [minBound .. maxBound]}++lintWith :: LintConfig -> Text -> [Diagnostic]+lintWith cfg src = lintTree cfg (newEnv False) [unknownTarget] Map.empty (parse src)++rulesOf :: Text -> [RuleId]+rulesOf = map diagRule . lintWith everything++base :: [Text]+base = ["Name: x", "Version: 1", "Release: 1%{?dist}", "Summary: s", "License: MIT", "Packager: p", "", "%description", "d", ""]++withBase :: [Text] -> Text+withBase extra = T.unlines (base <> extra)++withPreamble :: [Text] -> Text+withPreamble extra = T.unlines (take 6 base <> extra <> drop 6 base)++catches :: RuleId -> Text -> Spec+catches rid src = it ("catches " <> T.unpack rid) (rulesOf src `shouldContain` [rid])++passes :: RuleId -> Text -> Spec+passes rid src = it ("lets through what " <> T.unpack rid <> " allows") (rulesOf src `shouldNotContain` [rid])++fixes :: RuleId -> Text -> Text -> Spec+fixes rid src expected = it ("fixes " <> T.unpack rid) $+ case [f | d <- lintWith everything src, diagRule d == rid, f <- diagFixes d] of+ f : _ -> apply (fixEdits f) src `shouldBe` expected+ [] -> expectationFailure "no fix offered"++spec :: Spec+spec = describe "Rozbir.Lint" $ do+ it "has no findings on a clean spec" $ rulesOf (withBase ["%files", "", "%changelog"]) `shouldBe` []+ catches "unknown-tag" (withPreamble ["Nmae: y"])+ passes "unknown-tag" (withPreamble ["Source12: y", "BuildRequires: z"])+ catches "duplicate-tag" (withPreamble ["Version: 2"])+ passes "duplicate-tag" "%if 0%{?rhel}\nVersion: 1\n%else\nVersion: 2\n%endif\n"+ catches "missing-required-tag" "Name: x\n%description\nd\n"+ catches "missing-description" (withBase ["%package devel", "Summary: y"])+ catches "section-for-unknown-package" (withBase ["%files devel"])+ passes "section-for-unknown-package" (withBase ["%package devel", "Summary: y", "%description devel", "y", "%files devel"])+ catches "duplicate-source-number" (withPreamble ["Source1: a", "Source1: b"])+ catches "macro-in-comment" (withBase ["# %global foo 1"])+ fixes "macro-in-comment" "# %{x} and %y\n" "# %%{x} and %%y\n"+ catches "needs-newer-rpm" (withBase ["%conf"])+ catches "patchn-obsolete" (withBase ["%prep", "%patch0 -p1"])+ fixes "patchn-obsolete" "%prep\n%patch0 -p1\n" "%prep\n%patch -P 0 -p1\n"+ catches "changelog-date" (withBase ["%changelog", "* Mon Nov 20 2026 A - 1-1", "- x"])+ catches "changelog-order" (withBase ["%changelog", "* Mon Jan 05 2026 A", "- x", "* Fri Nov 20 2026 A", "- y"])+ catches "unclosed-if" (withBase ["%if 1"])+ catches "eval-error" (withBase ["%if 1 +", "%endif"])+ catches "deprecated-tag" (withPreamble ["BuildRoot: /tmp"])+ fixes "deprecated-tag" "BuildPreReq: x\n" "BuildRequires: x\n"+ catches "clean-section" (withBase ["%clean"])+ catches "hardcoded-path" (withBase ["%files", "/usr/bin/x"])+ passes "hardcoded-path" (withBase ["%files", "%{_bindir}/x"])+ catches "mixed-buildroot" (withBase ["%install", "rm -rf $RPM_BUILD_ROOT", "mkdir %{buildroot}", "mkdir %{buildroot}/a"])+ catches "rpm-buildroot-usage" (withBase ["%build", "ls %{buildroot}"])+ catches "macro-in-changelog" (withBase ["%changelog", "* Fri Nov 20 2026 A", "- use %{name}"])+ passes "macro-in-changelog" (withBase ["%changelog", "%autochangelog"])+ catches "patch-not-applied" (withPreamble ["Patch1: a.patch"] <> "%prep\n%setup -q\n")+ passes "patch-not-applied" (withPreamble ["Patch1: a.patch"] <> "%prep\n%autosetup -p1\n")+ catches "setup-not-quiet" (withBase ["%prep", "%setup -n x"])+ catches "summary-ended-with-dot" "Summary: A thing.\n"+ fixes "summary-ended-with-dot" "Summary: A thing.\n" "Summary: A thing\n"+ catches "make-check-outside-check-section" (withBase ["%build", "make check"])+ catches "mixed-tabs-spaces" "Name:\tx\nVersion: 1\n"+ catches "terra-packager" "Name: x\n"+ catches "terra-dist-release" "Release: 1\n"+ fixes "terra-dist-release" "Release: 1\n" "Release: 1%{?dist}\n"+ passes "terra-dist-release" "Release: %autorelease\n"+ catches "terra-define-global" "%define foo 1\n"+ catches "terra-version-editable" "Version: %{pyver}\n"+ catches "bcond-unused" (withPreamble ["%bcond docs 1"])+ passes "bcond-unused" (withPreamble ["%bcond docs 1", "%if %{with docs}", "BuildRequires: d", "%endif"])+ catches "duplicate-dependency" (withPreamble ["Requires: a", "Requires: b, a"])+ passes "duplicate-dependency" (withPreamble ["Requires: a", "Requires(post): a"])+ catches "unversioned-obsoletes" (withPreamble ["Obsoletes: old"])+ passes "unversioned-obsoletes" (withPreamble ["Obsoletes: old < 2"])+ catches "defattr" (withBase ["%files", "%defattr(-,root,root,-)"])+ catches "rm-buildroot" (withBase ["%install", "rm -rf %{buildroot}"])+ catches "terra-py3-build" (withBase ["%build", "%py3_build"])+ catches "terra-insecure-url" (withPreamble ["URL: http://example.com"])+ describe "undefined-macro" $ do+ let closedRules src = map diagRule (lintTree everything (newEnv True) [unknownTarget] Map.empty (parse src))+ it "catches a case typo" $ closedRules "URL: https://x\nSource0: %{URL}/a.tar.gz\n" `shouldContain` ["undefined-macro"]+ it "catches a tag macro used too early" $ closedRules "Summary: %{name}\nName: n\n" `shouldContain` ["undefined-macro"]+ it "ignores %files directives" $ closedRules "%files\n%doc README\n%dir /x\n" `shouldNotContain` ["undefined-macro"]+ it "ignores rpmbuild's own macros" $ closedRules "%install\nmkdir %{buildroot}\n" `shouldNotContain` ["undefined-macro"]+ it "stays quiet in an open environment" $ rulesOf "URL: x\nSource0: %{URL}/a\n" `shouldNotContain` ["undefined-macro"]+ describe "directives" $ do+ it "suppresses the next line" $+ rulesOf (withPreamble ["# rozbir: ignore[unknown-tag] it's fine", "Nmae: y"]) `shouldNotContain` ["unknown-tag"]+ it "suppresses a whole file" $+ rulesOf (T.unlines ["# rozbir: ignore-file[unknown-tag]"] <> withPreamble ["Nmae: y"]) `shouldNotContain` ["unknown-tag"]+ it "reports a directive that suppresses nothing" $+ rulesOf (withPreamble ["# rozbir: ignore[unknown-tag]", "Version: x"]) `shouldContain` ["unused-ignore"]+ it "reports an unknown rule in a directive" $+ rulesOf (withBase ["# rozbir: ignore[no-such-rule]"]) `shouldContain` ["unused-ignore"]+ describe "config" $ do+ it "leaves the terra rules off by default" $+ map diagRule (lintWith defaultConfig "Release: 1\n") `shouldNotContain` ["terra-dist-release"]+ it "disables a rule" $+ map diagRule (lintWith everything {lcOverrides = Map.fromList [("terra-dist-release", Nothing)]} "Release: 1\n") `shouldNotContain` ["terra-dist-release"]+ it "changes a severity" $+ [diagSeverity d | d <- lintWith everything {lcOverrides = Map.fromList [("terra-dist-release", Just Error)]} "Release: 1\n", diagRule d == "terra-dist-release"] `shouldBe` [Error]
+ test/ParseSpec.hs view
@@ -0,0 +1,101 @@+module ParseSpec (spec) where++import Arbitrary+import Data.List.NonEmpty qualified as NE+import Data.Text (Text)+import Data.Text qualified as T+import Rozbir.Syntax+import Rozbir.Syntax.Parse+import Rozbir.Syntax.Render+import Test.Hspec+import Test.QuickCheck++bodies :: Text -> [LineBody]+bodies = map lineBody . treeLines . parse++spec :: Spec+spec = describe "Rozbir.Syntax.Parse" $ do+ describe "round-trips" $ do+ it "spec-like text" $ property $ \(SpecText t) -> render (parse t) === t+ it "arbitrary text" $ property $ \(AnyText t) -> render (parse t) === t+ it "frags of arbitrary text" $ property $ \(AnyText t) -> renderFrags (parseFrags t) === t++ describe "lines" $ do+ it "classifies a tag" $+ bodies "Name: foo \n" `shouldBe` [Tag (TagLine "" "Name" Nothing ": " [Lit "foo"] " ")]+ it "keeps a qualifier" $ case bodies "Requires(post): bar" of+ [Tag t] -> (qualRaw <$> tagQualifier t) `shouldBe` Just "(post)"+ other -> expectationFailure (show other)+ it "doesn't read tags inside %description" $+ bodies "%description\nName: x\n" `shouldBe` [Header (SectionHeader SDescription "%description" []), Body [Lit "Name: x"]]+ it "reads tags inside %package" $ case bodies "%package devel\nSummary: x\n" of+ [Header _, Tag _] -> pure ()+ other -> expectationFailure (show other)+ it "only treats column 0 as a section header" $ case bodies " %files\n" of+ [Body _] -> pure ()+ other -> expectationFailure (show other)+ it "matches section names case-insensitively" $ case bodies "%Description\n" of+ [Header h] -> secKind h `shouldBe` SDescription+ other -> expectationFailure (show other)+ it "parses a %global with options and body" $ case bodies "%define foo(a:b) %{-a*} \n" of+ [Define d] -> (defKind d, defName d, defOpts d, renderFrags (defBody d), defTrailing d) `shouldBe` (DefDefine, "foo", Just "a:b", "%{-a*}", " ")+ other -> expectationFailure (show other)+ it "joins a %global continued with a backslash" $ case bodies "%global foo a \\\n b\nName: x\n" of+ [Define d, Tag _] -> renderFrags (defBody d) `shouldBe` "a \\\n b"+ other -> expectationFailure (show other)+ it "doesn't join a shell line continued with a backslash" $+ length (bodies "%build\nmake \\\n%if 1\n X=1\n%endif\n") `shouldBe` 5+ it "joins lines while a macro is open" $+ length (bodies "%global x %{lua:\nprint(1)\n}\nName: y\n") `shouldBe` 2+ it "reports an unclosed macro without swallowing the file" $ do+ let tree = parse "%global x %{lua:\nName: y\n"+ map seCode (treeErrors tree) `shouldBe` ["unclosed-macro"]+ length (treeLines tree) `shouldBe` 2+ it "marks stray text in the preamble" $+ map seCode (treeErrors (parse "hello there\n")) `shouldBe` ["not-a-tag"]++ describe "conditionals" $ do+ it "nests %if blocks" $ case treeNodes (parse "%if 1\n%if 0\nA: b\n%endif\n%else\nC: d\n%endif\n") of+ [NCond c] -> do+ NE.length (condBranches c) `shouldBe` 2+ case branchNodes (NE.head (condBranches c)) of+ [NCond inner] -> NE.length (condBranches inner) `shouldBe` 1+ other -> expectationFailure (show other)+ other -> expectationFailure (show other)+ it "reports an unclosed %if" $+ map seCode (treeErrors (parse "%if 1\nName: x\n")) `shouldBe` ["unclosed-if"]+ it "reports a stray %endif" $+ map seCode (treeErrors (parse "%endif\n")) `shouldBe` ["stray-endif"]+ it "reports %else after %else" $+ map seCode (treeErrors (parse "%if 1\n%else\n%else\n%endif\n")) `shouldBe` ["branch-after-else"]+ it "doesn't take %ifarch for %if" $ case bodies "%ifarch x86_64\n%endif\n" of+ [Cond c, Cond _] -> condKind c `shouldBe` CIfArch+ other -> expectationFailure (show other)+ it "lets %if wrap sections" $ case treeNodes (parse "%if 1\n%package doc\nSummary: x\n%description doc\nd\n%endif\n") of+ [NCond c] -> length [() | NSection _ <- branchNodes (NE.head (condBranches c))] `shouldBe` 2+ other -> expectationFailure (show other)++ describe "frags" $ do+ it "parses bare and braced macros" $+ parseFrags "a %name %{?b:c} %%" `shouldBe` [Lit "a ", Macro (Bare "" "name"), Lit " ", Macro (Braced "?" "b" (Just (ColonArg [Lit "c"]))), Lit " ", Escape]+ it "parses argument macros" $+ parseFrags "%1%*%**%#%{-f*}" `shouldBe` [Macro (Bare "" "1"), Macro (Bare "" "*"), Macro (Bare "" "**"), Macro (Bare "" "#"), Macro (Braced "" "-f*" Nothing)]+ it "keeps Lua raw" $+ parseFrags "%{lua: print(\"%{x}\")}" `shouldBe` [Macro (Lua " print(\"%{x}\")")]+ it "nests braces" $+ parseFrags "%{?a:%{b}}" `shouldBe` [Macro (Braced "?" "a" (Just (ColonArg [Macro (Braced "" "b" Nothing)])))]+ it "parses space arguments" $+ parseFrags "%{foo a b}" `shouldBe` [Macro (Braced "" "foo" (Just (SpaceArg [Lit " a b"])))]+ it "treats a lone % as text" $+ parseFrags "100% sure" `shouldBe` [Lit "100% sure"]+ it "keeps unterminated macros" $+ parseFrags "x %{abc" `shouldBe` [Lit "x ", Macro (Unterminated '{' "abc")]++ describe "spans" $ do+ it "tracks lines and columns" $ do+ let ls = treeLines (parse "a: b\r\n\nName: c")+ map (posLine . spanStart . lineSpan) ls `shouldBe` [0, 1, 2]+ map lineEol ls `shouldBe` ["\r\n", "\n", ""]+ it "covers the whole text" $ property $ \(SpecText t) ->+ let ls = treeLines (parse t)+ in sum (map (\l -> let Span s e = lineFullSpan l in posOffset e - posOffset s) ls) === T.length t
+ test/QuerySpec.hs view
@@ -0,0 +1,81 @@+module QuerySpec (spec) where++import Data.Map.Strict qualified as Map+import Data.Text (Text)+import Data.Text qualified as T+import Rozbir+import Rozbir.Eval (Reason (..), Tri (..), showValue)+import Rozbir.Spec+import Test.Hspec hiding (Spec)+import Test.Hspec qualified as H++sample :: Text+sample =+ T.unlines+ [ "%global major 1",+ "%global minor 2",+ "%global ver %{major}.%{minor}",+ "%bcond docs 1",+ "",+ "Name: demo",+ "Version: %{ver}",+ "Release: 3%{?dist}",+ "Epoch: 2",+ "Summary: A demo",+ "License: MIT",+ "Source0: https://example.com/demo-%{version}.tar.gz",+ "Source: extra.txt",+ "Patch: fix.patch",+ "BuildRequires: gcc, pkgconfig(foo) >= 1.0 (a or b)",+ "%if 0%{?fedora}",+ "BuildRequires: fedora-only",+ "%endif",+ "",+ "%description",+ "Demo.",+ "",+ "%package devel",+ "Summary: Headers",+ "",+ "%description devel",+ "Headers.",+ "",+ "%files devel",+ "",+ "%changelog",+ "* Thu Nov 19 2026 Someone <a@b.c> - 2:1.2-3",+ "- first"+ ]++f44 :: Target+f44 = Target (Just "x86_64") (Just "linux") [("dist", Just ".fc44"), ("fedora", Just "44")]++spec :: H.Spec+spec = describe "Rozbir.Query" $ do+ let tree = parse sample+ open = resolve (newEnv False) unknownTarget tree+ known' = resolve (newEnv False) f44 tree+ it "reads the name" $ name open `shouldBe` Resolved "demo"+ it "can't finish the EVR without a dist" $ evr open `shouldBe` Unresolved [Undefined "dist"]+ it "resolves the EVR for a target" $ evr known' `shouldBe` Resolved (EVR 2 "1.2" "3.fc44")+ it "follows %global chains for versionInputs" $ versionInputs tree `shouldBe` ["ver", "major", "minor"]+ it "numbers sources" $+ [(srcNumber (locValue s), showValue (srcValue (locValue s))) | s <- sources open]+ `shouldBe` [(0, "https://example.com/demo-1.2.tar.gz"), (1, "extra.txt")]+ it "numbers patches" $ map (srcNumber . locValue) (patches open) `shouldBe` [0]+ it "lists subpackages" $ map (showValue . pkgName) (subpackages open) `shouldBe` ["demo-devel"]+ it "reads bconds" $ [(bcName b, bcEnabled b) | b <- map locValue (bconds open)] `shouldBe` [("docs", Yes)]+ it "splits dependencies" $+ map locValue (buildRequires known') `shouldBe` ["gcc", "pkgconfig(foo) >= 1.0", "(a or b)", "fedora-only"]+ it "guards dependencies behind unknown conditions" $+ [locGuard d /= [] | d <- buildRequires open] `shouldBe` [False, False, False, True]+ it "parses the changelog" $ length (specChangelog open) `shouldBe` 1+ it "finds macro definitions" $ Map.keys (definitions tree) `shouldBe` ["major", "minor", "ver"]+ it "keeps both branches of an unknown %if" $ do+ let t = parse "Name: x\n%if 0%{?rhel}\nVersion: 1\n%else\nVersion: 2\n%endif\nRelease: 1\n"+ version (resolve (newEnv False) unknownTarget t) `shouldBe` Unresolved [Ambiguous "version"]+ version (resolve (newEnv False) (Target Nothing Nothing [("rhel", Just "10")]) t) `shouldBe` Resolved "1"+ version (resolve (newEnv False) (Target Nothing Nothing [("rhel", Nothing)]) t) `shouldBe` Resolved "2"+ it "merges macros defined in unknown branches" $ do+ let t = parse "%if 0%{?rhel}\n%global v 1\n%else\n%global v 2\n%endif\nName: x\nVersion: %{v}\n"+ version (resolve (newEnv False) unknownTarget t) `shouldBe` Unresolved [Ambiguous "v"]
+ test/ShellSpec.hs view
@@ -0,0 +1,67 @@+module ShellSpec (spec) where++import Data.Either (isLeft)+import Data.Text (Text)+import Rozbir.Eval+import Rozbir.Eval.Shell (runShell)+import Test.Hspec++shell :: Text -> Either Text Text+shell = runShell++spec :: Spec+spec = describe "Rozbir.Eval.Shell" $ do+ it "slices a variable" $ shell "c=0123456789; echo ${c:0:7}" `shouldBe` Right "0123456"+ it "strips prefixes and suffixes" $ shell "v=v1.2.tar; echo ${v#v} ${v%.tar}" `shouldBe` Right "1.2.tar v1.2"+ it "replaces in a variable" $ shell "v=1-2-3; echo ${v//-/.} ${v/-/.}" `shouldBe` Right "1.2.3 1.2-3"+ it "measures a variable" $ shell "v=abcd; echo ${#v}" `shouldBe` Right "4"+ it "runs sed s commands" $ shell "echo v1.2-rc1 | sed 's/^v//;s/-/~/g'" `shouldBe` Right "1.2~rc1"+ it "runs several sed scripts" $ shell "echo a-b | sed -e 's/a/x/' -e 's/b/y/'" `shouldBe` Right "x-y"+ it "honors ERE quantifiers" $ shell "echo aaab | sed -E 's/a+/x/'" `shouldBe` Right "xb"+ it "keeps + literal in BRE" $ shell "echo a+b | sed 's/a+/x/'" `shouldBe` Right "xb"+ it "matches the longest leftmost" $ shell "echo xaaay | sed 's/a*y/Z/'" `shouldBe` Right "xZ"+ it "replaces with &" $ shell "echo 1.2 | sed 's/[0-9]/<&>/g'" `shouldBe` Right "<1>.<2>"+ it "handles empty matches globally like GNU sed" $ shell "echo abc | sed 's/x*/-/g'" `shouldBe` Right "-a-b-c-"+ it "translates with tr" $ shell "echo 1~2 | tr '~' '-'" `shouldBe` Right "1-2"+ it "deletes with tr" $ shell "echo v1v | tr -d v" `shouldBe` Right "1"+ it "cuts fields" $ shell "echo 1.2.3 | cut -d. -f1,3" `shouldBe` Right "1.3"+ it "cuts characters" $ shell "echo abcdef | cut -c2-4" `shouldBe` Right "bcd"+ it "splits unquoted words" $ shell "v='a b'; echo $v \"$v\"" `shouldBe` Right "a b a b"+ it "drops trailing newlines like rpm" $ shell "echo x; echo" `shouldBe` Right "x"+ describe "refuses" $ do+ it "the environment" $ shell "echo $HOME" `shouldSatisfy` isLeft+ it "other commands" $ shell "date +%Y%m%d" `shouldSatisfy` isLeft+ it "command substitution" $ shell "echo $(date)" `shouldSatisfy` isLeft+ it "redirections" $ shell "echo x > /tmp/y" `shouldSatisfy` isLeft+ it "here-strings after a pipe" $ shell "echo x | sed 's/a/b/' <<< x" `shouldSatisfy` isLeft+ it "globs" $ shell "echo *" `shouldSatisfy` isLeft+ it "back-references" $ shell "echo ab | sed 's/\\(a\\)/\\1/'" `shouldSatisfy` isLeft+ it "sed reading stdin" $ shell "sed 's/a/b/'" `shouldSatisfy` isLeft+ it "&&" $ shell "true && echo x" `shouldSatisfy` isLeft+ describe "Lua patterns in %{gsub}, checked against rpm --eval" $ do+ let gsub ws = run ["%{gsub " <> ws <> "}"]+ run ts = fst (runEval (initialState (newEnv True)) (last <$> mapM expandText ts))+ mapM_+ (\(args, out) -> it (show args) (gsub args `shouldBe` known out))+ [ ("1.2-3 - ~", "1.2~3"),+ ("a-b-c - _ 2", "a_b_c"),+ ("hello o* x", "xhxexlxlx"),+ ("hello %w+ X", "X"),+ ("1.2.3 %. -", "1-2-3"),+ ("abc .- X", "XaXbXcX"),+ ("aaa a- X", "XaXaXaX"),+ ("1.2.3rc1 %d+ <%0>", "<1>.<2>.<3>rc<1>"),+ ("foo_bar [_-] .", "foo.bar"),+ ("CAPS %u .", "...."),+ ("tag-v1.0 ^.*%-v %0", "tag-v1.0"),+ ("a.b.c [^.]+ w", "w.w.w")+ ]+ it "is opaque about captures" $ gsub "ab (a)b %1" `shouldBe` opaque RunsLua+ it "reads here-strings" $ shell "v=1-2; sed 's/-/~/g' <<< $v" `shouldBe` Right "1~2"+ it "treats a leading \\+ in BRE as a literal" $ shell "echo 1.0+abc | sed 's/\\+.*//g'" `shouldBe` Right "1.0"+ describe "in macros" $ do+ let run ts = fst (runEval (initialState (newEnv False)) (last <$> mapM expandText ts))+ it "expands the classic shortcommit" $+ run ["%global commit 0123456789abcdef", "%global shortcommit %(c=%{commit}; echo ${c:0:7})", "%{shortcommit}"] `shouldBe` known "0123456"+ it "stays opaque for real commands" $+ run ["%(git rev-parse HEAD)"] `shouldBe` opaque RunsShell
+ test/Spec.hs view
@@ -0,0 +1,24 @@+module Main (main) where++import EditSpec qualified+import EvalSpec qualified+import ExprSpec qualified+import LintSpec qualified+import ParseSpec qualified+import QuerySpec qualified+import ShellSpec qualified+import Test.Hspec (hspec)+import TotalitySpec qualified+import VersionSpec qualified++main :: IO ()+main = hspec $ do+ ParseSpec.spec+ ExprSpec.spec+ EvalSpec.spec+ ShellSpec.spec+ QuerySpec.spec+ EditSpec.spec+ LintSpec.spec+ VersionSpec.spec+ TotalitySpec.spec
+ test/TotalitySpec.hs view
@@ -0,0 +1,53 @@+module TotalitySpec (spec) where++import Arbitrary+import Control.DeepSeq (force)+import Control.Exception (evaluate)+import Data.Map.Strict qualified as Map+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Time.Calendar (fromGregorian)+import Rozbir.Edit+import Rozbir.Eval (Target (..), newEnv, unknownTarget)+import Rozbir.Lint+import Rozbir.Query+import Rozbir.Spec hiding (Spec)+import Rozbir.Syntax.Parse (parse)+import Rozbir.Syntax.Render (render)+import Test.Hspec+import Test.Hspec.QuickCheck (modifyMaxSuccess)+import Test.QuickCheck++everything :: LintConfig+everything = defaultConfig {lcRuleSets = Set.fromList [minBound .. maxBound]}++targets :: [Target]+targets = [unknownTarget, Target (Just "x86_64") (Just "linux") [("fedora", Just "44"), ("dist", Just ".fc44")]]++survives :: Text -> IO ()+survives t = do+ let tree = parse t+ _ <- evaluate (length (show (lintTree everything (newEnv False) targets Map.empty tree)))+ _ <- evaluate (length (show (lintTree everything (newEnv True) targets Map.empty tree)))+ let s = resolve (newEnv False) unknownTarget tree+ _ <- evaluate (force (specPackages s, specSections s, specSources s))+ _ <- evaluate (length (show (evr s, versionInputs tree, buildRequires s)))+ mapM_+ (\r -> either (const (pure ())) (\es -> () <$ evaluate (render (parse (apply es t)))) r)+ [ setTag "version" "9.9" tree,+ setTag "release" "2" tree,+ bumpRelease tree,+ setVersion "1.0" tree,+ setMacro "ver" "2" tree,+ addChangelog (ChangelogInput (fromGregorian 2026 11 20) "A <a@b>" (Just "1-1") ["x"]) tree+ ]+ mapM_ (\d -> mapM_ (\f -> () <$ evaluate (render (parse (apply (fixEdits f) t)))) (diagFixes d)) (lintTree everything (newEnv False) targets Map.empty tree)++spec :: Spec+spec = describe "totality" $ modifyMaxSuccess (max 600) $ do+ it "never crashes on spec-like text" $ property $ \(SpecText t) -> ioProperty (survives t >> pure True)+ it "never crashes on arbitrary text" $ property $ \(AnyText t) -> ioProperty (survives t >> pure True)+ it "keeps edits on value spans" $ property $ \(SpecText t) ->+ case setTagLiteral "version" "X" (parse t) of+ Right es -> render (parse (apply es t)) === apply es t+ Left _ -> property True
+ test/VersionSpec.hs view
@@ -0,0 +1,26 @@+module VersionSpec (spec) where++import Rozbir.Version+import Test.Hspec++spec :: Spec+spec = describe "Rozbir.Version" $ do+ it "parses version-release" $ parseEVR "1.2.3-1.fc44" `shouldBe` Just (EVR 0 "1.2.3" "1.fc44")+ it "parses an epoch" $ parseEVR "2:1.0-3" `shouldBe` Just (EVR 2 "1.0" "3")+ it "rejects a missing release" $ parseEVR "1.0" `shouldBe` Nothing+ describe "rpmvercmp" $+ mapM_+ (\(a, b, o) -> it (show a <> " vs " <> show b) (rpmvercmp a b `shouldBe` o))+ [ ("1.0", "1.0", EQ),+ ("1.0", "2.0", LT),+ ("2.0.1", "2.0", GT),+ ("1.05", "1.5", EQ),+ ("5.5p10", "5.5p2", GT),+ ("1.0~rc1", "1.0", LT),+ ("1.0^git1", "1.0", GT),+ ("1.0^git1", "1.0.1", LT),+ ("a", "1", LT),+ ("1.0a", "1.0", GT)+ ]+ it "compares literals without a release" $+ (compareVersionLiteral <$> parseVersionLiteral "1.2" <*> parseVersionLiteral "1.2-3") `shouldBe` Just EQ