chore: lift to upstream version
parent
65d135a6d1
commit
4a58e6a94c
@ -0,0 +1,225 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright © 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>.
|
@ -0,0 +1,39 @@
|
|||||||
|
# Stub-file generator for cap'n proto schemas
|
||||||
|
|
||||||
|
Generates Python stubs files from cap'n proto schemas.
|
||||||
|
Useful for IDE auto-completion and static type checking.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
Clone and install with pip:
|
||||||
|
|
||||||
|
```Python
|
||||||
|
pip install capnp-stub-generator
|
||||||
|
```
|
||||||
|
|
||||||
|
Run on a set of files:
|
||||||
|
|
||||||
|
```
|
||||||
|
capnp-stub-generator -p "path/to/capnp/schemas/**/*.capnp" \
|
||||||
|
-c "path/to/output/directory/**/*_capnp.py" "path/to/output/directory/**/*_capnp.pyi" \
|
||||||
|
-e "**/c-capnproto/**/*.capnp" \
|
||||||
|
-r
|
||||||
|
```
|
||||||
|
|
||||||
|
where the options are
|
||||||
|
|
||||||
|
- `-p` - search paths that contain schema files
|
||||||
|
- `-c` - cleanup paths (delete matching files before generation)
|
||||||
|
- `-e` - exclude paths that shall not be converted to stubs
|
||||||
|
- `-r` - recursive file search
|
||||||
|
|
||||||
|
Currently, stub files are always created adjacent to schema files.
|
||||||
|
|
||||||
|
For a runnable example, see the [test generation script](./capnp-stub-generator/tests/test_generation.py).
|
||||||
|
|
||||||
|
## Style and packaging
|
||||||
|
|
||||||
|
This repository is a fork from a company-internal repository. Issues can be reported here, will be fixed upstream, and backported.
|
||||||
|
Therefore, this repository does not (yet) contain a style checking and packaging pipeline.
|
||||||
|
|
||||||
|
The repository may become independent in the future.
|
@ -0,0 +1 @@
|
|||||||
|
"""A stub generator for *.capnp schema files."""
|
@ -0,0 +1,415 @@
|
|||||||
|
"""Helper functionality that is used in other modules of this package."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from copy import copy
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from dataclasses import field
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
BUILDER_NAME = "Builder"
|
||||||
|
READER_NAME = "Reader"
|
||||||
|
|
||||||
|
|
||||||
|
def new_builder(type_name: str) -> str:
|
||||||
|
"""Converts a type name to its builder variant.
|
||||||
|
|
||||||
|
E.g. `MyClass` becomes `MyClassBuilder`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
type_name (str): The original type name.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The builder variant.
|
||||||
|
"""
|
||||||
|
return f"{type_name}{BUILDER_NAME}"
|
||||||
|
|
||||||
|
|
||||||
|
def new_reader(type_name: str) -> str:
|
||||||
|
"""Converts a type name to its reader variant.
|
||||||
|
|
||||||
|
E.g. `MyClass` becomes `MyClassTeader`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
type_name (str): The original type name.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The reader variant.
|
||||||
|
"""
|
||||||
|
return f"{type_name}{READER_NAME}"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class TypeHint:
|
||||||
|
"""A class that captures a type hint."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
scopes: list[str] = field(default_factory=list)
|
||||||
|
affix: str = ""
|
||||||
|
primary: bool = False
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
"""The string representation of the type hint.
|
||||||
|
|
||||||
|
This is composed of the scopes (if any), the name of the hint, and the affix (if any).
|
||||||
|
"""
|
||||||
|
if not self.scopes:
|
||||||
|
return f"{self.name}{self.affix}"
|
||||||
|
|
||||||
|
else:
|
||||||
|
return f"{'.'.join(self.scopes)}.{self.name}{self.affix}"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class TypeHintedVariable:
|
||||||
|
"""A class that represents a type hinted variable."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
type_hints: list[TypeHint]
|
||||||
|
default: str = ""
|
||||||
|
nesting_depth: int = 0
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
"""Sanity check for provided type hints."""
|
||||||
|
primary_type_hint_count = 0
|
||||||
|
|
||||||
|
for type_hint in self.type_hints:
|
||||||
|
if type_hint.primary:
|
||||||
|
primary_type_hint_count += 1
|
||||||
|
|
||||||
|
if primary_type_hint_count != 1:
|
||||||
|
raise ValueError(f"There can only be exactly one primary type hint. Found {primary_type_hint_count}")
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
"""String representation of this object.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The string representation.
|
||||||
|
"""
|
||||||
|
return self.typed_variable_with_full_hints
|
||||||
|
|
||||||
|
def _nest(self, unnested_type_name: str) -> str:
|
||||||
|
if self.nesting_depth > 0:
|
||||||
|
return f'{self.nesting_depth * "Sequence["}{unnested_type_name}{self.nesting_depth * "]"}'
|
||||||
|
|
||||||
|
else:
|
||||||
|
return unnested_type_name
|
||||||
|
|
||||||
|
@property
|
||||||
|
def typed_variable_with_full_hints(self) -> str:
|
||||||
|
"""Returns the typed variable string, hinted will all available type hints."""
|
||||||
|
return self._generate_typed_variable(self.full_type)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def typed_variable_with_primary_hint(self) -> str:
|
||||||
|
"""Returns the typed variable string, hinted only with the primary type hint."""
|
||||||
|
if self.primary_type_hint is None:
|
||||||
|
raise ValueError("No primary type hint available.")
|
||||||
|
|
||||||
|
return self._generate_typed_variable(str(self.primary_type_hint))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def primary_type_hint(self) -> TypeHint:
|
||||||
|
"""Returns the primary type hint."""
|
||||||
|
for type_hint in self.type_hints:
|
||||||
|
if type_hint.primary:
|
||||||
|
return type_hint
|
||||||
|
|
||||||
|
raise RuntimeError("Primary type hint not found.")
|
||||||
|
|
||||||
|
def _generate_typed_variable(self, type_name: str) -> str:
|
||||||
|
"""Generate the typed variable string for a chosen type name.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
type_name (str): The type name to use.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The typed variable string.
|
||||||
|
"""
|
||||||
|
nested_type_name = self._nest(type_name)
|
||||||
|
typed_variable = f"{self.name}: {nested_type_name}"
|
||||||
|
|
||||||
|
if self.default:
|
||||||
|
return f"{typed_variable} = {self.default}"
|
||||||
|
|
||||||
|
else:
|
||||||
|
return typed_variable
|
||||||
|
|
||||||
|
def _get_type_hints_for_affixes(self, affixes: list[str]) -> list[TypeHint]:
|
||||||
|
return [self.get_type_hint_for_affix(affix) for affix in affixes]
|
||||||
|
|
||||||
|
def get_typed_variable_with_affixes(self, affixes: list[str] | None) -> str:
|
||||||
|
"""Gets a typed version of this variable with the selected type hint affixes.
|
||||||
|
|
||||||
|
For example, when selecting the affixes "Reader" and "Builder" for the primary type "Something" and the variable
|
||||||
|
named "VariableName", this will return "VariableName: SomethingReader | SomethingBuilder".
|
||||||
|
|
||||||
|
Args:
|
||||||
|
affixes (list[str] | None): The affixes to select for type hints.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The typed variable in string format.
|
||||||
|
"""
|
||||||
|
type_hints: list[TypeHint] = []
|
||||||
|
|
||||||
|
if affixes is not None:
|
||||||
|
type_hints_for_affixes = self._get_type_hints_for_affixes(affixes)
|
||||||
|
|
||||||
|
if type_hints_for_affixes is not None:
|
||||||
|
type_hints.extend(type_hints_for_affixes)
|
||||||
|
|
||||||
|
return self._generate_typed_variable(self._join_type_hints(type_hints))
|
||||||
|
|
||||||
|
def _join_type_hints(self, type_hints: list[TypeHint]) -> str:
|
||||||
|
return " | ".join(str(type_hint) for type_hint in type_hints)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def full_type(self) -> str:
|
||||||
|
"""The full type string of the hinted variable."""
|
||||||
|
return self._join_type_hints(self.type_hints)
|
||||||
|
|
||||||
|
def add_type_hint(self, new_type_hint: TypeHint):
|
||||||
|
"""Add a type hint to the hinted variable.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
new_type_hint (TypeHint): The type hint to add.
|
||||||
|
"""
|
||||||
|
for type_hint in self.type_hints:
|
||||||
|
if type_hint == new_type_hint:
|
||||||
|
raise ValueError("Type hint already exists.")
|
||||||
|
|
||||||
|
if new_type_hint.primary:
|
||||||
|
raise ValueError("There can only be one primary type.")
|
||||||
|
|
||||||
|
self.type_hints.append(new_type_hint)
|
||||||
|
|
||||||
|
def add_type_scope(self, scope: str):
|
||||||
|
"""Add a scope to the type name.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
scope (str): The scope name to prefix to the type name.
|
||||||
|
"""
|
||||||
|
for type_hint in self.type_hints:
|
||||||
|
type_hint.scopes.append(scope)
|
||||||
|
|
||||||
|
def get_type_hint_for_affix(self, affix: str) -> TypeHint:
|
||||||
|
"""Looks for a type hint that has the provided affix and returns it.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
affix (str | None): The affix to look for.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
TypeHint: The type hint that was found.
|
||||||
|
"""
|
||||||
|
for type_hint in self.type_hints:
|
||||||
|
if type_hint.affix == affix:
|
||||||
|
return type_hint
|
||||||
|
|
||||||
|
raise KeyError(f"Affix '{affix}' is not present in any recorded type hint.")
|
||||||
|
|
||||||
|
def has_type_hint_with_affix(self, affix: str) -> bool:
|
||||||
|
"""Assess, whether or not the variable has a type hint with the provided affix."""
|
||||||
|
try:
|
||||||
|
self.get_type_hint_for_affix(affix)
|
||||||
|
|
||||||
|
except KeyError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
else:
|
||||||
|
return True
|
||||||
|
|
||||||
|
@property
|
||||||
|
def has_type_hint_with_builder_affix(self) -> bool:
|
||||||
|
"""Whether the variable holds a type hint with a builder affix."""
|
||||||
|
return self.has_type_hint_with_affix(BUILDER_NAME)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def has_type_hint_with_reader_affix(self) -> bool:
|
||||||
|
"""Whether the variable holds a type hint with a reader affix."""
|
||||||
|
return self.has_type_hint_with_affix(READER_NAME)
|
||||||
|
|
||||||
|
def add_builder_from_primary_type(self):
|
||||||
|
"""Add a type hint with builder affix, based on the primary type."""
|
||||||
|
self.add_type_hint(TypeHint(self.primary_type_hint.name, copy(self.primary_type_hint.scopes), BUILDER_NAME))
|
||||||
|
|
||||||
|
def add_reader_from_primary_type(self):
|
||||||
|
"""Add a type hint with builder affix, based on the primary type."""
|
||||||
|
self.add_type_hint(
|
||||||
|
TypeHint(
|
||||||
|
self.primary_type_hint.name,
|
||||||
|
copy(self.primary_type_hint.scopes),
|
||||||
|
READER_NAME,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def replace_capnp_suffix(original: str) -> str:
|
||||||
|
"""If found, replaces the .capnp suffix in a string with _capnp.
|
||||||
|
|
||||||
|
For example, `some_module.capnp` becomes `some_module_capnp`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
original (str): The string to replace the suffix in.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The string with the replaced suffix.
|
||||||
|
"""
|
||||||
|
if original.endswith(".capnp"):
|
||||||
|
return original.replace(".capnp", "_capnp")
|
||||||
|
|
||||||
|
else:
|
||||||
|
return original
|
||||||
|
|
||||||
|
|
||||||
|
def join_parameters(parameters: list[TypeHintedVariable] | list[str] | None) -> str:
|
||||||
|
"""Joins parameters by means of ', '.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
parameters (list[HintedVariable] | list[str] | None): The parameters to join.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The joined parameters.
|
||||||
|
"""
|
||||||
|
if parameters:
|
||||||
|
return ", ".join(str(p) for p in parameters if p)
|
||||||
|
|
||||||
|
else:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def new_type_alias(alias: str, type_name: str) -> str:
|
||||||
|
"""Generate a string for a type-alias.
|
||||||
|
|
||||||
|
For example, for a type alias `SomeType` with a type `TheType` this gives `SomeType = TheType`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
alias (str): The alias name.
|
||||||
|
type_name (str): The aliased type.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The type alias.
|
||||||
|
"""
|
||||||
|
return f"{alias} = {type_name}"
|
||||||
|
|
||||||
|
|
||||||
|
def new_group(name: str, members: list[str]) -> str:
|
||||||
|
"""Create a string for a group name and its members.
|
||||||
|
|
||||||
|
For example, when the group name is 'Type', and the parameters are 'str', and 'int',
|
||||||
|
the output will be 'Type[str, int]'.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name (str): The name of the group.
|
||||||
|
members (list[str]): The members of the group
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The resulting group string.
|
||||||
|
"""
|
||||||
|
return f"{name}[{join_parameters(members)}]"
|
||||||
|
|
||||||
|
|
||||||
|
def new_type_group(name: str, types: list[str]) -> str:
|
||||||
|
"""Create a string for a parameter with types.
|
||||||
|
|
||||||
|
Uses `new_group` internally.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name (str): The name of the parameter.
|
||||||
|
types (list[str]): The list of types to that this parameter can have.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The resulting parameter string.
|
||||||
|
"""
|
||||||
|
return new_group(name, types)
|
||||||
|
|
||||||
|
|
||||||
|
def new_function(
|
||||||
|
name: str, parameters: list[TypeHintedVariable] | list[str] | None = None, return_type: str | None = None
|
||||||
|
) -> str:
|
||||||
|
"""Create a string for a function.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name (str): The function name.
|
||||||
|
parameters (list[HintedVariable] | list[str] | None, optional): The function parameters, if any. Defaults to None.
|
||||||
|
return_type (str | None, optional): The function's return type. Defaults to None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The function string.
|
||||||
|
"""
|
||||||
|
if return_type is None:
|
||||||
|
return_type = "None"
|
||||||
|
|
||||||
|
arguments = join_parameters(parameters)
|
||||||
|
return f"def {name}({arguments}) -> {return_type}: ..."
|
||||||
|
|
||||||
|
|
||||||
|
def new_decorator(name: str, parameters: list[TypeHintedVariable] | list[str] | None = None) -> str:
|
||||||
|
"""Create a new decorator.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name (str): The name of the decorator.
|
||||||
|
parameters (list[HintedVariable] | list[str] | None, optional): The parameters (args, kwargs) of the decorator,
|
||||||
|
if any. Defaults to None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The decorator string.
|
||||||
|
"""
|
||||||
|
if parameters:
|
||||||
|
return f"@{name}({join_parameters(parameters)})"
|
||||||
|
|
||||||
|
else:
|
||||||
|
return f"@{name}"
|
||||||
|
|
||||||
|
|
||||||
|
def new_constructor(kwargs: list[str] | None = None) -> str:
|
||||||
|
"""Creates a new constructor.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
kwargs (list[str] | None, optional): The keyword arguments for the constructor. Defaults to None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The constructor string.
|
||||||
|
"""
|
||||||
|
constructor_args = "self"
|
||||||
|
|
||||||
|
kwargs_ = ""
|
||||||
|
|
||||||
|
if kwargs:
|
||||||
|
# Prepend '*' for catching any positional arguments, before the keyword arguments.
|
||||||
|
kwargs_ = join_parameters(["*"] + [f"{kwarg} = ..." for kwarg in kwargs])
|
||||||
|
|
||||||
|
return new_function("__init__", parameters=[constructor_args, kwargs_])
|
||||||
|
|
||||||
|
|
||||||
|
def new_class_declaration(name: str, parameters: list[str] | None = None) -> str:
|
||||||
|
"""Creates a string for declaring a class.
|
||||||
|
|
||||||
|
For example, for a name of 'SomeClass' and a list of parameters that is 'str, Type[str, int]', the output
|
||||||
|
will be 'SomeClass (str, Type[str, int]):'.
|
||||||
|
|
||||||
|
If no parameters are provided, the output is just 'SomeClass:'.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name (str): The class name.
|
||||||
|
parameters (list[str] | None, optional):
|
||||||
|
A list of parameters that are part of the class declaration. Defaults to None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The class declaration.
|
||||||
|
"""
|
||||||
|
if parameters:
|
||||||
|
return f"class {name}({join_parameters(parameters)}):"
|
||||||
|
|
||||||
|
else:
|
||||||
|
return f"class {name}:"
|
||||||
|
|
||||||
|
|
||||||
|
def get_display_name(schema: Any) -> str:
|
||||||
|
"""Extract the display name from a schema.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
schema (Any): The schema to get the display name from.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The display name of the schema.
|
||||||
|
"""
|
||||||
|
return schema.node.displayName[schema.node.displayNamePrefixLength :]
|
@ -0,0 +1,150 @@
|
|||||||
|
"""This module defines the scope, a unit of indented text."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import dataclasses
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from .helper import TypeHintedVariable
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
INDENT_SPACES = 4
|
||||||
|
|
||||||
|
|
||||||
|
class NoParentError(Exception):
|
||||||
|
"""Raised, when the parent of a scope is not available."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclasses.dataclass
|
||||||
|
class Scope:
|
||||||
|
"""A scope within the output .pyi file.
|
||||||
|
|
||||||
|
Scopes contain text and are indented by a certain amount. They often have parents, within which they are located.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name (str): The name of the scope. Use an empty name for the root scope ("").
|
||||||
|
id (int): A numerical identifier of the scope.
|
||||||
|
parent (Scope | None): The direct parent scope of this scope, if there is any.
|
||||||
|
return scope (Scope | None): The scope to which to return, when closing this one.
|
||||||
|
lines (list[str]): The list of text lines in this scope.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
id: int
|
||||||
|
parent: Scope | None
|
||||||
|
return_scope: Scope | None
|
||||||
|
lines: list[str] = dataclasses.field(default_factory=list)
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
"""Assures that, if this is the root scope, its name is empty."""
|
||||||
|
assert (self.is_root) == (self.name == "")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def parents(self) -> list[Scope]:
|
||||||
|
"""A list of all parent scopes of this scope, starting from the first parent.
|
||||||
|
|
||||||
|
If the returned list is empty, this scope has no parents. The first parent in the list has no further
|
||||||
|
parents, it is the root scope.
|
||||||
|
"""
|
||||||
|
parents: list[Scope] = []
|
||||||
|
scope: Scope | None = self.parent
|
||||||
|
|
||||||
|
while scope is not None:
|
||||||
|
parents.append(scope)
|
||||||
|
scope = scope.parent
|
||||||
|
|
||||||
|
parents.reverse()
|
||||||
|
|
||||||
|
return parents
|
||||||
|
|
||||||
|
@property
|
||||||
|
def trace(self) -> list[Scope]:
|
||||||
|
"""A list of all scopes that lead to this scope, starting from the first parent.
|
||||||
|
|
||||||
|
The first parent has no further parents.
|
||||||
|
"""
|
||||||
|
return self.parents + [self]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def root(self) -> Scope:
|
||||||
|
"""Get the root scope that has no further parents."""
|
||||||
|
if not self.parents:
|
||||||
|
return self
|
||||||
|
|
||||||
|
else:
|
||||||
|
return self.parents[0]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_root(self) -> bool:
|
||||||
|
"""Determine, whether this is the root scope."""
|
||||||
|
return self.root == self
|
||||||
|
|
||||||
|
@property
|
||||||
|
def indent_spaces(self) -> int:
|
||||||
|
"""The number of spaces by which this scope is indented."""
|
||||||
|
return len(self.parents) * INDENT_SPACES
|
||||||
|
|
||||||
|
def add(self, content: str | TypeHintedVariable = ""):
|
||||||
|
"""Add content to this scope, taking into account the current indent spaces.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
content (str | HintedVariable): The line or variable to add. Optional, defaults to "".
|
||||||
|
"""
|
||||||
|
if isinstance(content, TypeHintedVariable):
|
||||||
|
content = str(content)
|
||||||
|
|
||||||
|
if not content:
|
||||||
|
self.lines.append("")
|
||||||
|
|
||||||
|
else:
|
||||||
|
self.lines.append(" " * self.indent_spaces + content)
|
||||||
|
|
||||||
|
def trace_as_str(self, delimiter: Literal[".", "_"] = ".") -> str:
|
||||||
|
"""A string representation of this scope's relative trace.
|
||||||
|
|
||||||
|
Follow the trace of the scope, and connect parent scopes with a delimiter.
|
||||||
|
The root scope is not included in this trace string.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
delimiter (Literal[".", "_"]): The delimiter to join the scope names with.
|
||||||
|
"""
|
||||||
|
return delimiter.join(scope.name for scope in self.trace if (not scope.is_root) and (scope.name))
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
"""A string representation of this scope.
|
||||||
|
|
||||||
|
Follow the path of scopes, and connect parent scopes with '.'.
|
||||||
|
"""
|
||||||
|
return self.trace_as_str(".")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclasses.dataclass
|
||||||
|
class CapnpType:
|
||||||
|
"""Represents a type that is extracted from a .capnp schema.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
schema (Any):
|
||||||
|
name (str):
|
||||||
|
scope (Scope):
|
||||||
|
generic_params (list[str]):
|
||||||
|
"""
|
||||||
|
|
||||||
|
schema: Any
|
||||||
|
name: str
|
||||||
|
scope: Scope
|
||||||
|
generic_params: list[str] = dataclasses.field(default_factory=list)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def scoped_name(self) -> str:
|
||||||
|
"""Extract the name of a type, taking into account its containing scope.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The scoped type name.
|
||||||
|
"""
|
||||||
|
if not self.scope.is_root:
|
||||||
|
return f"{self.scope}.{self.name}"
|
||||||
|
|
||||||
|
else:
|
||||||
|
return self.name
|
@ -0,0 +1,945 @@
|
|||||||
|
"""Generate type hints for *.capnp schemas.
|
||||||
|
|
||||||
|
Note: This generator requires pycapnp >= 1.0.0.
|
||||||
|
|
||||||
|
Note: capnp interfaces (RPC) are not yet supported.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os.path
|
||||||
|
import pathlib
|
||||||
|
from types import ModuleType
|
||||||
|
from typing import Any
|
||||||
|
from typing import Literal
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
import capnp # type: ignore
|
||||||
|
from capnp_stub_generator import capnp_types
|
||||||
|
from capnp_stub_generator import helper
|
||||||
|
from capnp_stub_generator.scope import CapnpType
|
||||||
|
from capnp_stub_generator.scope import NoParentError
|
||||||
|
from capnp_stub_generator.scope import Scope
|
||||||
|
|
||||||
|
capnp.remove_import_hook()
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
InitChoice = Tuple[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
class Writer:
|
||||||
|
"""A class that handles writing the stub file, based on a provided module definition."""
|
||||||
|
|
||||||
|
VALID_TYPING_IMPORTS = Literal["Iterator", "Generic", "TypeVar", "Sequence", "Literal", "Union", "overload"]
|
||||||
|
|
||||||
|
def __init__(self, module: ModuleType, module_registry: capnp_types.ModuleRegistryType):
|
||||||
|
"""Initialize the stub writer with a module definition.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
module (ModuleType): The module definition to parse and write a stub for.
|
||||||
|
module_registry (ModuleRegistryType): The module registry, for finding dependencies between loaded modules.
|
||||||
|
"""
|
||||||
|
self.scope = Scope(name="", id=module.schema.node.id, parent=None, return_scope=None)
|
||||||
|
self.scopes_by_id: dict[int, Scope] = {self.scope.id: self.scope}
|
||||||
|
|
||||||
|
self._module = module
|
||||||
|
self._module_registry = module_registry
|
||||||
|
|
||||||
|
if self._module.__file__:
|
||||||
|
self._module_path = pathlib.Path(self._module.__file__)
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise ValueError("The module has no file path attached to it.")
|
||||||
|
|
||||||
|
self._imports: set[str] = set()
|
||||||
|
self._add_import("from __future__ import annotations")
|
||||||
|
|
||||||
|
self._typing_imports: set[Writer.VALID_TYPING_IMPORTS] = set()
|
||||||
|
|
||||||
|
self.type_vars: set[str] = set()
|
||||||
|
self.type_map: dict[int, CapnpType] = {}
|
||||||
|
|
||||||
|
self.docstring = f'"""This is an automatically generated stub for `{self._module_path.name}`."""'
|
||||||
|
|
||||||
|
def _add_typing_import(self, module_name: Writer.VALID_TYPING_IMPORTS):
|
||||||
|
"""Add an import for a module from the 'typing' package.
|
||||||
|
|
||||||
|
E.g., when using
|
||||||
|
add_typing_import("Sequence")
|
||||||
|
add_typing_import("Union")
|
||||||
|
|
||||||
|
this generates an import line `from typing import Sequence, Union`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
module_name (Writer.VALID_TYPING_IMPORTS): The module to import from `typing`.
|
||||||
|
"""
|
||||||
|
self._typing_imports.add(module_name)
|
||||||
|
|
||||||
|
def _add_import(self, import_line: str):
|
||||||
|
"""Add a full import line.
|
||||||
|
|
||||||
|
E.g. 'import numpy as np'.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
import_line (str): The import line to add.
|
||||||
|
"""
|
||||||
|
self._imports.add(import_line)
|
||||||
|
|
||||||
|
def _add_enum_import(self):
|
||||||
|
"""Adds an import for the `Enum` class."""
|
||||||
|
self._add_import("from enum import Enum")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def full_display_name(self) -> str:
|
||||||
|
"""The base name of this writer's target module."""
|
||||||
|
return self._module.schema.node.displayName
|
||||||
|
|
||||||
|
@property
|
||||||
|
def display_name(self) -> str:
|
||||||
|
"""The base name of this writer's target module."""
|
||||||
|
return pathlib.Path(self._module.schema.node.displayName).name
|
||||||
|
|
||||||
|
@property
|
||||||
|
def imports(self) -> list[str]:
|
||||||
|
"""Get the full list of import strings that were added to the writer, including typing imports.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list[str]: The list of imports that were previously added.
|
||||||
|
"""
|
||||||
|
import_lines: list[str] = []
|
||||||
|
|
||||||
|
for imp in self._imports:
|
||||||
|
import_lines.append(imp)
|
||||||
|
|
||||||
|
if self._typing_imports:
|
||||||
|
import_lines.append("from typing import " + ", ".join(sorted(self._typing_imports)))
|
||||||
|
|
||||||
|
return import_lines
|
||||||
|
|
||||||
|
def gen_slot(
|
||||||
|
self,
|
||||||
|
raw_field: Any,
|
||||||
|
field: Any,
|
||||||
|
new_type: CapnpType,
|
||||||
|
init_choices: list[InitChoice],
|
||||||
|
) -> helper.TypeHintedVariable | None:
|
||||||
|
"""Generates a new type from a slot. Which type, is later determined.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
raw_field (Any): The raw content of the field.
|
||||||
|
field (Any): The field to generate the type from.
|
||||||
|
new_type (CapnpType): The new type that was registered previously.
|
||||||
|
init_choices (list[InitChoice]): A list of possible (overload) `init` functions that are populated
|
||||||
|
by this method.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
helper.TypeHintedVariable | None: The type hinted variable that was created, or None otherwise.
|
||||||
|
"""
|
||||||
|
hinted_variable: helper.TypeHintedVariable | None
|
||||||
|
field_slot_type = field.slot.type.which()
|
||||||
|
|
||||||
|
if field_slot_type == capnp_types.CapnpElementType.LIST:
|
||||||
|
hinted_variable = self.gen_list_slot(field, raw_field.schema)
|
||||||
|
|
||||||
|
elif field_slot_type in capnp_types.CAPNP_TYPE_TO_PYTHON:
|
||||||
|
hinted_variable = self.gen_python_type_slot(field, field_slot_type)
|
||||||
|
|
||||||
|
elif field_slot_type == capnp_types.CapnpElementType.ENUM:
|
||||||
|
hinted_variable = self.gen_enum_slot(field, raw_field.schema)
|
||||||
|
|
||||||
|
elif field_slot_type == capnp_types.CapnpElementType.STRUCT:
|
||||||
|
hinted_variable = self.gen_struct_slot(field, raw_field.schema, init_choices)
|
||||||
|
hinted_variable.add_builder_from_primary_type()
|
||||||
|
hinted_variable.add_reader_from_primary_type()
|
||||||
|
|
||||||
|
elif field_slot_type == capnp_types.CapnpElementType.ANY_POINTER:
|
||||||
|
hinted_variable = self.gen_any_pointer_slot(field, new_type)
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise TypeError(f"Unknown field slot type {field_slot_type}.")
|
||||||
|
|
||||||
|
return hinted_variable
|
||||||
|
|
||||||
|
def gen_list_slot(
|
||||||
|
self, field: capnp.lib.capnp._DynamicStructReader, schema: capnp.lib.capnp._ListSchema
|
||||||
|
) -> helper.TypeHintedVariable:
|
||||||
|
"""Generate a slot, which contains a `list`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field (capnp.lib.capnp._DynamicStructReader): The field reader.
|
||||||
|
schema (capnp.lib.capnp._ListSchema): The schema of the list.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
helper.TypeHintedVariable: The extracted hinted variable object.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def schema_elements(schema: capnp.lib.capnp._ListSchema) -> capnp.lib.capnp._ListSchema:
|
||||||
|
"""An iterator over the schema elements of nested lists.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
schema (capnp.lib.capnp._ListSchema): The schema of a list.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
capnp.lib.capnp._ListSchema: The next deeper nested list schema.
|
||||||
|
"""
|
||||||
|
next_schema_element = schema
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
next_schema_element = next_schema_element.elementType
|
||||||
|
|
||||||
|
except (AttributeError, capnp.KjException):
|
||||||
|
break
|
||||||
|
|
||||||
|
else:
|
||||||
|
yield next_schema_element
|
||||||
|
|
||||||
|
def list_elements(list_: capnp.lib.capnp._DynamicStructReader) -> capnp.lib.capnp._DynamicStructReader:
|
||||||
|
"""An iterator over the list elements of nested lists.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
list_ (capnp.lib.capnp._DynamicStructReader): A list element.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
capnp.lib.capnp._DynamicStructReader: The next deeper nested list element.
|
||||||
|
"""
|
||||||
|
next_list_element = list_
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
next_list_element = next_list_element.list.elementType
|
||||||
|
|
||||||
|
except (AttributeError, capnp.KjException):
|
||||||
|
break
|
||||||
|
|
||||||
|
else:
|
||||||
|
yield next_list_element
|
||||||
|
|
||||||
|
list_depth: int = 1
|
||||||
|
nested_schema_elements = list(schema_elements(schema))
|
||||||
|
nested_list_elements = list(list_elements(field.slot.type))
|
||||||
|
|
||||||
|
create_extended_types = True
|
||||||
|
|
||||||
|
try:
|
||||||
|
last_element = nested_schema_elements[-1]
|
||||||
|
|
||||||
|
self.generate_nested(last_element)
|
||||||
|
list_depth = len(nested_schema_elements)
|
||||||
|
new_type = self.get_type_by_id(last_element.node.id)
|
||||||
|
type_name = new_type.scoped_name
|
||||||
|
|
||||||
|
except (AttributeError, IndexError):
|
||||||
|
# An attribute error indicates that the last element was not registered as a type, as it is a basic type.
|
||||||
|
# An index error indicates that the list is not nested.
|
||||||
|
last_element = nested_list_elements[-1]
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.generate_nested(last_element)
|
||||||
|
|
||||||
|
except AttributeError:
|
||||||
|
# This is a built-in type and does not require generation.
|
||||||
|
create_extended_types = False
|
||||||
|
type_name = self.get_type_name(last_element)
|
||||||
|
|
||||||
|
else:
|
||||||
|
type_name = self.get_type_name(field.slot.type.list.elementType)
|
||||||
|
|
||||||
|
list_depth = len(nested_list_elements)
|
||||||
|
|
||||||
|
self._add_typing_import("Sequence")
|
||||||
|
|
||||||
|
hinted_variable = helper.TypeHintedVariable(
|
||||||
|
field.name, [helper.TypeHint(type_name, primary=True)], nesting_depth=list_depth
|
||||||
|
)
|
||||||
|
|
||||||
|
if create_extended_types:
|
||||||
|
hinted_variable.add_builder_from_primary_type()
|
||||||
|
hinted_variable.add_reader_from_primary_type()
|
||||||
|
|
||||||
|
return hinted_variable
|
||||||
|
|
||||||
|
def gen_python_type_slot(
|
||||||
|
self, field: capnp.lib.capnp._DynamicStructReader, field_type: str
|
||||||
|
) -> helper.TypeHintedVariable:
|
||||||
|
"""Generate a slot, which contains a regular Python type.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field (capnp.lib.capnp._DynamicStructReader): The field reader.
|
||||||
|
field_type (str): The (primitive) type of the slot.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
helper.HintedVariable: The extracted hinted variable object.
|
||||||
|
"""
|
||||||
|
python_type_name: str = capnp_types.CAPNP_TYPE_TO_PYTHON[field_type]
|
||||||
|
return helper.TypeHintedVariable(field.name, [helper.TypeHint(python_type_name, primary=True)])
|
||||||
|
|
||||||
|
def gen_enum_slot(self, field: capnp.lib.capnp._DynamicStructReader, schema) -> helper.TypeHintedVariable:
|
||||||
|
"""Generate a slot, which contains a `enum`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field (capnp.lib.capnp._DynamicStructReader): The field reader.
|
||||||
|
schema (capnp.lib.capnp._StructSchema): The schema of the field.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The type-hinted slot.
|
||||||
|
"""
|
||||||
|
if not self.is_type_id_known(field.slot.type.enum.typeId):
|
||||||
|
try:
|
||||||
|
self.generate_nested(schema)
|
||||||
|
|
||||||
|
except NoParentError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
type_name = self.get_type_name(field.slot.type)
|
||||||
|
return helper.TypeHintedVariable(field.name, [helper.TypeHint(type_name, primary=True)])
|
||||||
|
|
||||||
|
def gen_struct_slot(
|
||||||
|
self,
|
||||||
|
field: capnp.lib.capnp._DynamicStructReader,
|
||||||
|
schema: capnp.lib.capnp._StructSchema,
|
||||||
|
init_choices: list[InitChoice],
|
||||||
|
) -> helper.TypeHintedVariable:
|
||||||
|
"""Generate a slot, which contains a `struct`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field (capnp.lib.capnp._DynamicStructReader): The field reader.
|
||||||
|
schema (capnp.lib.capnp._StructSchema): The schema of the field.
|
||||||
|
init_choices (list[InitChoice]): A list of overloaded `init` function choices, to be filled by this function.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
helper.HintedVariable: The extracted hinted variable object.
|
||||||
|
"""
|
||||||
|
if not self.is_type_id_known(schema.node.id):
|
||||||
|
self.gen_struct(schema)
|
||||||
|
|
||||||
|
type_name = self.get_type_name(field.slot.type)
|
||||||
|
init_choices.append((field.name, type_name))
|
||||||
|
return helper.TypeHintedVariable(field.name, [helper.TypeHint(type_name, primary=True)])
|
||||||
|
|
||||||
|
def gen_any_pointer_slot(
|
||||||
|
self, field: capnp.lib.capnp._DynamicStructReader, new_type: CapnpType
|
||||||
|
) -> helper.TypeHintedVariable | None:
|
||||||
|
"""Generate a slot, which contains an `any_pointer` object.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field (capnp.lib.capnp._DynamicStructReader): The field reader.
|
||||||
|
new_type (CapnpType): The new type that was registered previously.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
helper.HintedVariable | None: The extracted hinted variable object, or None in case of error.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
param = field.slot.type.anyPointer.parameter
|
||||||
|
type_name = new_type.generic_params[param.parameterIndex]
|
||||||
|
return helper.TypeHintedVariable(field.name, [helper.TypeHint(type_name)])
|
||||||
|
|
||||||
|
except capnp.KjException:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def gen_const(self, schema: capnp.lib.capnp._StructSchema) -> None:
|
||||||
|
"""Generate a `const` object.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
schema (capnp.lib.capnp._StructSchema): The schema to generate the `const` object out of.
|
||||||
|
"""
|
||||||
|
assert schema.node.which() == capnp_types.CapnpElementType.CONST
|
||||||
|
|
||||||
|
const_type = schema.node.const.type.which()
|
||||||
|
name = helper.get_display_name(schema)
|
||||||
|
|
||||||
|
if const_type in capnp_types.CAPNP_TYPE_TO_PYTHON:
|
||||||
|
python_type = capnp_types.CAPNP_TYPE_TO_PYTHON[schema.node.const.type.which()]
|
||||||
|
self.scope.add(helper.TypeHintedVariable(name, [helper.TypeHint(python_type, primary=True)]))
|
||||||
|
|
||||||
|
elif const_type == "struct":
|
||||||
|
pass
|
||||||
|
|
||||||
|
def gen_enum(self, schema: capnp.lib.capnp._StructSchema) -> CapnpType | None:
|
||||||
|
"""Generate an `enum` object.
|
||||||
|
|
||||||
|
An enum object is translated into a list of literals.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
schema (capnp.lib.capnp._StructSchema): The schema to generate the `enum` object out of.
|
||||||
|
"""
|
||||||
|
assert schema.node.which() == capnp_types.CapnpElementType.ENUM
|
||||||
|
|
||||||
|
imported = self.register_import(schema)
|
||||||
|
|
||||||
|
if imported is not None:
|
||||||
|
return imported
|
||||||
|
|
||||||
|
name = helper.get_display_name(schema)
|
||||||
|
self.register_type(schema.node.id, schema, name=name, scope=self.scope)
|
||||||
|
|
||||||
|
self._add_typing_import("Literal")
|
||||||
|
enum_type = helper.new_group("Literal", [f'"{enumerant.name}"' for enumerant in schema.node.enum.enumerants])
|
||||||
|
self.scope.add(helper.new_type_alias(name, enum_type))
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def gen_generic(self, schema: capnp.lib.capnp._StructSchema) -> list[str]:
|
||||||
|
"""Generate a `generic` type variable.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
schema (capnp.lib.capnp._StructSchema): The schema to generate the `generic` object out of.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list[str]: The list of registered generic type variables.
|
||||||
|
"""
|
||||||
|
self._add_typing_import("TypeVar")
|
||||||
|
self._add_typing_import("Generic")
|
||||||
|
|
||||||
|
generic_params: list[str] = [param.name for param in schema.node.parameters]
|
||||||
|
referenced_params: list[str] = []
|
||||||
|
|
||||||
|
for field, _ in zip(schema.node.struct.fields, schema.as_struct().fields_list):
|
||||||
|
if field.slot.type.which() == "anyPointer" and field.slot.type.anyPointer.which() == "parameter":
|
||||||
|
param = field.slot.type.anyPointer.parameter
|
||||||
|
|
||||||
|
t = self.get_type_by_id(param.scopeId)
|
||||||
|
|
||||||
|
if t is not None:
|
||||||
|
param_source = t.schema
|
||||||
|
source_params: list[str] = [param.name for param in param_source.node.parameters]
|
||||||
|
referenced_params.append(source_params[param.parameterIndex])
|
||||||
|
|
||||||
|
return [self.register_type_var(param) for param in generic_params + referenced_params]
|
||||||
|
|
||||||
|
# FIXME: refactor for reducing complexity
|
||||||
|
def gen_struct(self, schema: capnp.lib.capnp._StructSchema, type_name: str = "") -> CapnpType: # noqa: C901
|
||||||
|
"""Generate a `struct` object.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
schema (capnp.lib.capnp._StructSchema): The schema to generate the `struct` object out of.
|
||||||
|
type_name (str, optional): A type name to override the display name of the struct. Defaults to "".
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Type: The `struct`-type module that was generated.
|
||||||
|
"""
|
||||||
|
assert schema.node.which() == capnp_types.CapnpElementType.STRUCT
|
||||||
|
|
||||||
|
imported = self.register_import(schema)
|
||||||
|
|
||||||
|
if imported is not None:
|
||||||
|
return imported
|
||||||
|
|
||||||
|
if not type_name:
|
||||||
|
type_name = helper.get_display_name(schema)
|
||||||
|
|
||||||
|
registered_params: list[str] = []
|
||||||
|
if schema.node.isGeneric:
|
||||||
|
registered_params = self.gen_generic(schema)
|
||||||
|
|
||||||
|
class_declaration: str
|
||||||
|
if registered_params:
|
||||||
|
parameter = helper.new_type_group("Generic", registered_params)
|
||||||
|
class_declaration = helper.new_class_declaration(type_name, parameters=[parameter])
|
||||||
|
|
||||||
|
else:
|
||||||
|
class_declaration = helper.new_class_declaration(type_name)
|
||||||
|
|
||||||
|
# Do not write the class declaration to the scope, until all nested schemas were expanded.
|
||||||
|
parent_scope = self.new_scope(type_name, schema.node)
|
||||||
|
|
||||||
|
new_type: CapnpType = self.register_type(schema.node.id, schema, name=type_name)
|
||||||
|
new_type.generic_params = registered_params
|
||||||
|
|
||||||
|
new_builder_type_name = helper.new_builder(new_type.name)
|
||||||
|
new_reader_type_name = helper.new_reader(new_type.name)
|
||||||
|
scoped_new_builder_type_name = helper.new_builder(new_type.scoped_name)
|
||||||
|
scoped_new_reader_type_name = helper.new_reader(new_type.scoped_name)
|
||||||
|
|
||||||
|
init_choices: list[InitChoice] = []
|
||||||
|
slot_fields: list[helper.TypeHintedVariable] = []
|
||||||
|
|
||||||
|
for field, raw_field in zip(schema.node.struct.fields, schema.as_struct().fields_list):
|
||||||
|
field_type = field.which()
|
||||||
|
|
||||||
|
if field_type == capnp_types.CapnpFieldType.SLOT:
|
||||||
|
slot_field = self.gen_slot(raw_field, field, new_type, init_choices)
|
||||||
|
|
||||||
|
if slot_field is not None:
|
||||||
|
slot_fields.append(slot_field)
|
||||||
|
|
||||||
|
elif field_type == capnp_types.CapnpFieldType.GROUP:
|
||||||
|
group_name = field.name[0].upper() + field.name[1:]
|
||||||
|
|
||||||
|
assert group_name != field.name
|
||||||
|
|
||||||
|
raw_schema = raw_field.schema
|
||||||
|
group_name = self.gen_struct(raw_schema, type_name=group_name).name
|
||||||
|
|
||||||
|
hinted_variable = helper.TypeHintedVariable(field.name, [helper.TypeHint(group_name, primary=True)])
|
||||||
|
hinted_variable.add_builder_from_primary_type()
|
||||||
|
hinted_variable.add_reader_from_primary_type()
|
||||||
|
|
||||||
|
hinted_variable.add_type_scope(type_name)
|
||||||
|
|
||||||
|
slot_fields.append(hinted_variable)
|
||||||
|
init_choices.append((field.name, group_name))
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise AssertionError(f"{schema.node.displayName}: {field.name}: " f"{field.which()}")
|
||||||
|
|
||||||
|
# Finally, add the class declaration after the expansion of all nested schemas.
|
||||||
|
parent_scope.add(class_declaration)
|
||||||
|
|
||||||
|
# Add the slot fields, if any.
|
||||||
|
if slot_fields:
|
||||||
|
for slot_field in slot_fields:
|
||||||
|
self.scope.add(slot_field.typed_variable_with_full_hints)
|
||||||
|
|
||||||
|
# Add the `which` function, if there is a top-level union in the schema.
|
||||||
|
if schema.node.struct.discriminantCount:
|
||||||
|
self._add_typing_import("Literal")
|
||||||
|
field_names = [f'"{field.name}"' for field in schema.node.struct.fields if field.discriminantValue != 65535]
|
||||||
|
return_type = helper.new_type_group("Literal", field_names)
|
||||||
|
|
||||||
|
self.scope.add(helper.new_function("which", parameters=["self"], return_type=return_type))
|
||||||
|
|
||||||
|
# Add an overloaded `init` function for each nested struct.
|
||||||
|
if init_choices:
|
||||||
|
self._add_typing_import("Literal")
|
||||||
|
use_overload = len(init_choices) > 1
|
||||||
|
if use_overload:
|
||||||
|
self._add_typing_import("overload")
|
||||||
|
|
||||||
|
for field_name, field_type in init_choices:
|
||||||
|
if use_overload:
|
||||||
|
self.scope.add(helper.new_decorator("overload"))
|
||||||
|
|
||||||
|
self.scope.add(
|
||||||
|
helper.new_function(
|
||||||
|
"init", parameters=["self", f'name: Literal["{field_name}"]'], return_type=field_type
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add static methods for converting from/to bytes.
|
||||||
|
self._add_typing_import("Iterator")
|
||||||
|
self._add_import("from contextlib import contextmanager")
|
||||||
|
|
||||||
|
self.scope.add(helper.new_decorator("staticmethod"))
|
||||||
|
self.scope.add(helper.new_decorator("contextmanager"))
|
||||||
|
self.scope.add(
|
||||||
|
helper.new_function(
|
||||||
|
"from_bytes",
|
||||||
|
parameters=[
|
||||||
|
helper.TypeHintedVariable("data", [helper.TypeHint("bytes", primary=True)]),
|
||||||
|
helper.TypeHintedVariable(
|
||||||
|
"traversal_limit_in_words",
|
||||||
|
[helper.TypeHint("int", primary=True), helper.TypeHint("None")],
|
||||||
|
default="...",
|
||||||
|
),
|
||||||
|
helper.TypeHintedVariable(
|
||||||
|
"nesting_limit", [helper.TypeHint("int", primary=True), helper.TypeHint("None")], default="..."
|
||||||
|
),
|
||||||
|
],
|
||||||
|
return_type=helper.new_type_group("Iterator", [scoped_new_reader_type_name]),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.scope.add(helper.new_decorator("staticmethod"))
|
||||||
|
self.scope.add(
|
||||||
|
helper.new_function(
|
||||||
|
"from_bytes_packed",
|
||||||
|
parameters=[
|
||||||
|
helper.TypeHintedVariable("data", [helper.TypeHint("bytes", primary=True)]),
|
||||||
|
helper.TypeHintedVariable(
|
||||||
|
"traversal_limit_in_words",
|
||||||
|
[helper.TypeHint("int", primary=True), helper.TypeHint("None")],
|
||||||
|
default="...",
|
||||||
|
),
|
||||||
|
helper.TypeHintedVariable(
|
||||||
|
"nesting_limit", [helper.TypeHint("int", primary=True), helper.TypeHint("None")], default="..."
|
||||||
|
),
|
||||||
|
],
|
||||||
|
return_type=scoped_new_reader_type_name,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.scope.add(helper.new_decorator("staticmethod"))
|
||||||
|
self.scope.add(helper.new_function("new_message", return_type=scoped_new_builder_type_name))
|
||||||
|
self.scope.add(helper.new_function("to_dict", parameters=["self"], return_type="dict"))
|
||||||
|
|
||||||
|
self._add_import("from io import BufferedWriter")
|
||||||
|
|
||||||
|
self.return_from_scope()
|
||||||
|
|
||||||
|
# Generate the reader class
|
||||||
|
parent_scope = self.new_scope(new_reader_type_name, schema.node, register=False)
|
||||||
|
|
||||||
|
# Add the reader slot fields, if any.
|
||||||
|
for slot_field in slot_fields:
|
||||||
|
if slot_field.has_type_hint_with_reader_affix:
|
||||||
|
self.scope.add(slot_field.get_typed_variable_with_affixes([helper.READER_NAME]))
|
||||||
|
|
||||||
|
reader_class_declaration = helper.new_class_declaration(new_reader_type_name, parameters=[new_type.scoped_name])
|
||||||
|
parent_scope.add(reader_class_declaration)
|
||||||
|
self.scope.add(helper.new_function("as_builder", parameters=["self"], return_type=scoped_new_builder_type_name))
|
||||||
|
|
||||||
|
self.return_from_scope()
|
||||||
|
|
||||||
|
# Generate the builder class
|
||||||
|
parent_scope = self.new_scope(new_builder_type_name, schema.node, register=False)
|
||||||
|
|
||||||
|
# Add the builder slot fields, if any.
|
||||||
|
for slot_field in slot_fields:
|
||||||
|
if slot_field.has_type_hint_with_builder_affix:
|
||||||
|
self.scope.add(
|
||||||
|
slot_field.typed_variable_with_full_hints
|
||||||
|
) # .get_typed_variable_with_affixes([helper.BUILDER_NAME, helper.READER_NAME]))
|
||||||
|
|
||||||
|
self.scope.add(helper.new_decorator("staticmethod"))
|
||||||
|
self.scope.add(
|
||||||
|
helper.new_function(
|
||||||
|
"from_dict",
|
||||||
|
parameters=[helper.TypeHintedVariable("dictionary", [helper.TypeHint("dict", primary=True)])],
|
||||||
|
return_type=scoped_new_builder_type_name,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.scope.add(helper.new_function("copy", parameters=["self"], return_type=scoped_new_builder_type_name))
|
||||||
|
self.scope.add(helper.new_function("to_bytes", parameters=["self"], return_type="bytes"))
|
||||||
|
self.scope.add(helper.new_function("to_bytes_packed", parameters=["self"], return_type="bytes"))
|
||||||
|
self.scope.add(
|
||||||
|
helper.new_function(
|
||||||
|
"to_segments", parameters=["self"], return_type=helper.new_type_group("list", ["bytes"])
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
builder_class_declaration = helper.new_class_declaration(
|
||||||
|
new_builder_type_name, parameters=[new_type.scoped_name]
|
||||||
|
)
|
||||||
|
parent_scope.add(builder_class_declaration)
|
||||||
|
|
||||||
|
self.scope.add(helper.new_function("as_reader", parameters=["self"], return_type=scoped_new_reader_type_name))
|
||||||
|
|
||||||
|
self.scope.add(helper.new_decorator("staticmethod"))
|
||||||
|
self.scope.add(
|
||||||
|
helper.new_function(
|
||||||
|
"write",
|
||||||
|
parameters=[helper.TypeHintedVariable("file", [helper.TypeHint("BufferedWriter", primary=True)])],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.scope.add(helper.new_decorator("staticmethod"))
|
||||||
|
self.scope.add(
|
||||||
|
helper.new_function(
|
||||||
|
"write_packed",
|
||||||
|
parameters=[helper.TypeHintedVariable("file", [helper.TypeHint("BufferedWriter", primary=True)])],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.return_from_scope()
|
||||||
|
|
||||||
|
return new_type
|
||||||
|
|
||||||
|
def generate_nested(self, schema: capnp.lib.capnp._StructSchema) -> None:
|
||||||
|
"""Generate the type for a nested schema.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
schema (capnp.lib.capnp._StructSchema): The schema to generate types for.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
AssertionError: If the schema belongs to an unknown type.
|
||||||
|
"""
|
||||||
|
if self.is_type_id_known(schema.node.id):
|
||||||
|
return
|
||||||
|
|
||||||
|
node_type = schema.node.which()
|
||||||
|
|
||||||
|
if node_type == "const":
|
||||||
|
self.gen_const(schema)
|
||||||
|
|
||||||
|
elif node_type == "struct":
|
||||||
|
self.gen_struct(schema)
|
||||||
|
|
||||||
|
elif node_type == "enum":
|
||||||
|
self.gen_enum(schema)
|
||||||
|
|
||||||
|
elif node_type == "interface":
|
||||||
|
logger.warning("Skipping interface: not implemented.")
|
||||||
|
|
||||||
|
elif node_type == "annotation":
|
||||||
|
logger.warning("Skipping annotation: not implemented.")
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise AssertionError(node_type)
|
||||||
|
|
||||||
|
def generate_all_nested(self):
|
||||||
|
"""Generate types for all nested nodes, recursively."""
|
||||||
|
for node in self._module.schema.node.nestedNodes:
|
||||||
|
self.generate_nested(self._module.schema.get_nested(node.name))
|
||||||
|
|
||||||
|
def register_import(self, schema: capnp.lib.capnp._StructSchema) -> CapnpType | None:
|
||||||
|
"""Determine, whether a schema is imported from the base module.
|
||||||
|
|
||||||
|
If so, the type definition that the schema contains, is added to the type registry.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
schema (capnp.lib.capnp._StructSchema): The schema to check.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Type | None: The type of the import, if the schema is imported,
|
||||||
|
or None if the schema defines the base module itself.
|
||||||
|
"""
|
||||||
|
module_name, definition_name = schema.node.displayName.split(":")
|
||||||
|
|
||||||
|
if module_name == self.full_display_name:
|
||||||
|
# This is the base module, not an import.
|
||||||
|
return None
|
||||||
|
|
||||||
|
common_path: str
|
||||||
|
matching_path: pathlib.Path | None = None
|
||||||
|
|
||||||
|
# Find the path of the parent module, from which this schema is imported.
|
||||||
|
for path, module in self._module_registry.values():
|
||||||
|
for node in module.schema.node.nestedNodes:
|
||||||
|
if node.id == schema.node.id:
|
||||||
|
matching_path = pathlib.Path(path)
|
||||||
|
break
|
||||||
|
|
||||||
|
# Since this is an import, there must be a parent module.
|
||||||
|
assert matching_path is not None, f"The module named {module_name} was not provided to the stub generator."
|
||||||
|
|
||||||
|
# Find the relative path to go from the parent module, to this imported module.
|
||||||
|
common_path = os.path.commonpath([self._module_path, matching_path])
|
||||||
|
|
||||||
|
relative_module_path = self._module_path.relative_to(common_path)
|
||||||
|
relative_import_path = matching_path.relative_to(common_path)
|
||||||
|
|
||||||
|
# Shape the relative path to a relative Python import statement.
|
||||||
|
python_import_path = "." * len(relative_module_path.parents) + helper.replace_capnp_suffix(
|
||||||
|
".".join(relative_import_path.parts)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Import the regular definition name, alongside its builder.
|
||||||
|
self._add_import(
|
||||||
|
f"from {python_import_path} import "
|
||||||
|
f"{definition_name}, {helper.new_builder(definition_name)}, {helper.new_reader(definition_name)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return self.register_type(schema.node.id, schema, name=definition_name, scope=self.scope.root)
|
||||||
|
|
||||||
|
def register_type_var(self, name: str) -> str:
|
||||||
|
"""Find and register the full name of a type variable, which includes its scopes.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name (str): The type name to register.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The full name in the format scope0_scope1_..._scopeN_name, including the type name to register.
|
||||||
|
"""
|
||||||
|
full_name: str = self.scope.trace_as_str("_") + f"_{name}"
|
||||||
|
|
||||||
|
self.type_vars.add(full_name)
|
||||||
|
return full_name
|
||||||
|
|
||||||
|
def register_type(
|
||||||
|
self, type_id: int, schema: capnp.lib.capnp._StructSchema, name: str = "", scope: Scope | None = None
|
||||||
|
) -> CapnpType:
|
||||||
|
"""Register a new type in the writer's registry of types.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
type_id (int): The identification number of the type.
|
||||||
|
schema (capnp.lib.capnp._StructSchema): The schema that defines the type.
|
||||||
|
name (str, optional): An name to specify, if overriding the type name. Defaults to "".
|
||||||
|
scope (Scope | None, optional): The scope in which the type is defined. Defaults to None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Type: The registered type.
|
||||||
|
"""
|
||||||
|
if not name:
|
||||||
|
name = helper.get_display_name(schema)
|
||||||
|
|
||||||
|
if scope is None:
|
||||||
|
scope = self.scope.parent
|
||||||
|
|
||||||
|
if scope is None:
|
||||||
|
raise ValueError(f"No valid scope was found for registering the type '{name}'.")
|
||||||
|
|
||||||
|
self.type_map[type_id] = retval = CapnpType(schema=schema, name=name, scope=scope)
|
||||||
|
return retval
|
||||||
|
|
||||||
|
def is_type_id_known(self, type_id: int) -> bool:
|
||||||
|
"""Check, whether a type ID was previously registered.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
type_id (int): The type ID to check.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True, if the type ID is known, False otherwise.
|
||||||
|
"""
|
||||||
|
return type_id in self.type_map
|
||||||
|
|
||||||
|
def get_type_by_id(self, type_id: int) -> CapnpType:
|
||||||
|
"""Look up a type in the type registry, by means of its ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
type_id (int): The identification number of the type.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
KeyError: If the type ID was not found in the registry.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Type: The type, if it exists.
|
||||||
|
"""
|
||||||
|
if self.is_type_id_known(type_id):
|
||||||
|
return self.type_map[type_id]
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise KeyError(f"The type ID '{type_id} was not found in the type registry.'")
|
||||||
|
|
||||||
|
def new_scope(self, name: str, node: Any, scope_heading: str = "", register: bool = True) -> Scope:
|
||||||
|
"""Creates a new scope below the scope of the provided node.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name (str): The name of the new scope.
|
||||||
|
node (Any): The node whose scope is the parent scope of the new scope.
|
||||||
|
scope_heading (str): The line of code that starts this new scope.
|
||||||
|
register (bool): Whether to register this scope.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Scope: The parent of this scope.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
parent_scope = self.scopes_by_id[node.scopeId]
|
||||||
|
|
||||||
|
except KeyError as e:
|
||||||
|
raise NoParentError(f"The scope with name '{name}' has no parent.") from e
|
||||||
|
|
||||||
|
# Add the heading of the scope to the parent scope.
|
||||||
|
if scope_heading:
|
||||||
|
parent_scope.add(scope_heading)
|
||||||
|
|
||||||
|
# Then, make a new scope that is one indent level deeper.
|
||||||
|
child_scope = Scope(name=name, id=node.id, parent=parent_scope, return_scope=self.scope)
|
||||||
|
|
||||||
|
self.scope = child_scope
|
||||||
|
|
||||||
|
if register:
|
||||||
|
self.scopes_by_id[node.id] = child_scope
|
||||||
|
|
||||||
|
return parent_scope
|
||||||
|
|
||||||
|
def return_from_scope(self):
|
||||||
|
"""Return from the current scope."""
|
||||||
|
assert self.scope is not None, "The current scope is not valid."
|
||||||
|
assert not self.scope.is_root, "The current scope is the root scope and cannot be returned from."
|
||||||
|
assert self.scope.parent is not None, "The current scope has no parent."
|
||||||
|
assert self.scope.return_scope is not None, "The current scope does not define a scope to return to."
|
||||||
|
|
||||||
|
self.scope.parent.lines += self.scope.lines
|
||||||
|
self.scope = self.scope.return_scope
|
||||||
|
|
||||||
|
def get_type_name(self, type_reader: capnp._DynamicStructReader) -> str:
|
||||||
|
"""Extract the type name from a type reader.
|
||||||
|
|
||||||
|
The output type name is prepended by the scope name, if there is a parent scope.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
type_reader (capnp._DynamicStructReader): The type reader to get the type name from.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The extracted type name.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
return capnp_types.CAPNP_TYPE_TO_PYTHON[type_reader.which()]
|
||||||
|
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
type_reader_type = type_reader.which()
|
||||||
|
|
||||||
|
element_type: Any | None = None
|
||||||
|
|
||||||
|
if type_reader_type == capnp_types.CapnpElementType.STRUCT:
|
||||||
|
element_type = self.get_type_by_id(type_reader.struct.typeId)
|
||||||
|
type_name = element_type.name
|
||||||
|
generic_params = []
|
||||||
|
|
||||||
|
for brand_scope in type_reader.struct.brand.scopes:
|
||||||
|
brand_scope_type = brand_scope.which()
|
||||||
|
|
||||||
|
if brand_scope_type == "inherit":
|
||||||
|
parent_scope = self.get_type_by_id(brand_scope.scopeId)
|
||||||
|
generic_params.extend(parent_scope.generic_params)
|
||||||
|
|
||||||
|
elif brand_scope_type == "bind":
|
||||||
|
for bind in brand_scope.bind:
|
||||||
|
generic_params.append(self.get_type_name(bind.type))
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise TypeError(f"Unknown brand scope '{brand_scope_type}'.")
|
||||||
|
|
||||||
|
if generic_params:
|
||||||
|
type_name += f"[{', '.join(generic_params)}]"
|
||||||
|
|
||||||
|
elif type_reader_type == capnp_types.CapnpElementType.ENUM:
|
||||||
|
element_type = self.get_type_by_id(type_reader.enum.typeId)
|
||||||
|
type_name = element_type.name
|
||||||
|
|
||||||
|
elif type_reader_type == capnp_types.CapnpElementType.LIST:
|
||||||
|
type_name = type_reader.list.elementType.which()
|
||||||
|
|
||||||
|
# Traverse down to the innermost nested list element.
|
||||||
|
while type_name == capnp_types.CapnpElementType.LIST:
|
||||||
|
type_name += type_reader.list.elementType.which()
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise TypeError(f"Unknown type reader type '{type_reader_type}'.")
|
||||||
|
|
||||||
|
if element_type and (not element_type.scope.is_root):
|
||||||
|
return f"{element_type.scope}.{type_name}"
|
||||||
|
|
||||||
|
else:
|
||||||
|
return type_name
|
||||||
|
|
||||||
|
def dumps_pyi(self) -> str:
|
||||||
|
"""Generates string output for the *.pyi stub file that provides type hinting.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The output string.
|
||||||
|
"""
|
||||||
|
assert self.scope.is_root
|
||||||
|
|
||||||
|
out = []
|
||||||
|
out.append(self.docstring)
|
||||||
|
out.extend(self.imports)
|
||||||
|
out.append("")
|
||||||
|
|
||||||
|
if self.type_vars:
|
||||||
|
for name in sorted(self.type_vars):
|
||||||
|
out.append(f'{name} = TypeVar("{name}")')
|
||||||
|
out.append("")
|
||||||
|
|
||||||
|
out.extend(self.scope.lines)
|
||||||
|
return "\n".join(out)
|
||||||
|
|
||||||
|
def dumps_py(self) -> str:
|
||||||
|
"""Generates string output for the *.py stub file that handles the import of capnproto schemas.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The output string.
|
||||||
|
"""
|
||||||
|
assert self.scope.is_root
|
||||||
|
|
||||||
|
out = []
|
||||||
|
out.append(self.docstring)
|
||||||
|
out.append("import os")
|
||||||
|
out.append("import capnp # type: ignore")
|
||||||
|
out.append("capnp.remove_import_hook()")
|
||||||
|
out.append("here = os.path.dirname(os.path.abspath(__file__))")
|
||||||
|
|
||||||
|
out.append(f'module_file = os.path.abspath(os.path.join(here, "{self.display_name}"))')
|
||||||
|
|
||||||
|
for scope in self.scopes_by_id.values():
|
||||||
|
if scope.parent is not None and scope.parent.is_root:
|
||||||
|
out.append(f"{scope.name} = capnp.load(module_file).{scope.name}")
|
||||||
|
out.append(f"{helper.new_builder(scope.name)} = {scope.name}")
|
||||||
|
out.append(f"{helper.new_reader(scope.name)} = {scope.name}")
|
||||||
|
|
||||||
|
return "\n".join(out)
|
@ -1,19 +0,0 @@
|
|||||||
"""Helper functionality that is used in other modules of this package."""
|
|
||||||
|
|
||||||
|
|
||||||
def replace_capnp_suffix(original: str) -> str:
|
|
||||||
"""If found, replaces the .capnp suffix in a string with _capnp.
|
|
||||||
|
|
||||||
For example, `some_module.capnp` becomes `some_module_capnp`.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
original (str): The string to replace the suffix in.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The string with the replaced suffix.
|
|
||||||
"""
|
|
||||||
if original.endswith(".capnp"):
|
|
||||||
return original.replace(".capnp", "_capnp")
|
|
||||||
|
|
||||||
else:
|
|
||||||
return original
|
|
@ -1,810 +0,0 @@
|
|||||||
"""Generate type hints for *.capnp schemas.
|
|
||||||
|
|
||||||
Note: This generator requires pycapnp >= 1.0.0.
|
|
||||||
|
|
||||||
Note: capnp interfaces (RPC) are not yet supported.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import dataclasses
|
|
||||||
import keyword
|
|
||||||
import logging
|
|
||||||
import os.path
|
|
||||||
import pathlib
|
|
||||||
from types import ModuleType
|
|
||||||
from typing import Any, Literal, Set
|
|
||||||
|
|
||||||
import capnp
|
|
||||||
from capnp_stub_generator.capnp_types import (
|
|
||||||
CAPNP_TYPE_TO_PYTHON,
|
|
||||||
CapnpElementType,
|
|
||||||
CapnpFieldType,
|
|
||||||
CapnpSlotType,
|
|
||||||
ModuleRegistryType,
|
|
||||||
)
|
|
||||||
from capnp_stub_generator.helper import replace_capnp_suffix
|
|
||||||
|
|
||||||
capnp.remove_import_hook()
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
INDENT_SPACES = 4
|
|
||||||
|
|
||||||
|
|
||||||
class NoParentError(Exception):
|
|
||||||
"""Raised, when the parent of a scope is not available."""
|
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass
|
|
||||||
class Scope:
|
|
||||||
"""A scope within the output .pyi file.
|
|
||||||
|
|
||||||
Scopes contain text and are indented by a certain amount. They often have parents, within which they are located.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
name (str): The name of the scope. Use an empty name for the root scope ("").
|
|
||||||
id (int): A numerical identifier of the scope.
|
|
||||||
parent (Scope | None): The direct parent scope of this scope, if there is any.
|
|
||||||
return scope (Scope | None): The scope to which to return, when closing this one.
|
|
||||||
lines (list[str]): The list of text lines in this scope.
|
|
||||||
"""
|
|
||||||
|
|
||||||
name: str
|
|
||||||
id: int
|
|
||||||
parent: Scope | None
|
|
||||||
return_scope: Scope | None
|
|
||||||
lines: list[str] = dataclasses.field(default_factory=list)
|
|
||||||
|
|
||||||
def __post_init__(self):
|
|
||||||
"""Assures that, if this is the root scope, its name is empty."""
|
|
||||||
assert (self.is_root) == (self.name == "")
|
|
||||||
|
|
||||||
@property
|
|
||||||
def parents(self) -> list[Scope]:
|
|
||||||
"""A list of all parent scopes of this scope, starting from the first parent.
|
|
||||||
|
|
||||||
If the returned list is empty, this scope has no parents. The first parent in the list has no further
|
|
||||||
parents, it is the root scope.
|
|
||||||
"""
|
|
||||||
parents: list[Scope] = []
|
|
||||||
scope: Scope | None = self.parent
|
|
||||||
|
|
||||||
while scope is not None:
|
|
||||||
parents.append(scope)
|
|
||||||
scope = scope.parent
|
|
||||||
|
|
||||||
parents.reverse()
|
|
||||||
|
|
||||||
return parents
|
|
||||||
|
|
||||||
@property
|
|
||||||
def trace(self) -> list[Scope]:
|
|
||||||
"""A list of all scopes that lead to this scope, starting from the first parent.
|
|
||||||
|
|
||||||
The first parent has no further parents.
|
|
||||||
"""
|
|
||||||
return self.parents + [self]
|
|
||||||
|
|
||||||
@property
|
|
||||||
def root(self) -> Scope:
|
|
||||||
"""Get the root scope that has no further parents."""
|
|
||||||
if not self.parents:
|
|
||||||
return self
|
|
||||||
|
|
||||||
else:
|
|
||||||
return self.parents[0]
|
|
||||||
|
|
||||||
@property
|
|
||||||
def is_root(self) -> bool:
|
|
||||||
"""Determine, whether this is the root scope."""
|
|
||||||
return self.root == self
|
|
||||||
|
|
||||||
@property
|
|
||||||
def indent_spaces(self) -> int:
|
|
||||||
"""The number of spaces by which this scope is indented."""
|
|
||||||
return len(self.parents) * INDENT_SPACES
|
|
||||||
|
|
||||||
def add_line(self, line: str = ""):
|
|
||||||
"""Add a line to this scope, taking into account the current indent spaces.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
line (str): The line to add. Optional, defaults to "".
|
|
||||||
"""
|
|
||||||
if not line:
|
|
||||||
self.lines.append("")
|
|
||||||
|
|
||||||
else:
|
|
||||||
self.lines.append(" " * self.indent_spaces + line)
|
|
||||||
|
|
||||||
def trace_as_str(self, delimiter: Literal[".", "_"] = ".") -> str:
|
|
||||||
"""A string representation of this scope's relative trace.
|
|
||||||
|
|
||||||
Follow the trace of the scope, and connect parent scopes with a delimiter.
|
|
||||||
The root scope is not included in this trace string.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
delimiter (Literal[".", "_"]): The delimiter to join the scope names with.
|
|
||||||
"""
|
|
||||||
return delimiter.join((scope.name for scope in self.trace if not scope.is_root))
|
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
|
||||||
"""A string representation of this scope.
|
|
||||||
|
|
||||||
Follow the path of scopes, and connect parent scopes with '.'.
|
|
||||||
"""
|
|
||||||
return self.trace_as_str(".")
|
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass
|
|
||||||
class CapnpType:
|
|
||||||
"""Represents a type that is extracted from a .capnp schema.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
schema (Any):
|
|
||||||
name (str):
|
|
||||||
scope (Scope):
|
|
||||||
generic_params (list[str]):
|
|
||||||
"""
|
|
||||||
|
|
||||||
schema: Any
|
|
||||||
name: str
|
|
||||||
scope: Scope
|
|
||||||
generic_params: list[str] = dataclasses.field(default_factory=list)
|
|
||||||
|
|
||||||
|
|
||||||
class Writer:
|
|
||||||
"""A class that handles writing the stub file, based on a provided module definition."""
|
|
||||||
|
|
||||||
VALID_TYPING_IMPORTS = Literal["Generic", "TypeVar", "List", "Literal", "Union", "overload"]
|
|
||||||
|
|
||||||
def __init__(self, module: ModuleType, module_registry: ModuleRegistryType):
|
|
||||||
"""Initialize the stub writer with a module definition.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
module (ModuleType): The module definition to parse and write a stub for.
|
|
||||||
module_registry (ModuleRegistryType): The module registry, for finding dependencies between loaded modules.
|
|
||||||
"""
|
|
||||||
self.scope = Scope(name="", id=module.schema.node.id, parent=None, return_scope=None)
|
|
||||||
self.scopes_by_id: dict[int, Scope] = {self.scope.id: self.scope}
|
|
||||||
|
|
||||||
self._module = module
|
|
||||||
self._module_registry = module_registry
|
|
||||||
|
|
||||||
if self._module.__file__:
|
|
||||||
self._module_path = pathlib.Path(self._module.__file__)
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise ValueError("The module has no file path attached to it.")
|
|
||||||
|
|
||||||
self._imports: Set[str] = set()
|
|
||||||
self._add_import("from __future__ import annotations")
|
|
||||||
|
|
||||||
self._typing_imports: Set[Writer.VALID_TYPING_IMPORTS] = set()
|
|
||||||
|
|
||||||
self.type_vars: set[str] = set()
|
|
||||||
self.type_map: dict[int, CapnpType] = {}
|
|
||||||
|
|
||||||
self.docstring = f'"""This is an automatically generated stub for `{self._module_path.name}`."""'
|
|
||||||
|
|
||||||
def _add_typing_import(self, module_name: Writer.VALID_TYPING_IMPORTS):
|
|
||||||
"""Add an import for a module from the 'typing' package.
|
|
||||||
|
|
||||||
E.g., when using
|
|
||||||
add_typing_import("List")
|
|
||||||
add_typing_import("Union")
|
|
||||||
|
|
||||||
this generates an import line `from typing import List, Union`.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
module_name (Writer.VALID_TYPING_IMPORTS): The module to import from `typing`.
|
|
||||||
"""
|
|
||||||
self._typing_imports.add(module_name)
|
|
||||||
|
|
||||||
def _add_import(self, import_line: str):
|
|
||||||
"""Add a full import line.
|
|
||||||
|
|
||||||
E.g. 'import numpy as np'.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
import_line (str): The import line to add.
|
|
||||||
"""
|
|
||||||
self._imports.add(import_line)
|
|
||||||
|
|
||||||
def _add_enum_import(self):
|
|
||||||
"""Adds an import for the `Enum` class."""
|
|
||||||
self._add_import("from enum import Enum")
|
|
||||||
|
|
||||||
@property
|
|
||||||
def base_module_name(self) -> str:
|
|
||||||
"""The base name of this writer's target module."""
|
|
||||||
return self._module.schema.node.displayName
|
|
||||||
|
|
||||||
@property
|
|
||||||
def imports(self) -> list[str]:
|
|
||||||
"""Get the full list of import strings that were added to the writer, including typing imports.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
list[str]: The list of imports that were previously added.
|
|
||||||
"""
|
|
||||||
import_lines: list[str] = []
|
|
||||||
|
|
||||||
for imp in self._imports:
|
|
||||||
import_lines.append(imp)
|
|
||||||
|
|
||||||
if self._typing_imports:
|
|
||||||
import_lines.append("from typing import " + ", ".join(sorted(self._typing_imports)))
|
|
||||||
|
|
||||||
return import_lines
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def get_display_name(schema: Any) -> str:
|
|
||||||
"""Extract the display name from the schema.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
schema (Any): The schema to get the display name from.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The display name of the schema.
|
|
||||||
"""
|
|
||||||
return schema.node.displayName[schema.node.displayNamePrefixLength :]
|
|
||||||
|
|
||||||
def gen_const(self, schema: Any) -> None:
|
|
||||||
"""Generate a `const` object.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
schema (Any): The schema to generate the `const` object out of.
|
|
||||||
"""
|
|
||||||
assert schema.node.which() == CapnpElementType.CONST
|
|
||||||
|
|
||||||
name = self.get_display_name(schema)
|
|
||||||
python_type = CAPNP_TYPE_TO_PYTHON[schema.node.const.type.which()]
|
|
||||||
self.scope.add_line(f"{name}: {python_type}")
|
|
||||||
|
|
||||||
def gen_enum(self, schema: Any) -> CapnpType | None:
|
|
||||||
"""Generate an `enum` object.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
schema (Any): The schema to generate the `enum` object out of.
|
|
||||||
"""
|
|
||||||
assert schema.node.which() == CapnpElementType.ENUM
|
|
||||||
|
|
||||||
imported = self.register_import(schema)
|
|
||||||
|
|
||||||
if imported is not None:
|
|
||||||
return imported
|
|
||||||
|
|
||||||
name = self.get_display_name(schema)
|
|
||||||
self._add_enum_import()
|
|
||||||
|
|
||||||
self.new_scope(name, schema.node, f"class {name}(str, Enum):")
|
|
||||||
self.register_type(schema.node.id, schema, name)
|
|
||||||
|
|
||||||
for enumerant in schema.node.enum.enumerants:
|
|
||||||
value = enumerant.name
|
|
||||||
name = enumerant.name
|
|
||||||
|
|
||||||
if enumerant.name in keyword.kwlist:
|
|
||||||
# Avoid naming collisions with Python keywords.
|
|
||||||
name += "_"
|
|
||||||
|
|
||||||
self.scope.add_line(f'{name}: str = "{value}"')
|
|
||||||
|
|
||||||
self.return_from_scope()
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
def gen_generic(self, schema: Any) -> list[str]:
|
|
||||||
"""Generate a `generic` type variable.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
schema (Any): The schema to generate the `generic` object out of.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
list[str]: The list of registered generic type variables.
|
|
||||||
"""
|
|
||||||
self._add_typing_import("TypeVar")
|
|
||||||
self._add_typing_import("Generic")
|
|
||||||
|
|
||||||
generic_params: list[str] = [param.name for param in schema.node.parameters]
|
|
||||||
referenced_params: list[str] = []
|
|
||||||
|
|
||||||
for field, _ in zip(schema.node.struct.fields, schema.as_struct().fields_list):
|
|
||||||
if field.slot.type.which() == "anyPointer" and field.slot.type.anyPointer.which() == "parameter":
|
|
||||||
param = field.slot.type.anyPointer.parameter
|
|
||||||
|
|
||||||
t = self.get_type_by_id(param.scopeId)
|
|
||||||
|
|
||||||
if t is not None:
|
|
||||||
param_source = t.schema
|
|
||||||
source_params: list[str] = [param.name for param in param_source.node.parameters]
|
|
||||||
referenced_params.append(source_params[param.parameterIndex])
|
|
||||||
|
|
||||||
return [self.register_type_var(param) for param in generic_params + referenced_params]
|
|
||||||
|
|
||||||
def gen_slot(
|
|
||||||
self,
|
|
||||||
schema: Any,
|
|
||||||
field: Any,
|
|
||||||
raw_field: Any,
|
|
||||||
registered_type: CapnpType,
|
|
||||||
contructor_kwargs: list[str],
|
|
||||||
init_choices: list[tuple[str, str]],
|
|
||||||
) -> None:
|
|
||||||
"""Generate a slot of a type that is yet to be determined.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
schema (Any): The schema to extract the slot from.
|
|
||||||
field (Any): FIXME
|
|
||||||
raw_field (Any): FIXME
|
|
||||||
registered_type (Type): FIXME
|
|
||||||
contructor_kwargs (list[str]): FIXME
|
|
||||||
init_choices (list[tuple[str, str]]): FIXME
|
|
||||||
"""
|
|
||||||
|
|
||||||
def gen_list_slot():
|
|
||||||
"""Generate a slot, which contains a `list`."""
|
|
||||||
list_slot_type: CapnpElementType = field.slot.type.list.elementType.which()
|
|
||||||
|
|
||||||
if list_slot_type == CapnpElementType.STRUCT:
|
|
||||||
if not self.is_type_id_known(field.slot.type.list.elementType.struct.typeId):
|
|
||||||
self.generate_nested(raw_field.schema.elementType)
|
|
||||||
|
|
||||||
elif list_slot_type == CapnpElementType.ENUM:
|
|
||||||
if not self.is_type_id_known(field.slot.type.list.elementType.enum.typeId):
|
|
||||||
self.generate_nested(raw_field.schema.elementType)
|
|
||||||
|
|
||||||
type_name = self.get_type_name(field.slot.type.list.elementType)
|
|
||||||
field_py_code = f"{field.name}: List[{type_name}]"
|
|
||||||
self.scope.add_line(field_py_code)
|
|
||||||
contructor_kwargs.append(field_py_code)
|
|
||||||
self._add_typing_import("List")
|
|
||||||
|
|
||||||
def gen_python_type_slot():
|
|
||||||
"""Generate a slot, which contains a regular Python type."""
|
|
||||||
python_type_name: str = CAPNP_TYPE_TO_PYTHON[field_slot_type]
|
|
||||||
|
|
||||||
field_py_code = f"{field.name}: {python_type_name}"
|
|
||||||
self.scope.add_line(field_py_code)
|
|
||||||
contructor_kwargs.append(field_py_code)
|
|
||||||
|
|
||||||
def gen_enum_slot():
|
|
||||||
"""Generate a slot, which contains an `enum`."""
|
|
||||||
if not self.is_type_id_known(field.slot.type.enum.typeId):
|
|
||||||
try:
|
|
||||||
self.generate_nested(raw_field.schema)
|
|
||||||
|
|
||||||
except NoParentError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
type_name = self.get_type_name(field.slot.type)
|
|
||||||
field_py_code = f"{field.name}: {type_name}"
|
|
||||||
self.scope.add_line(field_py_code)
|
|
||||||
contructor_kwargs.append(field_py_code)
|
|
||||||
|
|
||||||
def gen_struct_slot():
|
|
||||||
"""Generate a slot, which contains a `struct`."""
|
|
||||||
elem_type = raw_field.schema
|
|
||||||
|
|
||||||
if not self.is_type_id_known(elem_type.node.id):
|
|
||||||
self.gen_struct(elem_type)
|
|
||||||
|
|
||||||
type_name = self.get_type_name(field.slot.type)
|
|
||||||
field_py_code = f"{field.name}: {type_name}"
|
|
||||||
self.scope.add_line(field_py_code)
|
|
||||||
contructor_kwargs.append(field_py_code)
|
|
||||||
init_choices.append((field.name, type_name))
|
|
||||||
|
|
||||||
def gen_any_pointer_slot():
|
|
||||||
"""Generate a slot, which contains an `any_pointer` object."""
|
|
||||||
param = field.slot.type.anyPointer.parameter
|
|
||||||
type_name = registered_type.generic_params[param.parameterIndex]
|
|
||||||
field_py_code = f"{field.name}: {type_name}"
|
|
||||||
self.scope.add_line(field_py_code)
|
|
||||||
contructor_kwargs.append(field_py_code)
|
|
||||||
|
|
||||||
field_slot_type = field.slot.type.which()
|
|
||||||
|
|
||||||
if field_slot_type == CapnpSlotType.LIST:
|
|
||||||
gen_list_slot()
|
|
||||||
|
|
||||||
elif field_slot_type in CAPNP_TYPE_TO_PYTHON:
|
|
||||||
gen_python_type_slot()
|
|
||||||
|
|
||||||
elif field_slot_type == CapnpSlotType.ENUM:
|
|
||||||
gen_enum_slot()
|
|
||||||
|
|
||||||
elif field_slot_type == CapnpSlotType.STRUCT:
|
|
||||||
gen_struct_slot()
|
|
||||||
|
|
||||||
elif field_slot_type == CapnpSlotType.ANY_POINTER:
|
|
||||||
gen_any_pointer_slot()
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise AssertionError(f"{schema.node.displayName}: {field.name}: " f"{field_slot_type}")
|
|
||||||
|
|
||||||
def gen_struct(self, schema: Any, type_name: str = "") -> CapnpType:
|
|
||||||
"""Generate a `struct` object.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
schema (Any): The schema to generate the `struct` object out of.
|
|
||||||
type_name (str, optional): A type name to override the display name of the struct. Defaults to "".
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Type: The `struct`-type module that was generated.
|
|
||||||
"""
|
|
||||||
assert schema.node.which() == CapnpElementType.STRUCT
|
|
||||||
|
|
||||||
imported = self.register_import(schema)
|
|
||||||
|
|
||||||
if imported is not None:
|
|
||||||
return imported
|
|
||||||
|
|
||||||
if not type_name:
|
|
||||||
type_name = self.get_display_name(schema)
|
|
||||||
|
|
||||||
registered_params: list[str] = []
|
|
||||||
if schema.node.isGeneric:
|
|
||||||
registered_params = self.gen_generic()
|
|
||||||
|
|
||||||
if registered_params:
|
|
||||||
scope_decl_line = f"class {type_name}(Generic[{', '.join(registered_params)}]):"
|
|
||||||
|
|
||||||
else:
|
|
||||||
scope_decl_line = f"class {type_name}:"
|
|
||||||
|
|
||||||
self.new_scope(type_name, schema.node, scope_decl_line)
|
|
||||||
|
|
||||||
registered_type: CapnpType = self.register_type(schema.node.id, schema, name=type_name)
|
|
||||||
registered_type.generic_params = registered_params
|
|
||||||
type_name = registered_type.name
|
|
||||||
definition_has_body = False
|
|
||||||
|
|
||||||
init_choices: list[tuple[str, str]] = []
|
|
||||||
contructor_kwargs: list[str] = []
|
|
||||||
|
|
||||||
for field, raw_field in zip(schema.node.struct.fields, schema.as_struct().fields_list):
|
|
||||||
field_type = field.which()
|
|
||||||
|
|
||||||
if field_type == CapnpFieldType.SLOT:
|
|
||||||
definition_has_body = True
|
|
||||||
self.gen_slot(schema, field, raw_field, registered_type, contructor_kwargs, init_choices)
|
|
||||||
|
|
||||||
elif field_type == CapnpFieldType.GROUP:
|
|
||||||
group_name = field.name[0].upper() + field.name[1:]
|
|
||||||
|
|
||||||
assert group_name != field.name
|
|
||||||
|
|
||||||
raw_schema = raw_field.schema
|
|
||||||
group_name = self.gen_struct(raw_schema, type_name=group_name).name
|
|
||||||
field_py_code = f"{field.name}: {group_name}"
|
|
||||||
self.scope.add_line(field_py_code)
|
|
||||||
contructor_kwargs.append(field_py_code)
|
|
||||||
definition_has_body = True
|
|
||||||
init_choices.append((field.name, group_name))
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise AssertionError(f"{schema.node.displayName}: {field.name}: " f"{field.which()}")
|
|
||||||
|
|
||||||
if not registered_type.scope.is_root:
|
|
||||||
scoped_name = f"{registered_type.scope}.{type_name}"
|
|
||||||
|
|
||||||
else:
|
|
||||||
scoped_name = type_name
|
|
||||||
|
|
||||||
self.scope.add_line("@staticmethod")
|
|
||||||
self.scope.add_line(f"def from_bytes(data: bytes) -> {scoped_name}: ...")
|
|
||||||
self.scope.add_line("def to_bytes(self) -> bytes: ...")
|
|
||||||
definition_has_body = True
|
|
||||||
|
|
||||||
if schema.node.struct.discriminantCount:
|
|
||||||
literals = ", ".join(
|
|
||||||
f'Literal["{field.name}"]' for field in schema.node.struct.fields if field.discriminantValue != 65535
|
|
||||||
)
|
|
||||||
self._add_typing_import("Literal")
|
|
||||||
self._add_typing_import("Union")
|
|
||||||
self.scope.add_line(f"def which(self) -> Union[{literals}]: ...")
|
|
||||||
definition_has_body = True
|
|
||||||
|
|
||||||
if contructor_kwargs:
|
|
||||||
kwargs = ", ".join(f"{kwarg} = ..." for kwarg in contructor_kwargs)
|
|
||||||
self.scope.add_line(f"def __init__(self, *, {kwargs}) -> None: ...")
|
|
||||||
definition_has_body = True
|
|
||||||
|
|
||||||
if len(init_choices) > 1:
|
|
||||||
self._add_typing_import("Literal")
|
|
||||||
self._add_typing_import("overload")
|
|
||||||
|
|
||||||
for field_name, field_type in init_choices:
|
|
||||||
|
|
||||||
self.scope.add_line("@overload")
|
|
||||||
self.scope.add_line(f'def init(self, name: Literal["{field_name}"])' f" -> {field_type}: ...")
|
|
||||||
|
|
||||||
elif len(init_choices) == 1:
|
|
||||||
self._add_typing_import("Literal")
|
|
||||||
field_name, field_type = init_choices[0]
|
|
||||||
self.scope.add_line(f'def init(self, name: Literal["{field_name}"])' f" -> {field_type}: ...")
|
|
||||||
|
|
||||||
if not definition_has_body:
|
|
||||||
self.scope.add_line("pass")
|
|
||||||
|
|
||||||
self.return_from_scope()
|
|
||||||
|
|
||||||
return registered_type
|
|
||||||
|
|
||||||
def generate_nested(self, schema: Any) -> None:
|
|
||||||
"""Generate the type for a nested schema.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
schema (Any): The schema to generate types for.
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
AssertionError: If the schema belongs to an unknown type.
|
|
||||||
"""
|
|
||||||
if schema.node.id in self.type_map:
|
|
||||||
return # already generated type hints for this type
|
|
||||||
|
|
||||||
node_type = schema.node.which()
|
|
||||||
|
|
||||||
if node_type == "const":
|
|
||||||
self.gen_const(schema)
|
|
||||||
|
|
||||||
elif node_type == "struct":
|
|
||||||
self.gen_struct(schema)
|
|
||||||
|
|
||||||
elif node_type == "enum":
|
|
||||||
self.gen_enum(schema)
|
|
||||||
|
|
||||||
elif node_type == "interface":
|
|
||||||
logger.warning("Skipping interface: not implemented")
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise AssertionError(node_type)
|
|
||||||
|
|
||||||
def generate_recursive(self):
|
|
||||||
"""Generate types for all nested nodes, recursively."""
|
|
||||||
for node in self._module.schema.node.nestedNodes:
|
|
||||||
self.generate_nested(self._module.schema.get_nested(node.name))
|
|
||||||
|
|
||||||
def register_import(self, schema) -> CapnpType | None:
|
|
||||||
"""Determine, whether a schema is imported from the base module.
|
|
||||||
|
|
||||||
If so, the type definition that the schema contains, is added to the type registry.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
schema (Any): The schema to check.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Type | None: The type of the import, if the schema is imported,
|
|
||||||
or None if the schema defines the base module itself.
|
|
||||||
"""
|
|
||||||
module_name, definition_name = schema.node.displayName.split(":")
|
|
||||||
|
|
||||||
if module_name == self.base_module_name:
|
|
||||||
# This is the base module, not an import.
|
|
||||||
return None
|
|
||||||
|
|
||||||
common_path: str
|
|
||||||
matching_path: pathlib.Path | None = None
|
|
||||||
|
|
||||||
# Find the path of the parent module, from which this schema is imported.
|
|
||||||
for path, module in self._module_registry.values():
|
|
||||||
for node in module.schema.node.nestedNodes:
|
|
||||||
if node.id == schema.node.id:
|
|
||||||
matching_path = pathlib.Path(path)
|
|
||||||
break
|
|
||||||
|
|
||||||
# Since this is an import, there must be a parent module.
|
|
||||||
assert matching_path is not None
|
|
||||||
|
|
||||||
# Find the relative path to go from the parent module, to this imported module.
|
|
||||||
common_path = os.path.commonpath([self._module_path, matching_path])
|
|
||||||
|
|
||||||
relative_module_path = self._module_path.relative_to(common_path)
|
|
||||||
relative_import_path = matching_path.relative_to(common_path)
|
|
||||||
|
|
||||||
# Shape the relative path to a relative Python import statement.
|
|
||||||
python_import_path = "." * len(relative_module_path.parents) + replace_capnp_suffix(
|
|
||||||
".".join(relative_import_path.parts)
|
|
||||||
)
|
|
||||||
self._add_import(f"from {python_import_path} import {definition_name}")
|
|
||||||
|
|
||||||
return self.register_type(schema.node.id, schema, name=definition_name, scope=self.scope.root)
|
|
||||||
|
|
||||||
def register_type_var(self, name: str) -> str:
|
|
||||||
"""Find and register the full name of a type variable, which includes its scopes.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
name (str): The type name to register.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The full name in the format scope0_scope1_..._scopeN_name, including the type name to register.
|
|
||||||
"""
|
|
||||||
full_name: str = self.scope.trace_as_str("_") + f"_{name}"
|
|
||||||
|
|
||||||
self.type_vars.add(full_name)
|
|
||||||
return full_name
|
|
||||||
|
|
||||||
def register_type(self, type_id: int, schema: Any, name: str = "", scope: Scope | None = None) -> CapnpType:
|
|
||||||
"""Register a new type in the writer's registry of types.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
type_id (int): The identification number of the type.
|
|
||||||
schema (Any): The schema that defines the type.
|
|
||||||
name (str, optional): An name to specify, if overriding the type name. Defaults to "".
|
|
||||||
scope (Scope | None, optional): The scope in which the type is defined. Defaults to None.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Type: The registered type.
|
|
||||||
"""
|
|
||||||
if not name:
|
|
||||||
name = self.get_display_name(schema)
|
|
||||||
|
|
||||||
if scope is None:
|
|
||||||
scope = self.scope.parent
|
|
||||||
|
|
||||||
if scope is None:
|
|
||||||
raise ValueError(f"No valid scope was found for registering the type '{name}'.")
|
|
||||||
|
|
||||||
self.type_map[type_id] = retval = CapnpType(schema=schema, name=name, scope=scope)
|
|
||||||
return retval
|
|
||||||
|
|
||||||
def is_type_id_known(self, type_id: int) -> bool:
|
|
||||||
"""Check, whether a type ID was previously registered.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
type_id (int): The type ID to check.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: True, if the type ID is known, False otherwise.
|
|
||||||
"""
|
|
||||||
return type_id in self.type_map
|
|
||||||
|
|
||||||
def get_type_by_id(self, type_id: int) -> CapnpType:
|
|
||||||
"""Look up a type in the type registry, by means of its ID.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
type_id (int): The identification number of the type.
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
KeyError: If the type ID was not found in the registry.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Type: The type, if it exists.
|
|
||||||
"""
|
|
||||||
if self.is_type_id_known(type_id):
|
|
||||||
return self.type_map[type_id]
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise KeyError(f"The type ID '{type_id} was not found in the type registry.'")
|
|
||||||
|
|
||||||
def new_scope(self, name: str, node: Any, scope_heading: str) -> None:
|
|
||||||
"""Creates a new scope below the scope of the provided node.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
name (str): The name of the new scope.
|
|
||||||
node (Any): The node whose scope is the parent scope of the new scope.
|
|
||||||
scope_heading (str): The line of code that starts this new scope.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
parent_scope = self.scopes_by_id[node.scopeId]
|
|
||||||
|
|
||||||
except KeyError as e:
|
|
||||||
raise NoParentError(f"The scope with name '{name}' has no parent.") from e
|
|
||||||
|
|
||||||
# Add the heading of the scope to the parent scope.
|
|
||||||
parent_scope.add_line(scope_heading)
|
|
||||||
|
|
||||||
# Then, make a new scope that is one indent level deeper.
|
|
||||||
child_scope = Scope(name=name, id=node.id, parent=parent_scope, return_scope=self.scope)
|
|
||||||
|
|
||||||
self.scope = child_scope
|
|
||||||
self.scopes_by_id[node.id] = child_scope
|
|
||||||
|
|
||||||
def return_from_scope(self):
|
|
||||||
"""Return from the current scope."""
|
|
||||||
# Cannot return from the root scope, as it is the highest of all scopes.
|
|
||||||
assert not self.scope.is_root
|
|
||||||
|
|
||||||
scope = self.scope
|
|
||||||
scope.parent.lines += scope.lines
|
|
||||||
self.scope = scope.return_scope
|
|
||||||
|
|
||||||
def get_type_name(self, type_reader: capnp._DynamicStructReader) -> str:
|
|
||||||
"""Extract the type name from a type reader.
|
|
||||||
|
|
||||||
The output type name is prepended by the scope name, if there is a parent scope.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
type_reader (capnp._DynamicStructReader): The type reader to get the type name from.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The extracted type name.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
return CAPNP_TYPE_TO_PYTHON[type_reader.which()]
|
|
||||||
|
|
||||||
except KeyError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
type_reader_type = type_reader.which()
|
|
||||||
|
|
||||||
if type_reader_type == "struct":
|
|
||||||
element_type = self.get_type_by_id(type_reader.struct.typeId)
|
|
||||||
type_name = element_type.name
|
|
||||||
generic_params = []
|
|
||||||
|
|
||||||
for brand_scope in type_reader.struct.brand.scopes:
|
|
||||||
brand_scope_type = brand_scope.which()
|
|
||||||
|
|
||||||
if brand_scope_type == "inherit":
|
|
||||||
parent_scope = self.get_type_by_id(brand_scope.scopeId)
|
|
||||||
generic_params.extend(parent_scope.generic_params)
|
|
||||||
|
|
||||||
elif brand_scope_type == "bind":
|
|
||||||
for bind in brand_scope.bind:
|
|
||||||
generic_params.append(self.get_type_name(bind.type))
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise TypeError(f"Unknown brand scope '{brand_scope_type}'.")
|
|
||||||
|
|
||||||
if generic_params:
|
|
||||||
type_name += f"[{', '.join(generic_params)}]"
|
|
||||||
|
|
||||||
elif type_reader_type == "enum":
|
|
||||||
element_type = self.get_type_by_id(type_reader.enum.typeId)
|
|
||||||
type_name = element_type.name
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise TypeError(f"Unknown type reader type '{type_reader_type}'.")
|
|
||||||
|
|
||||||
if not element_type.scope.is_root:
|
|
||||||
return f"{element_type.scope}.{type_name}"
|
|
||||||
|
|
||||||
else:
|
|
||||||
return type_name
|
|
||||||
|
|
||||||
def dumps_pyi(self) -> str:
|
|
||||||
"""Generates string output for the *.pyi stub file that provides type hinting.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The output string.
|
|
||||||
"""
|
|
||||||
assert self.scope.is_root
|
|
||||||
|
|
||||||
out = []
|
|
||||||
out.append(self.docstring)
|
|
||||||
out.extend(self.imports)
|
|
||||||
out.append("")
|
|
||||||
|
|
||||||
if self.type_vars:
|
|
||||||
for name in sorted(self.type_vars):
|
|
||||||
out.append(f'{name} = TypeVar("{name}")')
|
|
||||||
out.append("")
|
|
||||||
|
|
||||||
out.extend(self.scope.lines)
|
|
||||||
return "\n".join(out)
|
|
||||||
|
|
||||||
def dumps_py(self) -> str:
|
|
||||||
"""Generates string output for the *.py stub file that handles the import of capnproto schemas.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The output string.
|
|
||||||
"""
|
|
||||||
assert self.scope.is_root
|
|
||||||
|
|
||||||
out = []
|
|
||||||
out.append(self.docstring)
|
|
||||||
out.append("import os")
|
|
||||||
out.append("import capnp")
|
|
||||||
out.append("capnp.remove_import_hook()")
|
|
||||||
out.append("here = os.path.dirname(os.path.abspath(__file__))")
|
|
||||||
|
|
||||||
out.append(f'module_file = os.path.abspath(os.path.join(here, "{self.base_module_name}"))')
|
|
||||||
|
|
||||||
for scope in self.scopes_by_id.values():
|
|
||||||
if scope.parent is not None and scope.parent.is_root:
|
|
||||||
out.append(f"{scope.name} = capnp.load(module_file).{scope.name}")
|
|
||||||
|
|
||||||
return "\n".join(out)
|
|
@ -0,0 +1 @@
|
|||||||
|
*dummy*.py*
|
@ -0,0 +1,26 @@
|
|||||||
|
# Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
|
||||||
|
# Licensed under the MIT License:
|
||||||
|
#
|
||||||
|
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
# of this software and associated documentation files (the "Software"), to deal
|
||||||
|
# in the Software without restriction, including without limitation the rights
|
||||||
|
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
# copies of the Software, and to permit persons to whom the Software is
|
||||||
|
# furnished to do so, subject to the following conditions:
|
||||||
|
#
|
||||||
|
# The above copyright notice and this permission notice shall be included in
|
||||||
|
# all copies or substantial portions of the Software.
|
||||||
|
#
|
||||||
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
# THE SOFTWARE.
|
||||||
|
|
||||||
|
@0xbdf87d7bb8304e81;
|
||||||
|
$namespace("capnp::annotations");
|
||||||
|
|
||||||
|
annotation namespace(file): Text;
|
||||||
|
annotation name(field, enumerant, struct, enum, interface, method, param, group, union): Text;
|
@ -0,0 +1,48 @@
|
|||||||
|
# Copyright (c) 2016 NetDEF, Inc. and contributors
|
||||||
|
# Licensed under the MIT License:
|
||||||
|
#
|
||||||
|
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
# of this software and associated documentation files (the "Software"), to deal
|
||||||
|
# in the Software without restriction, including without limitation the rights
|
||||||
|
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
# copies of the Software, and to permit persons to whom the Software is
|
||||||
|
# furnished to do so, subject to the following conditions:
|
||||||
|
#
|
||||||
|
# The above copyright notice and this permission notice shall be included in
|
||||||
|
# all copies or substantial portions of the Software.
|
||||||
|
#
|
||||||
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
# THE SOFTWARE.
|
||||||
|
|
||||||
|
@0xc0183dd65ffef0f3;
|
||||||
|
|
||||||
|
annotation nameinfix @0x85a8d86d736ba637 (file): Text;
|
||||||
|
# add an infix (middle insert) for output file names
|
||||||
|
#
|
||||||
|
# "make" generally has implicit rules for compiling "foo.c" => "foo". This
|
||||||
|
# is very annoying with capnp since the rule will be "foo" => "foo.c", leading
|
||||||
|
# to a loop. $nameinfix (recommended parameter: "-gen") inserts its parameter
|
||||||
|
# before the ".c", so the filename becomes "foo-gen.c"
|
||||||
|
#
|
||||||
|
# Alternatively, add this Makefile rule to disable compiling "foo.capnp.c" -> "foo.capnp":
|
||||||
|
# %.capnp: ;
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# ("foo" is really "foo.capnp", so it's foo.capnp-gen.c)
|
||||||
|
|
||||||
|
annotation fieldgetset @0xf72bc690355d66de (file): Void;
|
||||||
|
# generate getter & setter functions for accessing fields
|
||||||
|
#
|
||||||
|
# allows grabbing/putting values without de-/encoding the entire struct.
|
||||||
|
|
||||||
|
annotation donotinclude @0x8c99797357b357e9 (file): UInt64;
|
||||||
|
# do not generate an include directive for an import statement for the file with
|
||||||
|
# the given ID
|
||||||
|
|
||||||
|
annotation typedefto @0xcefaf27713042144 (struct, enum): Text;
|
||||||
|
# generate a typedef for the annotated struct or enum declaration
|
@ -0,0 +1,711 @@
|
|||||||
|
# Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
|
||||||
|
# Licensed under the MIT License:
|
||||||
|
#
|
||||||
|
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
# of this software and associated documentation files (the "Software"), to deal
|
||||||
|
# in the Software without restriction, including without limitation the rights
|
||||||
|
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
# copies of the Software, and to permit persons to whom the Software is
|
||||||
|
# furnished to do so, subject to the following conditions:
|
||||||
|
#
|
||||||
|
# The above copyright notice and this permission notice shall be included in
|
||||||
|
# all copies or substantial portions of the Software.
|
||||||
|
#
|
||||||
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
# THE SOFTWARE.
|
||||||
|
|
||||||
|
@0xd6fe35252d9d2bbb;
|
||||||
|
|
||||||
|
using C = import "c.capnp";
|
||||||
|
using Cxx = import "c++.capnp";
|
||||||
|
|
||||||
|
$C.fieldgetset;
|
||||||
|
|
||||||
|
# Use a namespace likely to cause trouble if the generated code doesn't use fully-qualified
|
||||||
|
# names for stuff in the capnproto namespace.
|
||||||
|
$Cxx.namespace("capnproto_test::capnp::test");
|
||||||
|
|
||||||
|
enum TestEnum {
|
||||||
|
foo @0;
|
||||||
|
bar @1;
|
||||||
|
baz @2;
|
||||||
|
qux @3;
|
||||||
|
quux @4;
|
||||||
|
corge @5;
|
||||||
|
grault @6;
|
||||||
|
garply @7;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestAllTypes {
|
||||||
|
voidField @0 : Void;
|
||||||
|
boolField @1 : Bool;
|
||||||
|
int8Field @2 : Int8;
|
||||||
|
int16Field @3 : Int16;
|
||||||
|
int32Field @4 : Int32;
|
||||||
|
int64Field @5 : Int64;
|
||||||
|
uInt8Field @6 : UInt8;
|
||||||
|
uInt16Field @7 : UInt16;
|
||||||
|
uInt32Field @8 : UInt32;
|
||||||
|
uInt64Field @9 : UInt64;
|
||||||
|
float32Field @10 : Float32;
|
||||||
|
float64Field @11 : Float64;
|
||||||
|
textField @12 : Text;
|
||||||
|
dataField @13 : Data;
|
||||||
|
structField @14 : TestAllTypes;
|
||||||
|
enumField @15 : TestEnum;
|
||||||
|
interfaceField @16 : Void; # TODO
|
||||||
|
|
||||||
|
voidList @17 : List(Void);
|
||||||
|
boolList @18 : List(Bool);
|
||||||
|
int8List @19 : List(Int8);
|
||||||
|
int16List @20 : List(Int16);
|
||||||
|
int32List @21 : List(Int32);
|
||||||
|
int64List @22 : List(Int64);
|
||||||
|
uInt8List @23 : List(UInt8);
|
||||||
|
uInt16List @24 : List(UInt16);
|
||||||
|
uInt32List @25 : List(UInt32);
|
||||||
|
uInt64List @26 : List(UInt64);
|
||||||
|
float32List @27 : List(Float32);
|
||||||
|
float64List @28 : List(Float64);
|
||||||
|
textList @29 : List(Text);
|
||||||
|
dataList @30 : List(Data);
|
||||||
|
structList @31 : List(TestAllTypes);
|
||||||
|
enumList @32 : List(TestEnum);
|
||||||
|
interfaceList @33 : List(Void); # TODO
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestDefaults {
|
||||||
|
voidField @0 : Void = void;
|
||||||
|
boolField @1 : Bool = true;
|
||||||
|
int8Field @2 : Int8 = -123;
|
||||||
|
int16Field @3 : Int16 = -12345;
|
||||||
|
int32Field @4 : Int32 = -12345678;
|
||||||
|
int64Field @5 : Int64 = -123456789012345;
|
||||||
|
uInt8Field @6 : UInt8 = 234;
|
||||||
|
uInt16Field @7 : UInt16 = 45678;
|
||||||
|
uInt32Field @8 : UInt32 = 3456789012;
|
||||||
|
uInt64Field @9 : UInt64 = 12345678901234567890;
|
||||||
|
float32Field @10 : Float32 = 1234.5;
|
||||||
|
float64Field @11 : Float64 = -123e45;
|
||||||
|
textField @12 : Text = "foo";
|
||||||
|
dataField @13 : Data = 0x"62 61 72"; # "bar"
|
||||||
|
structField @14 : TestAllTypes = (
|
||||||
|
voidField = void,
|
||||||
|
boolField = true,
|
||||||
|
int8Field = -12,
|
||||||
|
int16Field = 3456,
|
||||||
|
int32Field = -78901234,
|
||||||
|
int64Field = 56789012345678,
|
||||||
|
uInt8Field = 90,
|
||||||
|
uInt16Field = 1234,
|
||||||
|
uInt32Field = 56789012,
|
||||||
|
uInt64Field = 345678901234567890,
|
||||||
|
float32Field = -1.25e-10,
|
||||||
|
float64Field = 345,
|
||||||
|
textField = "baz",
|
||||||
|
dataField = "qux",
|
||||||
|
structField = (
|
||||||
|
textField = "nested",
|
||||||
|
structField = (textField = "really nested")),
|
||||||
|
enumField = baz,
|
||||||
|
# interfaceField can't have a default
|
||||||
|
|
||||||
|
voidList = [void, void, void],
|
||||||
|
boolList = [false, true, false, true, true],
|
||||||
|
int8List = [12, -34, -0x80, 0x7f],
|
||||||
|
int16List = [1234, -5678, -0x8000, 0x7fff],
|
||||||
|
int32List = [12345678, -90123456, -0x80000000, 0x7fffffff],
|
||||||
|
int64List = [123456789012345, -678901234567890, -0x8000000000000000, 0x7fffffffffffffff],
|
||||||
|
uInt8List = [12, 34, 0, 0xff],
|
||||||
|
uInt16List = [1234, 5678, 0, 0xffff],
|
||||||
|
uInt32List = [12345678, 90123456, 0, 0xffffffff],
|
||||||
|
uInt64List = [123456789012345, 678901234567890, 0, 0xffffffffffffffff],
|
||||||
|
float32List = [0, 1234567, 1e37, -1e37, 1e-37, -1e-37],
|
||||||
|
float64List = [0, 123456789012345, 1e306, -1e306, 1e-306, -1e-306],
|
||||||
|
textList = ["quux", "corge", "grault"],
|
||||||
|
dataList = ["garply", "waldo", "fred"],
|
||||||
|
structList = [
|
||||||
|
(textField = "x structlist 1"),
|
||||||
|
(textField = "x structlist 2"),
|
||||||
|
(textField = "x structlist 3")],
|
||||||
|
enumList = [qux, bar, grault]
|
||||||
|
# interfaceList can't have a default
|
||||||
|
);
|
||||||
|
enumField @15 : TestEnum = corge;
|
||||||
|
interfaceField @16 : Void; # TODO
|
||||||
|
|
||||||
|
voidList @17 : List(Void) = [void, void, void, void, void, void];
|
||||||
|
boolList @18 : List(Bool) = [true, false, false, true];
|
||||||
|
int8List @19 : List(Int8) = [111, -111];
|
||||||
|
int16List @20 : List(Int16) = [11111, -11111];
|
||||||
|
int32List @21 : List(Int32) = [111111111, -111111111];
|
||||||
|
int64List @22 : List(Int64) = [1111111111111111111, -1111111111111111111];
|
||||||
|
uInt8List @23 : List(UInt8) = [111, 222] ;
|
||||||
|
uInt16List @24 : List(UInt16) = [33333, 44444];
|
||||||
|
uInt32List @25 : List(UInt32) = [3333333333];
|
||||||
|
uInt64List @26 : List(UInt64) = [11111111111111111111];
|
||||||
|
float32List @27 : List(Float32) = [5555.5, inf, -inf, nan];
|
||||||
|
float64List @28 : List(Float64) = [7777.75, inf, -inf, nan];
|
||||||
|
textList @29 : List(Text) = ["plugh", "xyzzy", "thud"];
|
||||||
|
dataList @30 : List(Data) = ["oops", "exhausted", "rfc3092"];
|
||||||
|
structList @31 : List(TestAllTypes) = [
|
||||||
|
(textField = "structlist 1"),
|
||||||
|
(textField = "structlist 2"),
|
||||||
|
(textField = "structlist 3")];
|
||||||
|
enumList @32 : List(TestEnum) = [foo, garply];
|
||||||
|
interfaceList @33 : List(Void); # TODO
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestAnyPointer {
|
||||||
|
anyPointerField @0 :AnyPointer;
|
||||||
|
|
||||||
|
# Do not add any other fields here! Some tests rely on anyPointerField being the last pointer
|
||||||
|
# in the struct.
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestOutOfOrder {
|
||||||
|
foo @3 :Text;
|
||||||
|
bar @2 :Text;
|
||||||
|
baz @8 :Text;
|
||||||
|
qux @0 :Text;
|
||||||
|
quux @6 :Text;
|
||||||
|
corge @4 :Text;
|
||||||
|
grault @1 :Text;
|
||||||
|
garply @7 :Text;
|
||||||
|
waldo @5 :Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestUnion {
|
||||||
|
union0 @0! :union {
|
||||||
|
# Pack union 0 under ideal conditions: there is no unused padding space prior to it.
|
||||||
|
u0f0s0 @4: Void;
|
||||||
|
u0f0s1 @5: Bool;
|
||||||
|
u0f0s8 @6: Int8;
|
||||||
|
u0f0s16 @7: Int16;
|
||||||
|
u0f0s32 @8: Int32;
|
||||||
|
u0f0s64 @9: Int64;
|
||||||
|
u0f0sp @10: Text;
|
||||||
|
|
||||||
|
# Pack more stuff into union0 -- should go in same space.
|
||||||
|
u0f1s0 @11: Void;
|
||||||
|
u0f1s1 @12: Bool;
|
||||||
|
u0f1s8 @13: Int8;
|
||||||
|
u0f1s16 @14: Int16;
|
||||||
|
u0f1s32 @15: Int32;
|
||||||
|
u0f1s64 @16: Int64;
|
||||||
|
u0f1sp @17: Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Pack one bit in order to make pathological situation for union1.
|
||||||
|
bit0 @18: Bool;
|
||||||
|
|
||||||
|
union1 @1! :union {
|
||||||
|
# Pack pathologically bad case. Each field takes up new space.
|
||||||
|
u1f0s0 @19: Void;
|
||||||
|
u1f0s1 @20: Bool;
|
||||||
|
u1f1s1 @21: Bool;
|
||||||
|
u1f0s8 @22: Int8;
|
||||||
|
u1f1s8 @23: Int8;
|
||||||
|
u1f0s16 @24: Int16;
|
||||||
|
u1f1s16 @25: Int16;
|
||||||
|
u1f0s32 @26: Int32;
|
||||||
|
u1f1s32 @27: Int32;
|
||||||
|
u1f0s64 @28: Int64;
|
||||||
|
u1f1s64 @29: Int64;
|
||||||
|
u1f0sp @30: Text;
|
||||||
|
u1f1sp @31: Text;
|
||||||
|
|
||||||
|
# Pack more stuff into union1 -- each should go into the same space as corresponding u1f0s*.
|
||||||
|
u1f2s0 @32: Void;
|
||||||
|
u1f2s1 @33: Bool;
|
||||||
|
u1f2s8 @34: Int8;
|
||||||
|
u1f2s16 @35: Int16;
|
||||||
|
u1f2s32 @36: Int32;
|
||||||
|
u1f2s64 @37: Int64;
|
||||||
|
u1f2sp @38: Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Fill in the rest of that bitfield from earlier.
|
||||||
|
bit2 @39: Bool;
|
||||||
|
bit3 @40: Bool;
|
||||||
|
bit4 @41: Bool;
|
||||||
|
bit5 @42: Bool;
|
||||||
|
bit6 @43: Bool;
|
||||||
|
bit7 @44: Bool;
|
||||||
|
|
||||||
|
# Interleave two unions to be really annoying.
|
||||||
|
# Also declare in reverse order to make sure union discriminant values are sorted by field number
|
||||||
|
# and not by declaration order.
|
||||||
|
union2 @2! :union {
|
||||||
|
u2f0s64 @54: Int64;
|
||||||
|
u2f0s32 @52: Int32;
|
||||||
|
u2f0s16 @50: Int16;
|
||||||
|
u2f0s8 @47: Int8;
|
||||||
|
u2f0s1 @45: Bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
union3 @3! :union {
|
||||||
|
u3f0s64 @55: Int64;
|
||||||
|
u3f0s32 @53: Int32;
|
||||||
|
u3f0s16 @51: Int16;
|
||||||
|
u3f0s8 @48: Int8;
|
||||||
|
u3f0s1 @46: Bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
byte0 @49: UInt8;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestUnnamedUnion {
|
||||||
|
before @0 :Text;
|
||||||
|
|
||||||
|
union {
|
||||||
|
foo @1 :UInt16;
|
||||||
|
bar @3 :UInt32;
|
||||||
|
}
|
||||||
|
|
||||||
|
middle @2 :UInt16;
|
||||||
|
|
||||||
|
after @4 :Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestUnionInUnion {
|
||||||
|
# There is no reason to ever do this.
|
||||||
|
outer :union {
|
||||||
|
inner :union {
|
||||||
|
foo @0 :Int32;
|
||||||
|
bar @1 :Int32;
|
||||||
|
}
|
||||||
|
baz @2 :Int32;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestGroups {
|
||||||
|
groups :union {
|
||||||
|
foo :group {
|
||||||
|
corge @0 :Int32;
|
||||||
|
grault @2 :Int64;
|
||||||
|
garply @8 :Text;
|
||||||
|
}
|
||||||
|
bar :group {
|
||||||
|
corge @3 :Int32;
|
||||||
|
grault @4 :Text;
|
||||||
|
garply @5 :Int64;
|
||||||
|
}
|
||||||
|
baz :group {
|
||||||
|
corge @1 :Int32;
|
||||||
|
grault @6 :Text;
|
||||||
|
garply @7 :Text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestInterleavedGroups {
|
||||||
|
group1 :group {
|
||||||
|
foo @0 :UInt32;
|
||||||
|
bar @2 :UInt64;
|
||||||
|
union {
|
||||||
|
qux @4 :UInt16;
|
||||||
|
corge :group {
|
||||||
|
grault @6 :UInt64;
|
||||||
|
garply @8 :UInt16;
|
||||||
|
plugh @14 :Text;
|
||||||
|
xyzzy @16 :Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
fred @12 :Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
waldo @10 :Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
group2 :group {
|
||||||
|
foo @1 :UInt32;
|
||||||
|
bar @3 :UInt64;
|
||||||
|
union {
|
||||||
|
qux @5 :UInt16;
|
||||||
|
corge :group {
|
||||||
|
grault @7 :UInt64;
|
||||||
|
garply @9 :UInt16;
|
||||||
|
plugh @15 :Text;
|
||||||
|
xyzzy @17 :Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
fred @13 :Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
waldo @11 :Text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestUnionDefaults {
|
||||||
|
s16s8s64s8Set @0 :TestUnion =
|
||||||
|
(union0 = (u0f0s16 = 321), union1 = (u1f0s8 = 123), union2 = (u2f0s64 = 12345678901234567),
|
||||||
|
union3 = (u3f0s8 = 55));
|
||||||
|
s0sps1s32Set @1 :TestUnion =
|
||||||
|
(union0 = (u0f1s0 = void), union1 = (u1f0sp = "foo"), union2 = (u2f0s1 = true),
|
||||||
|
union3 = (u3f0s32 = 12345678));
|
||||||
|
|
||||||
|
unnamed1 @2 :TestUnnamedUnion = (foo = 123);
|
||||||
|
unnamed2 @3 :TestUnnamedUnion = (bar = 321, before = "foo", after = "bar");
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestNestedTypes {
|
||||||
|
enum NestedEnum1 {
|
||||||
|
foo @0;
|
||||||
|
bar @1;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct NestedStruct {
|
||||||
|
enum NestedEnum2 {
|
||||||
|
baz @0;
|
||||||
|
qux @1;
|
||||||
|
quux @2;
|
||||||
|
}
|
||||||
|
|
||||||
|
outerNestedEnum @0 :TestNestedTypes.NestedEnum1 = bar;
|
||||||
|
innerNestedEnum @1 :NestedEnum2 = quux;
|
||||||
|
listOuterNestedEnum @2 :List(NestedEnum1) = [foo, bar];
|
||||||
|
listInnerNestedEnum @3 :List(NestedEnum2) = [quux, qux];
|
||||||
|
}
|
||||||
|
|
||||||
|
nestedStruct @0 :NestedStruct;
|
||||||
|
|
||||||
|
outerNestedEnum @1 :NestedEnum1 = bar;
|
||||||
|
innerNestedEnum @2 :NestedStruct.NestedEnum2 = quux;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestUsing {
|
||||||
|
using OuterNestedEnum = TestNestedTypes.NestedEnum1;
|
||||||
|
using TestNestedTypes.NestedStruct.NestedEnum2;
|
||||||
|
|
||||||
|
outerNestedEnum @1 :OuterNestedEnum = bar;
|
||||||
|
innerNestedEnum @0 :NestedEnum2 = quux;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestLists {
|
||||||
|
# Small structs, when encoded as list, will be encoded as primitive lists rather than struct
|
||||||
|
# lists, to save space.
|
||||||
|
struct Struct0 { f @0 :Void; }
|
||||||
|
struct Struct1 { f @0 :Bool; }
|
||||||
|
struct Struct8 { f @0 :UInt8; }
|
||||||
|
struct Struct16 { f @0 :UInt16; }
|
||||||
|
struct Struct32 { f @0 :UInt32; }
|
||||||
|
struct Struct64 { f @0 :UInt64; }
|
||||||
|
struct StructP { f @0 :Text; }
|
||||||
|
|
||||||
|
# Versions of the above which cannot be encoded as primitive lists.
|
||||||
|
struct Struct0c { f @0 :Void; pad @1 :Text; }
|
||||||
|
struct Struct1c { f @0 :Bool; pad @1 :Text; }
|
||||||
|
struct Struct8c { f @0 :UInt8; pad @1 :Text; }
|
||||||
|
struct Struct16c { f @0 :UInt16; pad @1 :Text; }
|
||||||
|
struct Struct32c { f @0 :UInt32; pad @1 :Text; }
|
||||||
|
struct Struct64c { f @0 :UInt64; pad @1 :Text; }
|
||||||
|
struct StructPc { f @0 :Text; pad @1 :UInt64; }
|
||||||
|
|
||||||
|
list0 @0 :List(Struct0);
|
||||||
|
list1 @1 :List(Struct1);
|
||||||
|
list8 @2 :List(Struct8);
|
||||||
|
list16 @3 :List(Struct16);
|
||||||
|
list32 @4 :List(Struct32);
|
||||||
|
list64 @5 :List(Struct64);
|
||||||
|
listP @6 :List(StructP);
|
||||||
|
|
||||||
|
listlist0 @7 :List(List(Struct0));
|
||||||
|
listlist1 @8 :List(List(Struct1));
|
||||||
|
listlist8 @9 :List(List(Struct8));
|
||||||
|
listlist16 @10 :List(List(Struct16));
|
||||||
|
listlist32 @11 :List(List(Struct32));
|
||||||
|
listlist64 @12 :List(List(Struct64));
|
||||||
|
listlistP @13 :List(List(StructP));
|
||||||
|
|
||||||
|
list0c @14 :List(Struct0c);
|
||||||
|
list1c @15 :List(Struct1c);
|
||||||
|
list8c @16 :List(Struct8c);
|
||||||
|
list16c @17 :List(Struct16c);
|
||||||
|
list32c @18 :List(Struct32c);
|
||||||
|
list64c @19 :List(Struct64c);
|
||||||
|
listPc @20 :List(StructPc);
|
||||||
|
|
||||||
|
listlist0c @21 :List(List(Struct0c));
|
||||||
|
listlist1c @22 :List(List(Struct1c));
|
||||||
|
listlist8c @23 :List(List(Struct8c));
|
||||||
|
listlist16c @24 :List(List(Struct16c));
|
||||||
|
listlist32c @25 :List(List(Struct32c));
|
||||||
|
listlist64c @26 :List(List(Struct64c));
|
||||||
|
listlistPc @27 :List(List(StructPc));
|
||||||
|
|
||||||
|
int32ListList @28 :List(List(Int32));
|
||||||
|
textListList @29 :List(List(Text));
|
||||||
|
structListList @30 :List(List(TestAllTypes));
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestFieldZeroIsBit {
|
||||||
|
bit @0 :Bool;
|
||||||
|
secondBit @1 :Bool = true;
|
||||||
|
thirdField @2 :UInt8 = 123;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestListDefaults {
|
||||||
|
lists @0 :TestLists = (
|
||||||
|
list0 = [(f = void), (f = void)],
|
||||||
|
list1 = [(f = true), (f = false)],
|
||||||
|
list8 = [(f = 123), (f = 45)],
|
||||||
|
list16 = [(f = 12345), (f = 6789)],
|
||||||
|
list32 = [(f = 123456789), (f = 234567890)],
|
||||||
|
list64 = [(f = 1234567890123456), (f = 2345678901234567)],
|
||||||
|
listP = [(f = "foo"), (f = "bar")],
|
||||||
|
|
||||||
|
listlist0 = [[(f = void), (f = void)],[(f = void), (f = void)]],
|
||||||
|
listlist1 = [[(f = true), (f = false)],[(f = true), (f = true)]],
|
||||||
|
listlist8 = [[(f = 123), (f = 45)],[(f = 123), (f = 45)]],
|
||||||
|
listlist16 = [[(f = 12345), (f = 6789)],[(f = 12345), (f = 6789)]],
|
||||||
|
listlist32 = [[(f = 123456789), (f = 234567890)],[(f = 123456789), (f = 234567890)]],
|
||||||
|
listlist64 = [[(f = 1234567890123456), (f = 2345678901234567)],[(f = 1234567890123456), (f = 2345678901234567)]],
|
||||||
|
listlistP = [[(f = "foo"), (f = "bar")],[(f = "foo"), (f = "bar")]],
|
||||||
|
|
||||||
|
list0c = [(f = void, pad = "foo"), (f = void, pad = "bar")],
|
||||||
|
list1c = [(f = true, pad = "foo"), (f = false, pad = "bar")],
|
||||||
|
list8c = [(f = 123, pad = "foo"), (f = 45, pad = "bar")],
|
||||||
|
list16c = [(f = 12345, pad = "foo"), (f = 6789, pad = "bar")],
|
||||||
|
list32c = [(f = 123456789, pad = "foo"), (f = 234567890, pad = "bar")],
|
||||||
|
list64c = [(f = 1234567890123456, pad = "foo"), (f = 2345678901234567, pad = "bar")],
|
||||||
|
listPc = [(f = "foo", pad = 1234567890123456), (f = "bar", pad = 2345678901234567)],
|
||||||
|
|
||||||
|
listlist0c = [[(f = void, pad = "foo"), (f = void, pad = "bar")],[(f = void, pad = "foo"), (f = void, pad = "bar")]],
|
||||||
|
listlist1c = [[(f = true, pad = "foo"), (f = false, pad = "bar")],[(f = true, pad = "foo"), (f = false, pad = "bar")]],
|
||||||
|
listlist8c = [[(f = 123, pad = "foo"), (f = 45, pad = "bar")],[(f = 123, pad = "foo"), (f = 45, pad = "bar")]],
|
||||||
|
listlist16c = [[(f = 12345, pad = "foo"), (f = 6789, pad = "bar")],[(f = 12345, pad = "foo"), (f = 6789, pad = "bar")]],
|
||||||
|
listlist32c = [[(f = 123456789, pad = "foo"), (f = 234567890, pad = "bar")],[(f = 123456789, pad = "foo"), (f = 234567890, pad = "bar")]],
|
||||||
|
listlist64c = [[(f = 1234567890123456, pad = "foo"), (f = 2345678901234567, pad = "bar")],[(f = 1234567890123456, pad = "foo"), (f = 2345678901234567, pad = "bar")]],
|
||||||
|
listlistPc = [[(f = "foo", pad = 1234567890123456), (f = "bar", pad = 2345678901234567)],[(f = "foo", pad = 1234567890123456), (f = "bar", pad = 2345678901234567)]],
|
||||||
|
|
||||||
|
int32ListList = [[1, 2, 3], [4, 5], [12341234]],
|
||||||
|
textListList = [["foo", "bar"], ["baz"], ["qux", "corge"]],
|
||||||
|
structListList = [[(int32Field = 123), (int32Field = 456)], [(int32Field = 789)]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestLateUnion {
|
||||||
|
# Test what happens if the unions are not the first ordinals in the struct. At one point this
|
||||||
|
# was broken for the dynamic API.
|
||||||
|
|
||||||
|
foo @0 :Int32;
|
||||||
|
bar @1 :Text;
|
||||||
|
baz @2 :Int16;
|
||||||
|
|
||||||
|
theUnion @3! :union {
|
||||||
|
qux @4 :Text;
|
||||||
|
corge @5 :List(Int32);
|
||||||
|
grault @6 :Float32;
|
||||||
|
}
|
||||||
|
|
||||||
|
anotherUnion @7! :union {
|
||||||
|
qux @8 :Text;
|
||||||
|
corge @9 :List(Int32);
|
||||||
|
grault @10 :Float32;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestOldVersion {
|
||||||
|
# A subset of TestNewVersion.
|
||||||
|
old1 @0 :Int64;
|
||||||
|
old2 @1 :Text;
|
||||||
|
old3 @2 :TestOldVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestNewVersion {
|
||||||
|
# A superset of TestOldVersion.
|
||||||
|
old1 @0 :Int64;
|
||||||
|
old2 @1 :Text;
|
||||||
|
old3 @2 :TestNewVersion;
|
||||||
|
new1 @3 :Int64 = 987;
|
||||||
|
new2 @4 :Text = "baz";
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestStructUnion {
|
||||||
|
un @0! :union {
|
||||||
|
struct @1 :SomeStruct;
|
||||||
|
object @2 :TestAnyPointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SomeStruct {
|
||||||
|
someText @0 :Text;
|
||||||
|
moreText @1 :Text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestPrintInlineStructs {
|
||||||
|
someText @0 :Text;
|
||||||
|
|
||||||
|
structList @1 :List(InlineStruct);
|
||||||
|
struct InlineStruct {
|
||||||
|
int32Field @0 :Int32;
|
||||||
|
textField @1 :Text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestWholeFloatDefault {
|
||||||
|
# At one point, these failed to compile in C++ because it would produce literals like "123f",
|
||||||
|
# which is not valid; it needs to be "123.0f".
|
||||||
|
field @0 :Float32 = 123;
|
||||||
|
bigField @1 :Float32 = 2e30;
|
||||||
|
const constant :Float32 = 456;
|
||||||
|
const bigConstant :Float32 = 4e30;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestEmptyStruct {}
|
||||||
|
|
||||||
|
struct TestConstants {
|
||||||
|
const voidConst :Void = void;
|
||||||
|
const boolConst :Bool = true;
|
||||||
|
const int8Const :Int8 = -123;
|
||||||
|
const int16Const :Int16 = -12345;
|
||||||
|
const int32Const :Int32 = -12345678;
|
||||||
|
const int64Const :Int64 = -123456789012345;
|
||||||
|
const uint8Const :UInt8 = 234;
|
||||||
|
const uint16Const :UInt16 = 45678;
|
||||||
|
const uint32Const :UInt32 = 3456789012;
|
||||||
|
const uint64Const :UInt64 = 12345678901234567890;
|
||||||
|
const float32Const :Float32 = 1234.5;
|
||||||
|
const float64Const :Float64 = -123e45;
|
||||||
|
const textConst :Text = "foo";
|
||||||
|
const dataConst :Data = "bar";
|
||||||
|
const structConst :TestAllTypes = (
|
||||||
|
voidField = void,
|
||||||
|
boolField = true,
|
||||||
|
int8Field = -12,
|
||||||
|
int16Field = 3456,
|
||||||
|
int32Field = -78901234,
|
||||||
|
int64Field = 56789012345678,
|
||||||
|
uInt8Field = 90,
|
||||||
|
uInt16Field = 1234,
|
||||||
|
uInt32Field = 56789012,
|
||||||
|
uInt64Field = 345678901234567890,
|
||||||
|
float32Field = -1.25e-10,
|
||||||
|
float64Field = 345,
|
||||||
|
textField = "baz",
|
||||||
|
dataField = "qux",
|
||||||
|
structField = (
|
||||||
|
textField = "nested",
|
||||||
|
structField = (textField = "really nested")),
|
||||||
|
enumField = baz,
|
||||||
|
# interfaceField can't have a default
|
||||||
|
|
||||||
|
voidList = [void, void, void],
|
||||||
|
boolList = [false, true, false, true, true],
|
||||||
|
int8List = [12, -34, -0x80, 0x7f],
|
||||||
|
int16List = [1234, -5678, -0x8000, 0x7fff],
|
||||||
|
int32List = [12345678, -90123456, -0x80000000, 0x7fffffff],
|
||||||
|
int64List = [123456789012345, -678901234567890, -0x8000000000000000, 0x7fffffffffffffff],
|
||||||
|
uInt8List = [12, 34, 0, 0xff],
|
||||||
|
uInt16List = [1234, 5678, 0, 0xffff],
|
||||||
|
uInt32List = [12345678, 90123456, 0, 0xffffffff],
|
||||||
|
uInt64List = [123456789012345, 678901234567890, 0, 0xffffffffffffffff],
|
||||||
|
float32List = [0, 1234567, 1e37, -1e37, 1e-37, -1e-37],
|
||||||
|
float64List = [0, 123456789012345, 1e306, -1e306, 1e-306, -1e-306],
|
||||||
|
textList = ["quux", "corge", "grault"],
|
||||||
|
dataList = ["garply", "waldo", "fred"],
|
||||||
|
structList = [
|
||||||
|
(textField = "x structlist 1"),
|
||||||
|
(textField = "x structlist 2"),
|
||||||
|
(textField = "x structlist 3")],
|
||||||
|
enumList = [qux, bar, grault]
|
||||||
|
# interfaceList can't have a default
|
||||||
|
);
|
||||||
|
const enumConst :TestEnum = corge;
|
||||||
|
|
||||||
|
const voidListConst :List(Void) = [void, void, void, void, void, void];
|
||||||
|
const boolListConst :List(Bool) = [true, false, false, true];
|
||||||
|
const int8ListConst :List(Int8) = [111, -111];
|
||||||
|
const int16ListConst :List(Int16) = [11111, -11111];
|
||||||
|
const int32ListConst :List(Int32) = [111111111, -111111111];
|
||||||
|
const int64ListConst :List(Int64) = [1111111111111111111, -1111111111111111111];
|
||||||
|
const uint8ListConst :List(UInt8) = [111, 222] ;
|
||||||
|
const uint16ListConst :List(UInt16) = [33333, 44444];
|
||||||
|
const uint32ListConst :List(UInt32) = [3333333333];
|
||||||
|
const uint64ListConst :List(UInt64) = [11111111111111111111];
|
||||||
|
const float32ListConst :List(Float32) = [5555.5, inf, -inf, nan];
|
||||||
|
const float64ListConst :List(Float64) = [7777.75, inf, -inf, nan];
|
||||||
|
const textListConst :List(Text) = ["plugh", "xyzzy", "thud"];
|
||||||
|
const dataListConst :List(Data) = ["oops", "exhausted", "rfc3092"];
|
||||||
|
const structListConst :List(TestAllTypes) = [
|
||||||
|
(textField = "structlist 1"),
|
||||||
|
(textField = "structlist 2"),
|
||||||
|
(textField = "structlist 3")];
|
||||||
|
const enumListConst :List(TestEnum) = [foo, garply];
|
||||||
|
}
|
||||||
|
|
||||||
|
const globalInt :UInt32 = 12345;
|
||||||
|
const globalText :Text = "foobar";
|
||||||
|
const globalStruct :TestAllTypes = (int32Field = 54321);
|
||||||
|
const globalPrintableStruct :TestPrintInlineStructs = (someText = "foo");
|
||||||
|
const derivedConstant :TestAllTypes = (
|
||||||
|
uInt32Field = .globalInt,
|
||||||
|
textField = TestConstants.textConst,
|
||||||
|
structField = TestConstants.structConst,
|
||||||
|
int16List = TestConstants.int16ListConst,
|
||||||
|
structList = TestConstants.structListConst);
|
||||||
|
|
||||||
|
struct TestSturdyRef {
|
||||||
|
hostId @0 :TestSturdyRefHostId;
|
||||||
|
objectId @1 :AnyPointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestSturdyRefHostId {
|
||||||
|
host @0 :Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestSturdyRefObjectId {
|
||||||
|
tag @0 :Tag;
|
||||||
|
enum Tag {
|
||||||
|
testInterface @0;
|
||||||
|
testExtends @1;
|
||||||
|
testPipeline @2;
|
||||||
|
testTailCallee @3;
|
||||||
|
testTailCaller @4;
|
||||||
|
testMoreStuff @5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestProvisionId {}
|
||||||
|
struct TestRecipientId {}
|
||||||
|
struct TestThirdPartyCapId {}
|
||||||
|
struct TestJoinResult {}
|
||||||
|
|
||||||
|
struct TestNameAnnotation $Cxx.name("RenamedStruct") {
|
||||||
|
union {
|
||||||
|
badFieldName @0 :Bool $Cxx.name("goodFieldName");
|
||||||
|
bar @1 :Int8;
|
||||||
|
}
|
||||||
|
|
||||||
|
enum BadlyNamedEnum $Cxx.name("RenamedEnum") {
|
||||||
|
foo @0;
|
||||||
|
bar @1;
|
||||||
|
baz @2 $Cxx.name("qux");
|
||||||
|
}
|
||||||
|
|
||||||
|
anotherBadFieldName @2 :BadlyNamedEnum $Cxx.name("anotherGoodFieldName");
|
||||||
|
|
||||||
|
struct NestedStruct $Cxx.name("RenamedNestedStruct") {
|
||||||
|
badNestedFieldName @0 :Bool $Cxx.name("goodNestedFieldName");
|
||||||
|
anotherBadNestedFieldName @1 :NestedStruct $Cxx.name("anotherGoodNestedFieldName");
|
||||||
|
|
||||||
|
enum DeeplyNestedEnum $Cxx.name("RenamedDeeplyNestedEnum") {
|
||||||
|
quux @0;
|
||||||
|
corge @1;
|
||||||
|
grault @2 $Cxx.name("garply");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
badlyNamedUnion :union $Cxx.name("renamedUnion") {
|
||||||
|
badlyNamedGroup :group $Cxx.name("renamedGroup") {
|
||||||
|
foo @3 :Void;
|
||||||
|
bar @4 :Void;
|
||||||
|
}
|
||||||
|
baz @5 :NestedStruct $Cxx.name("qux");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
"""Generate a new reference file."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from capnp_stub_generator.cli import main as stub_generator_main
|
||||||
|
|
||||||
|
here = os.path.dirname(__file__)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Generate a new reference from the dummy schema."""
|
||||||
|
stub_generator_main(
|
||||||
|
[
|
||||||
|
"-p",
|
||||||
|
os.path.join(here, "dummy.capnp"),
|
||||||
|
"-c",
|
||||||
|
os.path.join(here, "dummy_capnp.py"),
|
||||||
|
os.path.join(here, "dummy_capnp.pyi"),
|
||||||
|
os.path.join(here, "ref_dummy_capnp.pyi_nocheck"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
os.rename(os.path.join(here, "dummy_capnp.pyi"), os.path.join(here, "ref_dummy_capnp.pyi_nocheck"))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
@ -0,0 +1,28 @@
|
|||||||
|
"""Tests the capnproto stub generator."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from capnp_stub_generator.cli import main
|
||||||
|
|
||||||
|
here = os.path.dirname(__file__)
|
||||||
|
|
||||||
|
|
||||||
|
def test_generation():
|
||||||
|
"""Compare the generated output to a reference file."""
|
||||||
|
main(
|
||||||
|
[
|
||||||
|
"-p",
|
||||||
|
os.path.join(here, "dummy.capnp"),
|
||||||
|
"-c",
|
||||||
|
os.path.join(here, "dummy_capnp.pyi"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(os.path.join(here, "dummy_capnp.pyi"), encoding="utf8") as test_file:
|
||||||
|
test_data = test_file.readlines()
|
||||||
|
|
||||||
|
with open(os.path.join(here, "ref_dummy_capnp.pyi_nocheck"), encoding="utf8") as ref_file:
|
||||||
|
ref_data = ref_file.readlines()
|
||||||
|
|
||||||
|
assert test_data == ref_data
|
Loading…
Reference in New Issue