pax_global_header00006660000000000000000000000064137612230070014513gustar00rootroot0000000000000052 comment=874291a64aba50bf90bd414e87d1aee3e161a82b valabind-1.8.0/000077500000000000000000000000001376122300700133015ustar00rootroot00000000000000valabind-1.8.0/.gitignore000066400000000000000000000000171376122300700152670ustar00rootroot00000000000000build valabind valabind-1.8.0/.travis.yml000066400000000000000000000004161376122300700154130ustar00rootroot00000000000000os: linux language: c compiler: gcc before_install: - wget https://download.gnome.org/sources/vala/0.39/vala-0.39.5.tar.xz - tar xJvf vala-0.39.5.tar.xz - cd vala-0.39.5 - ./configure --prefix=/usr - make -j12 - sudo make install - cd .. script: - make valabind-1.8.0/AUTHORS000066400000000000000000000002551376122300700143530ustar00rootroot00000000000000Credits of Valabind =================== Author ------ Name: pancake Main developer and author of valabind. Contributors: ------------- See THANKS valabind-1.8.0/LICENSE000066400000000000000000001045131376122300700143120ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . valabind-1.8.0/Makefile000066400000000000000000000074341376122300700147510ustar00rootroot00000000000000_VERSION=? -include config.mk PWD:=$(shell pwd) #GIT_TIP=$(shell [ -d .git ] && git log HEAD^..HEAD 2>/dev/null |head -n1|cut -d ' ' -f2) GIT_TIP=$(shell git describe --tags) DESTDIR?= PREFIX?=/usr MANDIR?=$(PREFIX)/share/man CC?=gcc VALAFLAGS:=$(foreach w,$(CPPFLAGS) $(CFLAGS) $(LDFLAGS),-X $(w)) VALAC?=valac -g --cc="$(CC)" $(VALAFLAGS) RTLIBS=gobject-2.0 glib-2.0 VALAPKG:=lib$(shell ./getvv) BUILD?=build BIN=valabind SRC=config.vala main.vala valabindwriter.vala nodeffiwriter.vala utils.vala SRC+=girwriter.vala swigwriter.vala cxxwriter.vala ctypeswriter.vala dlangwriter.vala gowriter.vala SRC+=vlangwriter.vala VAPIS:=$(SRC:%.vala=$(BUILD)/%.vapi) CSRC:=$(SRC:%.vala=$(BUILD)/%.c) VALA_FILTER=$(filter %.vala,$?) TEMPS=$(addprefix --use-fast-vapi=,$(filter-out $(VALA_FILTER:%.vala=$(BUILD)/%.vapi),$(VAPIS))) TEMPS+=$(VALA_FILTER) $(patsubst %.vala,$(BUILD)/%.c,$(filter-out $?,$^)) ifneq ($(GIT_TIP),) SGIT_TIP=$(shell echo ${GIT_TIP} | sed -e s,${_VERSION},,) else SGIT_TIP=$(GIT_TIP) endif ifneq ($(SGIT_TIP),) VERSION=$(_VERSION)-$(SGIT_TIP) else VERSION=$(_VERSION) endif INSTALL_MAN?=install -m0644 INSTALL_PROGRAM?=install -m0755 ifneq ($(W32),) VALAFLAGS+=-D W32=1 PREFIX=/opt/gtk3w32/ PKG_CONFIG_PATH=$(W32_PREFIX)/lib/pkgconfig CFLAGS=-I$(PREFIX)/include/glib CFLAGS+=-I$(PREFIX)/include/glib LDFLAGS=-L$(PREFIX)/lib CC=i686-pc-mingw32-gcc all: $(BIN).exe else all: $(BIN) endif VALA_VERSION=$(shell ./getvv) VALA_PKGLIBDIR=$(shell pkg-config --variable=pkglibdir lib${VALA_VERSION}) ifeq ($(VALA_PKGLIBDIR),) VALA_LIBDIR=$(shell pkg-config --variable=libdir lib${VALA_VERSION}) VALA_PKGLIBDIR=$(VALA_LIBDIR)/$(shell ./getvv) endif VALA_PRIVATE_CODEGEN=--pkg $(VALAPKG) VALA_PRIVATE_CODEGEN+=--vapidir=$(PWD)/private --pkg codegen -X -I$(PWD)/private VALA_PRIVATE_CODEGEN+=--vapidir=${R2PM_PREFIX}/share/vala/vapi/ VALA_PRIVATE_CODEGEN+=-X -L$(VALA_PKGLIBDIR) -X -lvalaccodegen ifneq ($(shell uname),Darwin) VALA_PRIVATE_CODEGEN+=-X -Wl,-rpath=$(VALA_PKGLIBDIR) endif w32: $(MAKE) W32=1 .PRECIOUS: $(BUILD)/%.c $(BUILD)/%.vapi $(BIN).exe: $(SRC) | $(VAPIS) @echo 'Compiling $(VALA_FILTER) -> $@' $(VALAC) --vapidir=. -D W32 -X "${CFLAGS}" -X "${LDFLAGS}" -o $@ --pkg $(VALAPKG) --save-temps ${TEMPS} windows.c --pkg windows @mv $(VALA_FILTER:%.vala=%.c) $(BUILD) $(BIN): $(SRC) | $(VAPIS) @echo 'Compiling $(VALA_FILTER) -> $@' $(VALAC) -o $@ --pkg posix $(VALA_PRIVATE_CODEGEN) --save-temps ${TEMPS} @mv $(VALA_FILTER:%.vala=%.c) $(BUILD) $(BUILD)/%.vapi: %.vala | $(BUILD) @echo 'Generating $< -> $@' @$(VALAC) $(VALAFLAGS) --fast-vapi=$@ $< @${MAKE} config.vala config.vala: Makefile @echo 'Generating $@' @echo 'const string version_string = "$(VERSION)";' > $@ $(BUILD): mkdir -p $@ install_dirs: mkdir -p $(DESTDIR)$(PREFIX)/bin mkdir -p $(DESTDIR)$(MANDIR)/man1 install: install_dirs $(INSTALL_MAN) $(BIN).1 $(DESTDIR)$(MANDIR)/man1 $(INSTALL_MAN) $(BIN)-cc.1 $(DESTDIR)$(MANDIR)/man1 $(INSTALL_PROGRAM) $(BIN) $(DESTDIR)$(PREFIX)/bin $(INSTALL_PROGRAM) $(BIN)-cc $(DESTDIR)$(PREFIX)/bin symstall: install_dirs chmod +x $(PWD)/$(BIN)-cc ln -fs $(PWD)/$(BIN).1 $(DESTDIR)$(MANDIR)/man1 ln -fs $(PWD)/$(BIN)-cc.1 $(DESTDIR)$(MANDIR)/man1 ln -fs $(PWD)/$(BIN) $(DESTDIR)$(PREFIX)/bin ln -fs $(PWD)/$(BIN)-cc $(DESTDIR)$(PREFIX)/bin dist: $(MAKE) shot GIT_TIP= shot: rm -rf valabind-$(VERSION) git clone . valabind-$(VERSION) cd valabind-$(VERSION) && $(MAKE) config.vala rm -rf valabind-$(VERSION)/.git tar czvf valabind-$(VERSION).tar.gz valabind-$(VERSION) mrproper clean: rm -f config.vala rm -rf $(BUILD) $(BIN) rm -rf $(CSRC) deinstall: uninstall uninstall: -rm $(DESTDIR)$(MANDIR)/man1/$(BIN).1 -rm $(DESTDIR)$(MANDIR)/man1/$(BIN)-cc.1 -rm $(DESTDIR)$(PREFIX)/bin/$(BIN) -rm $(DESTDIR)$(PREFIX)/bin/$(BIN)-cc .PHONY: all clean dist install symstall uninstall deinstall mrproper valabind-1.8.0/NOTES000066400000000000000000000032531376122300700141170ustar00rootroot00000000000000NOTES ===== Random notes taken from random .i files out there in the internets: https://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/swig/ /* ----------------------------------------------------------------------- The following struct members have to be read-only because otherwise strings assigned to then would never be freed, resulting in memory leaks. This prevents the swig warning "Warning(451): Setting const char * member may leak memory." */ %immutable svn_log_changed_path_t::copyfrom_path; %immutable svn_dirent_t::last_author; %immutable svn_error_t::message; %immutable svn_error_t::file; /* ### need to use freearg or somesuch to ensure the string is freed. ### watch out for 'return' anywhere in the binding code. */ #ifdef SWIGPYTHON %typemap(argout) (char *buffer, apr_size_t *len) { %append_output(PyString_FromStringAndSize($1, *$2)); free($1); } #endif #ifdef SWIGPERL %typemap(argout) (char *buffer, apr_size_t *len) { %append_output(sv_2mortal(newSVpvn($1, *$2))); free($1); } #endif #ifdef SWIGRUBY %typemap(argout) (char *buffer, apr_size_t *len) { %append_output(*$2 == 0 ? Qnil : rb_str_new($1, *$2)); free($1); } #endif %extend svn_commit_info_t { svn_commit_info_t(apr_pool_t *pool) { return svn_create_commit_info(pool); }; ~svn_commit_info_t() { }; svn_commit_info_t *dup(apr_pool_t *pool) { return svn_commit_info_dup(self, pool); }; } %init %{ #if defined(SVN_AVOID_CIRCULAR_LINKAGE_AT_ALL_COSTS_HACK) svn_swig_pl_bind_current_pool_fns (&svn_swig_pl_get_current_pool, &svn_swig_pl_set_current_pool); #endif %} %apply const char *NOT_NULL { const char *path }; valabind-1.8.0/README.md000066400000000000000000000013201376122300700145540ustar00rootroot00000000000000Valabind [![Build Status](https://travis-ci.org/radare/valabind.svg?branch=master)](https://travis-ci.org/radare/valabind) ======== Valabind is a tool to parse vala[1] or vapi files to transform them into swig[2] interface files, C++, NodeJS-ffi or GIR. With swig, you can create language bindings for any API written in vala or C with a vapi interface. It can also generate bindings for C++. Valabind mercurial repository is stored here: git clone https://github.com/radare/valabind This software is free, feel free to contribute, modify and report patches, ideas, bug reports, etc.. Contact ------- * e-mail: pancake@nopcode.org * twitter: @trufae [1] http://live.gnome.org/Vala [2] http://www.swig.org valabind-1.8.0/THANKS000066400000000000000000000012511376122300700142130ustar00rootroot00000000000000Thanks to: ---------- Name: Aitor P. Iturri Added -D flag Name: Anton Kochkov Support for Ruby Name: David Holm Fix `getvv` on MacOS X Lion Name: David Martínez Moreno Patches from Debian Name: Eduard Burtescu Implement Node-ffi bindings and some major refactorings Name: Ritesh Khadgaray Fix build for Vala 0.26 Name: Willi Ballenthin Work in progress Go bindings Name: dequis Refactor ctypeswriter Name: ditch Fix handling dependencies in ctypeswriter valabind-1.8.0/TODO.md000066400000000000000000000021511376122300700143670ustar00rootroot00000000000000valabind todo ============= beyond ------ [ ] Finish Go support [ ] Add support for Java using JNA [ ] Add support for unions (required for dynamic bindings) [ ] Unify all output modes --ctypes --swig --node ... those are should not be flags Use something like this: --mode=gir --mode=swig --mode=c++ --format=gir [ ] Add support to compile from C, do not generate (valabind-cc) [ ] Add support for destructors (class.get_destructor () .. [ ] Add support for varargs //%varargs(int mode = 0) open; int open(const char *path, int oflags, int mode = 0); [ ] Add support for contractual programming %contract Foo::bar(int x, int y) { require: x > 0; ensure: bar > 0; } [ ] Add support for exceptions (See %exception) [ ] Add support for properties [ ] Add support for %namespace foo { ... } [ ] Use templates in Swig? %template(intList) List; typedef int Integer void foo (vector *x); valabind-1.8.0/config.mk.acr000066400000000000000000000000761376122300700156460ustar00rootroot00000000000000PREFIX?=@PREFIX@ CC?=@CC@ CFLAGS+=@CFLAGS@ _VERSION=@VERSION@ valabind-1.8.0/config.vala000066400000000000000000000000551376122300700154130ustar00rootroot00000000000000const string version_string = "1.7.1-1.7.2"; valabind-1.8.0/configure000077500000000000000000000256031376122300700152160ustar00rootroot00000000000000#!/bin/sh # This script was automatically generated by ACR v1.9.4 # @author: pancake # @url: http://www.nopcode.org # @repo: git clone https://github.com/radare/acr [ -z "${AWK}" ] && AWK=awk do_remove() { if [ "${ACR_RMFILES}" ]; then printf "cleaning temporally files... " rm -f ${ACR_RMFILES} echo "done" fi } control_c() { printf "\n\n^C control-c : script execution interrupted.\n" do_remove exit 1 } trap control_c 2 [ -z "${VALA}" ] && VALA="vala" [ -z "${VALAC}" ] && VALAC="valac" split_host() { S="$" while : ; do ENVWORDS="${ENVWORDS} $1_CPU $1_OS" STR=`eval "echo ${S}$1"` SPLIT_CPU="`echo "$STR" | cut -d - -f 1`" SPLIT_OS="`echo "$STR" | $AWK -F - '{ if ($2=="unknown"){ if (NF<3) { print $2; } else { print $3; } } else { if ($2=="linux") { print $2; } else if (NF<3) { print $2; } else { print $3; } } }'`" eval "$1_CPU=\"$SPLIT_CPU\"" eval "$1_OS=\"$SPLIT_OS\"" shift [ -z "$1" ] && break done } QUIET=0 be_quiet() { QUIET=1 } VPATH=`dirname ${0}` if [ "${VPATH}" = "." ]; then WODIS=current else if [ "${VPATH}" = "${PWD}" ]; then VPATH=. WODIS=current else WODIS=crosspath CURDIR=$PWD cd $VPATH VPATH="${PWD}/" cd $CURDIR fi fi guess_os() { if [ -e "${VPATH}/config.guess" ]; then sh ${VPATH}/config.guess return fi CPU="`uname -m|sed -e 's, ,,g'|cut -d - -f 1`" OS="`uname -s|tr A-Z a-z`" uname -r | grep -qE "(Microsoft|WSL)" 2>/dev/null && OS="wsl" GNU="`uname --help 2>&1 | grep gnu`" [ "${GNU}" ] && OS="${OS}-gnu" [ "${CPU}" = ppc ] && CPU="powerpc" echo "${CPU}-unknown-${OS}" } SEARCHPATH="/usr /usr/local /usr/pkg /sw" : ${PREFIX:=/usr/local} CROSSBUILD=0 BUILD=`guess_os` HOST="${BUILD}" TARGET="${HOST}" SYSCONFDIR="" create_environ() { : ${EPREFIX:="${PREFIX}"} : ${SPREFIX:="${PREFIX}"} : ${BINDIR:="${SPREFIX}/bin"} : ${SBINDIR:="${PREFIX}/sbin"} : ${SYSCONFDIR:="${SPREFIX}/etc"} : ${LIBDIR:="${SPREFIX}/lib"} : ${LIBEXECDIR:="${SPREFIX}/libexec"} : ${INCLUDEDIR:="${SPREFIX}/include"} : ${DATADIR:="${SPREFIX}/share"} : ${INFODIR:="${DATADIR}/info"} : ${MANDIR:="${DATADIR}/man"} : ${DOCDIR:="${DATADIR}/doc/valabind"} : ${LOCALSTATEDIR:="${SPREFIX}/var"} for A in `echo ${PATH} | sed -e 's,:, ,g'` ; do [ -e "$A"/ginstall ] && : ${INSTALL:="$A"/ginstall} && break [ -e "$A"/install ] && : ${INSTALL:="$A"/install} && break done : ${INSTALL_DIR:=${INSTALL} -d} : ${INSTALL_DATA:=${INSTALL} -m 644} : ${INSTALL_SCRIPT:=${INSTALL} -m 755} : ${INSTALL_PROGRAM:=${INSTALL} -m 755} : ${INSTALL_PROGRAM_STRIP:=${INSTALL} -m 755 -s} : ${INSTALL_MAN:=${INSTALL} -m 444} : ${INSTALL_LIB:=${INSTALL} -m 755 -c} PKGNAME='valabind' ; VERSION='1.8.0' ; VERSION_MAJOR=1; VERSION_MINOR=8; VERSION_PATCH=0; VERSION_NUMBER=10800; CONTACT_MAIL="pancake@nopcode.org" ; CONTACT_NAME="pancake" ; CONTACT="pancake " ; } show_usage() { cat < if you have libraries in a nonstandard directory CPPFLAGS C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor VALAC Vala compiler to be used. " printf " Report bugs to: pancake " echo "" exit 0 } take_environ() { : ${SH:=/bin/sh} : ${CPP:=cpp} : ${CC:=gcc} : ${VALAC:=valac} : ${PREFIX:=/usr/local/} } ochof() { [ "$QUIET" = 1 ] && return printf "$*" } ocho() { [ "$QUIET" = 1 ] && return echo "$*" } show_version() { if [ "$QUIET" = 1 ]; then echo "1.8.0" exit 0 fi echo "valabind-1.8.0 configuration script done with acr v1.9.4. The 'Free Software Foundation' message is only for autodetection. Originally written by pancake ." exit 0 } parse_options() { flag=`echo $1| cut -d = -f 1` value=`echo $1| $AWK 'BEGIN{FS="=";}{print $2}'` flag2=`echo $flag|cut -f2- -d -| sed -e 's,-,_,g' -e 's,^_,,g'|tr '[a-z]' '[A-Z]'` if [ "${TARGET_OS}" = "darwin" ]; then LIBPATH=-Wl,-install_name, else LIBPATH=-Wl,-R fi case $flag in -h|--help|--hel|--h|--he|-help) show_usage ; ;; -qV|-quiet-version|--quiet-version) be_quiet show_version ; ;; -q|-quiet|--quiet) be_quiet ; ;; -V|-version|--version) show_version ; ;; -r|--r|--report) echo "PKGNAME: valabind" echo "VERSION: 1.8.0" echo "LANGS: c vala" echo "FLAGS: --with-vala=vala --with-valac=valac" exit 0 ;; --cache-file) # ignored: acr have no cache ;; --build) BUILD="$value"; split_host BUILD ; ;; --host) CROSSBUILD=1 # XXX HOST="$value"; split_host HOST ; ;; --target) TARGET="$value"; split_host TARGET ; ;; --prefix) PREFIX="$value"; ;; --exec-prefix) EPREFIX="$value"; ;; --sandbox|--sprefix) SPREFIX="$value"; ;; --bindir) BINDIR="$value"; ;; --sbindir) SBINDIR="$value"; ;; --libexecdir) LIBEXECDIR="$value"; ;; --docdir) DOCDIR="$value"; ;; --datadir) DATADIR="$value"; ;; --sysconfdir) SYSCONFDIR="$value"; ;; --sharedstatedir) SHAREDSTATEDIR="$value"; ;; --localstatedir) LOCALSTATEDIR="$value"; ;; --libdir) LIBDIR="$value"; ;; --libpath) LDFLAGS="${LDFLAGS} ${LIBPATH}$value"; ;; --includedir) INCLUDEDIR="$value"; CFLAGS="${CFLAGS} -I$value"; ;; --infodir) INFODIR="$value"; ;; --mandir) MANDIR="$value"; ;; --with-vala) if [ -z "${value}" ]; then VALA="vala"; else VALA="${value}" ; fi ;; --with-valac) if [ -z "${value}" ]; then VALAC="valac"; else VALAC="${value}" ; fi ;; *) if [ "$value" ]; then eval "`echo $flag2=$value`" ; else echo ; echo "WARNING: Unknown flag '$flag'." >&2 ; echo ; fi ;; esac } # MAIN # take_environ split_host BUILD HOST TARGET [ -z "$ACRHOOK" ] && ACRHOOK=./configure.hook [ -e "$ACRHOOK" ] && . ${ACRHOOK} while : ; do [ -z "$1" ] && break parse_options "$1" shift done ENVWORDS="MANDIR INFODIR LIBDIR INCLUDEDIR LOCALSTATEDIR SYSCONFDIR DATADIR DOCDIR LIBEXECDIR SBINDIR BINDIR EPREFIX PREFIX SPREFIX TARGET HOST BUILD INSTALL INSTALL_LIB INSTALL_MAN INSTALL_PROGRAM INSTALL_PROGRAM_STRIP INSTALL_DIR INSTALL_SCRIPT INSTALL_DATA HOST_OS HOST_CPU BUILD_OS BUILD_CPU TARGET_OS TARGET_CPU VERSION VERSION_MAJOR VERSION_MINOR VERSION_PATCH VERSION_NUMBER PKGNAME VPATH CONTACT CONTACT_NAME CONTACT_MAIL CC CFLAGS CPPFLAGS LDFLAGS HAVE_LANG_C VALA VALAC" create_environ ocho "checking build system type... ${BUILD}" ocho "checking host system type... ${HOST}" ocho "checking target system type... ${TARGET}" [ "${CROSSBUILD}" = 1 ] && echo "using crosscompilation mode." #split_host BUILD HOST TARGET [ -n "${prefix}" ] && PREFIX="${prefix}" ocho "checking for working directories... ${WODIS}" ocho "using prefix '${PREFIX}'" ACR_RMFILES=" test.c a.out a.exe .test.vala .test" COMPILER=CC printf "checking for c compiler... " HAVE_LANG_C=1 if [ "${CROSSBUILD}" = 1 ]; then (command -v ${HOST}-${CC} >/dev/null 2>&1) if [ $? = 0 ]; then CC="${HOST}-${CC}"; fi fi echo "int main(int argc, char **argv){return 0;}" > test.c (exec ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} test.c >/dev/null 2>&1) if [ $? = 0 ]; then echo ${CC}; else echo no ; HAVE_LANG_C=0 do_remove echo "ERROR: ${CC} cannot create executables" >&2 ; exit 1 ; fi printf "checking vala compiler... " HAVE_LANG_VALA=1 HAVE_VALA=1 HAVE_VALAC=1 VALA_VERSION="" echo "void main(){}" > .test.vala ${VALAC} .test.vala 2>&1 >/dev/null if [ $? = 0 ]; then echo ${VALAC}; VALA_VERSION=$(${VALAC} --version | cut -d " " -f 2 | cut -d . -f 1,2); printf "checking vala... "; ${VALA} .test.vala 2>&1 >/dev/null if [ $? = 0 ]; then echo ${VALA}; else echo no ; HAVE_LANG_VALA=0 ; HAVE_VALA=0 fi else echo no ; HAVE_LANG_VALA=0 ; HAVE_VALAC=0 fi if [ "${HAVE_LANG_VALA}" = 0 ]; then echo "ERROR: ${VALAC} cannot create C code"; exit 1 fi rm -f .test.vala SEDFLAGS=" -e '" COUNT=0 for A in ${ENVWORDS} ; do [ "${A}" = VPATH ] && continue [ "${A}" = srcdir ] && continue eval "VAR=\$${A}" VAR="`echo ${VAR} | sed -e 's/\,/\\\,/g'`" [ $COUNT = 10 ] && COUNT=0 && SEDFLAGS="${SEDFLAGS}' -e '" COUNT=$(($COUNT+1)) SEDFLAGS="${SEDFLAGS}s,@${A}@,${VAR},g;" done SEDFLAGS="${SEDFLAGS}'" for A in ./config.mk ; do # SUBDIRS if [ -f "${VPATH}/${A}.acr" ]; then SD_TARGET=${A} else if [ -d "${VPATH}/${A}" ]; then SD_TARGET=${A}/Makefile mkdir -p ${A} else echo "ERROR: Cannot find ${VPATH}/${A}.acr" >&2 exit 1 fi fi ocho "creating ${SD_TARGET}" mkdir -p $(echo ${A} | sed -e "s,/`basename ${A}`$,,g") cat ${VPATH}/${SD_TARGET}.acr | \ eval sed -e "s,@VPATH@,${VPATH}/${A},g" ${SEDFLAGS} > ${SD_TARGET}.tmp for A in ${ENVWORDS}; do VALUE=`eval echo "$"${A}` if [ "$VALUE" = 0 ]; then ## FALSE MARK="##${A}##" if [ -n "`grep \"${MARK}\" ${SD_TARGET}.tmp`" ]; then mv ${SD_TARGET}.tmp ${SD_TARGET}.tmp2 cat ${SD_TARGET}.tmp2 | MARK=$MARK $AWK 'BEGIN{a=0;}{if($1==ENVIRON["MARK"]){if(a)a=0;else a=1}else{if(!a)print;}}' > ${SD_TARGET}.tmp fi fi done mv ${SD_TARGET}.tmp ${SD_TARGET} && rm -f ${SD_TARGET}.tmp2 if [ ! $? = 0 ]; then echo Cannot write target file ; control_c ; fi done do_remove valabind-1.8.0/configure.acr000066400000000000000000000001601376122300700157460ustar00rootroot00000000000000PKGNAME valabind VERSION 1.8.0 CONTACT pancake ; pancake@nopcode.org LANG_C! LANG_VALA! SUBDIRS ./config.mk ; valabind-1.8.0/ctypeswriter.vala000066400000000000000000000443641376122300700167250ustar00rootroot00000000000000/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ /* Copyright GPLv3 - 2009-2019 - pancake */ using Vala; private class CtypeCompiler { public GLib.SList classes; public CtypeClass cur; private bool sorted = false; public string to_string () { var str = ""; if (!this.sorted) this.sort (); foreach (var c in this.classes) str += c.to_string (); return str; } public CtypeCompiler() { this.cur = null; } public bool contains (string c) { foreach (var a in this.classes) if (a.name == c) return true; return false; } public void sort () { uint count, count2 = 0; var n = new GLib.SList(); do { count = classes.length (); foreach (var c in classes) { if (c.is_satisfied (this)) { n.append (c); classes.remove (c); } else { warning ("UNSATISFIED "+c.name); } } count2 = classes.length (); if (count2 > 0 && count == count2) { // detect infinite loop error ("Cannot compile, infinite loop dependency detected\n"); } } while (count2 > 0); /* refill */ foreach (var c in classes) { if (c.is_satisfied (this)) { n.prepend (c); classes.remove (c); } } this.classes = n.copy(); this.sorted = true; } public void add_class (string name, string text) { var cc = new CtypeClass (name); this.classes.append (cc); this.cur = cc; this.cur.append (text); this.sorted = false; } } private class CtypeClass { public string name; public string text; public GLib.SList deps; public bool is_satisfied (CtypeCompiler c) { foreach (var d in deps) { if (d == this.name) { stderr.printf ("==> "+d+"\n"); // break; } stderr.printf ("--> "+d+"\n"); if (!c.contains (d)) { return false; } } stderr.printf (" *** Yep. "+name+" is satisfied\n"); return true; } public CtypeClass(string? name) { this.deps = new SList(); this.name = name; this.text = ""; } public bool contains(SList a, string b) { if (b == this.name) { error ("Classes with self dependencies are not supported"); // return true; } foreach (var i in a) { if (i == b) return true; } return false; } public void add_dependency (string d) { if (!this.contains (deps, d)) deps.append (d); } /* public bool depends_on(string d) { foreach (var s in deps) if (s == d) return true; return false; } */ public string to_string() { return this.text; } public void append(string s) { this.text += s; } } public class CtypesWriter : ValabindWriter { public GLib.List includefiles = new GLib.List (); CtypeCompiler ctc = new CtypeCompiler (); string ?ns_pfx; string delegatestr = ""; public CtypesWriter () { } public override string get_filename (string base_name) { return base_name + ".py"; } // FIXME duplicate from NodeFFIWriter void add_includes (Symbol s) { foreach (string i in Vala.get_ccode_header_filenames (s).split (",")) { bool include = true; foreach (string j in includefiles) { if (i == j) { include = false; break; } } if (include) { includefiles.prepend (i); } } } // FIXME duplicate from NodeFFIWriter string sep (string str, string separator) { if (str.length != 0) { char last = str[str.length-1]; if (last != '(' && last != '[' && last != '{') { return str + separator; } } return str; } string get_alias (string oname) { string name = oname; switch (oname) { case "break": case "import": case "from": case "del": name = "_"+oname; break; case "continue": name = "cont"; break; } if (name != oname) { warning ("Method %s renamed to %s".printf (oname, name)); } return name; } string type_name (DataType type, bool retType=false, bool ignoreRef=false) { if (type == null) { warning ("Cannot resolve type"); return "__UNRESOLVED_TYPE_OH_PLEASE_KILL_ME__"; } // HACK is this required? if (type is EnumValueType) return "c_long"; // HACK needs proper generic support if (type is GenericType) return "c_void_p"; //return type.to_qualified_string (); if (type is PointerType) { var tn = type_name ((type as PointerType).base_type, retType, true); if (tn == "void") return "c_void_p"; return "POINTER("+tn+")"; } if (type is ArrayType) { ArrayType array = type as ArrayType; string element = type_name (array.element_type, retType); int len = array_length(array); if (len < 0) { return element; //+"*"; // FIXME should this be element+"[]"? } return "'"+element+"', * %d".printf (len); // FIXME will this work? } if (!ignoreRef && (type is ReferenceType)) { string unref_type = type_name (type, retType, true); // HACK just check for the string class instead (how?) if (unref_type == "char*" || unref_type == "const char*") { return unref_type; } // FIXME should it be & under C++? return unref_type; //+"_p"; //+"*"; } string generic = ""; foreach (DataType t in type.get_type_arguments ()) generic = sep (generic, ", ") + type_name (t); string _type = type.to_string (); // HACK find a better way to remove generic type args _type = _type.split ("<", 2)[0]; _type = _type.replace (ns_pfx, "").replace (".", ""); _type = _type.replace ("?",""); _type = _type.replace ("unsigned ", "u"); switch (_type) { case "bool": case "gboolean": return "c_bool"; case "gconstpointer": case "gpointer": return "c_void_p"; case "char": case "gchar": return "c_char"; case "gint": return "c_int"; case "uint": case "guint": return "c_uint"; case "glong": return "c_long"; case "ut8": case "uint8": case "guint8": return "c_ubyte"; case "guint16": case "uint16": return "c_ushort"; case "gint16": case "int16": case "short": return "c_short"; case "int": case "st32": case "int32": case "gint32": return "c_int"; case "ut32": case "uint32": case "guint32": return "c_uint"; case "st64": case "int64": case "gint64": return "c_longlong"; case "ut64": case "uint64": case "guint64": // HACK uint64_t doesn't work here because radare2 doesn't use the right type return "c_ulonglong"; case "gdouble": return "c_double"; case "gfloat": return "c_float"; case "string": return "c_char_p"; //case "const gchar*": // return "const char*"; // HACK needs proper generic support case "RList": return "RList"; case "SdbList": return "SdbList"; } return _type; } public override void visit_constant (Constant c) { warning ("Constants not yet supported on ctypes ("+c.name+")"); //var cname = Vala.get_ccode_name (c); //classes += c.name+" = "+cname+";\n"; } public override void visit_enum (Vala.Enum e) { add_includes (e); // TODO: copy from node } public override void visit_struct (Struct s) { string name = s.get_full_name ().replace (ns_pfx, "").replace (".", ""); visit_struct_or_class (s, name, s.get_fields (), s.get_methods (), null); } public override void visit_class (Class c) { string name = c.get_full_name ().replace (ns_pfx, "").replace (".", ""); visit_struct_or_class (c, name, c.get_fields (), c.get_methods (), c.get_delegates ()); /* walk nested structs and classes */ foreach (Struct s in c.get_structs ()) { s.accept (this); } foreach (Class k in c.get_classes ()) { k.accept (this); } /* TODO: add support for freefun in destructor string? freefun = null; if (Vala.is_reference_counting (c)) freefun = Vala.get_ccode_unref_function (c); else freefun = Vala.get_ccode_free_function (c); if (freefun == "") freefun = null; var methods = c.get_methods (); if (freefun != null || methods.size > 0) { ... */ } private string get_constructor_args(Vala.List methods) { foreach (Method m in methods) { if (m is CreationMethod) { var str = ""; add_includes (m); foreach (var foo in m.get_parameters ()) { str += ", "+get_alias (foo.name); } return str; } } return ""; } string wrappers; int n = 0; private void visit_struct_or_class (Symbol s, string name, Vala.List fields, Vala.List methods, Vala.List? delegates) { //string cname = Vala.get_ccode_name (s); add_includes (s); ctc.add_class (name, "class "+name+"(Structure): #"+n.to_string()+"\n"); stderr.printf ("--> "+name+" ("+n.to_string()+")\n"); n++; if (fields.size > 0) { ctc.cur.append ("\t_fields_ = [\n"); foreach (Field f in fields) f.accept (this); ctc.cur.append ("\t]\n"); } else { ctc.cur.append ("\t_fields_ = [\n\t]\n"); } if (methods.size > 0) { string call_args = get_constructor_args (methods); ctc.cur.append ("\tdef __init__(self"+call_args+"):\n"); ctc.cur.append ("\t\tStructure.__init__(self)\n"); // TODO: control how many methods and constructors there are // TODO: add support for more than one constructor /* constructors */ wrappers = ""; foreach (Method m in methods) if (m is CreationMethod) visit_method (m); /* helper function */ if (name == "RList") { ctc.cur.append ( "\tdef to_list(self,type):\n"+ "\t\treturn rlist2array(self,type)\n"); } if (name == "SdbList") { ctc.cur.append ( "\tdef to_list(self,type):\n"+ "\t\treturn sdblist2array(self,type)\n"); } /* delegates */ if (delegates != null) foreach (Delegate d in delegates) visit_delegate (d); ctc.cur.append ("\n\t_o = AddressHolder()\n\n"); /* methods */ foreach (Method m in methods) if (!(m is CreationMethod)) visit_method (m); ctc.cur.append (wrappers); ctc.cur.append ("\n"); } } public override void visit_field (Field f) { if (f.is_private_symbol ()) return; // HACK don't output fields with C++ keywords as names. if (f.name == "class") return; string field = ""; DataType type = f.variable_type; var stype = type.to_string (); if (type is ArrayType) { ArrayType array = type as ArrayType; string element = type_name (array.element_type); warning ("Arrays not yet supported in ctypes bindings"); int len = array_length(array); if (len < 0) { field = element + "* " + f.name; // FIXME should this be element+"[]"? } field = "'%s', %s * %d".printf (f.name, element, len); // warning ("Field is array " + element); // ctc.cur.add_dependency ("RRegItem"); // if dependency type is not a c one if (element[0] != 'c' && element[1] != '_') { ctc.cur.add_dependency (element); } else { warning ("NODEP " + element); } } else { /* HACK to support generics. this is r2 specific */ if (stype.index_of ("RListIter") != -1) { stype = "c_void_p"; // XXX RListIter*"; } else if (stype.index_of ("RList") != -1) { stype = "c_void_p"; // XXX "RList*"; } else if (stype.index_of ("SdbListIter") != -1) { stype = "c_void_p"; // XXX SdbListIter*"; } else if (stype.index_of ("SdbList") != -1) { stype = "c_void_p"; // XXX "SdbList*"; } else stype = type_name (type); field = "\"%s\", %s".printf (f.name, stype); } ctc.cur.append ("\t\t(" + field + "),\n"); if (stype[0].isupper () && !stype.has_prefix ("POINTER") && stype.index_of (".") == -1) { //stderr.printf ("ADD DEP : "+field+" "+stype+"\n"); ctc.cur.add_dependency (stype); } } public override void visit_delegate (Delegate d) { string cname = Vala.get_ccode_name (d); string args = ""; foreach (var p in d.get_parameters ()) { DataType? bar = p.variable_type; string? arg_type = type_name (bar); args += ", "+arg_type; } var cn = d.parent_symbol.get_full_name ().replace (ns_pfx, "").replace (".", ""); this.delegatestr += cname + " = CFUNCTYPE ("+cn+args+")\n"; } public override void visit_method (Method m) { if (m.is_private_symbol ()) return; add_includes (m); string cname = Vala.get_ccode_name (m); //string alias = get_alias (m.name); bool is_static = (m.binding & MemberBinding.STATIC) != 0; bool is_constructor = (m is CreationMethod); //var parent = m.parent_symbol; //bool parent_is_class = parent is Class || parent is Struct; // TODO: Implement contractual support // m.get_preconditions (); // m.get_postconditions (); string ret = type_name (m.return_type, true); string pyc_args = ""; string def_args = ""; string call_args = ""; string clears = ""; foreach (var foo in m.get_parameters ()) { //DataType? bar = foo.parameter_type; DataType? bar = foo.variable_type; if (bar == null) { warning ("Unknown datatype "+foo.name+"\n"); continue; } string arg_name = get_alias (foo.name); string? arg_type = type_name (bar); /* TODO: move to type_name */ if (foo.direction != ParameterDirection.IN) { var var_name = ""; if (foo.direction == ParameterDirection.OUT) var_name = "OUTPUT"; else if (foo.direction == ParameterDirection.REF) var_name = "INOUT"; if (arg_type.index_of ("*") == -1) arg_type = "POINTER("+arg_type+")"; //applys += "\t%%apply %s %s { %s %s };\n".printf (arg_type, var_name, arg_type, arg_name); clears += "\t%%clear %s %s;\n".printf (arg_type, arg_name); } call_args = sep (call_args, ", ") + arg_name; def_args = sep (def_args, ", ") + arg_type + " " + arg_name; pyc_args = sep (pyc_args, ", ") + arg_type; } if (is_constructor) { var text = "\t\t%s = lib.%s\n".printf (cname, cname); text += "\t\t%s.restype = c_void_p\n".printf (cname); text += "\t\tself._o = %s (%s)\n".printf (cname, call_args); // TODO: support constructor arguments #if 0 var classname = parent.get_full_name ().replace (ns_pfx, "").replace (".", ""); text += "\t%s (%s) {\n".printf (classname, def_args); if (context.is_defined ("GOBJECT")) text += "\t\tg_type_init ();\n"; text += "\t\treturn %s (%s);\n\t}\n".printf (cname, call_args); #endif text += clears; ctc.cur.append (text); } else { if (!is_static) { if (pyc_args == "") pyc_args = "c_void_p"; else pyc_args = "c_void_p, " + pyc_args; } if (ret == "RList") { wrappers +="\tdef %s(self%s):\n".printf (m.name, call_args); m.name = "_"+m.name; string gen = ""; var type = m.return_type; foreach (DataType t in type.get_type_arguments ()) gen = sep (gen, ", ") + type_name (t); ret = "RList<"+gen+">"; wrappers +="\t\treturn rlist2array(self.%s(%s),%s)\n".printf ( m.name, call_args, gen); } if (ret == "SdbList") { wrappers +="\tdef %s(self%s):\n".printf (m.name, call_args); m.name = "_"+m.name; string gen = ""; var type = m.return_type; foreach (DataType t in type.get_type_arguments ()) gen = sep (gen, ", ") + type_name (t); ret = "SdbList<"+gen+">"; wrappers +="\t\treturn sdblist2array(self.%s(%s),%s)\n".printf ( m.name, call_args, gen); } ret = (ret=="void")? "None": "'"+ret+"'"; ctc.cur.append ( "\t%s, %s = register('%s','%s',%s)\n".printf ( get_alias(m.name), cname, cname, pyc_args, ret)); } } public override void visit_namespace (Namespace ns) { string name = ns.get_full_name (); bool use = use_namespace (ns); if (use) ns_pfx = name+ "."; if (ns_pfx != null) add_includes (ns); foreach (var n in ns.get_namespaces ()) n.accept (this); if (ns_pfx != null) { foreach (Constant c in ns.get_constants ()) c.accept (this); foreach (Vala.Enum e in ns.get_enums ()) e.accept (this); foreach (Struct s in ns.get_structs ()) s.accept (this); foreach (Class c in ns.get_classes ()) c.accept (this); } if (use) ns_pfx = null; } public override void write (string file) { var stream = FileStream.open (file, "w"); if (stream == null) error ("Cannot open %s for writing".printf (file)); stream.printf ( "# this file has been automatically generated by valabind\n"+ "import sys\n"+ "from ctypes import *\n"+ "from ctypes.util import find_library\n"+ "if sys.platform.startswith('win'):\n"+ " lib = WinDLL (find_library ('%s'))\n"+ "else:\n"+ " lib = CDLL (find_library ('%s'))\n", library, library); stream.puts ( "def rlist2array(x,y):\n"+ " it = x.iterator ()\n"+ " ret = []\n"+ " while True:\n"+ " data = it.get_data ()\n"+ " ds = cast (data, POINTER(y)).contents\n"+ " ret.append (ds)\n"+ " if it.n == None:\n"+ " break\n"+ " it = it.get_next ()\n"+ " return ret\n"+ "\n"+ "class AddressHolder(object):\n"+ " def __get__(self, obj, type_):\n"+ " if getattr(obj, '_address', None) is None:\n"+ " obj._address = addressof(obj)\n"+ " return obj._address\n"+ "\n"+ " def __set__(self, obj, value):\n"+ " obj._address = value\n"+ "\n"+ "class WrappedRMethod(object):\n"+ " def __init__(self, cname, args, ret):\n"+ " self.cname = cname\n"+ " self.args = args\n"+ " self.ret = ret\n"+ " self.args_set = False\n"+ " self.method = getattr(lib, cname)\n"+ "\n"+ " def __call__(self, *a):\n"+ " if not self.args_set:\n"+ " if self.args:\n"+ " self.method.argtypes = [eval(x.strip()) for x in self.args.split(',')]\n"+ " self.method.restype = eval(self.ret) if self.ret else None\n"+ " self.args_set = True\n"+ " return self.method(*a)\n"+ "\n"+ "class WrappedApiMethod(object):\n"+ " def __init__(self, method, ret2, last):\n"+ " self.method = method\n"+ " self._o = None\n"+ " self.ret2 = ret2\n"+ " self.last = last\n"+ "\n"+ " def __call__(self, *a):\n"+ " result = self.method(self._o, *a)\n"+ " if self.ret2:\n"+ " result = eval(self.ret2)(result)\n"+ " if self.last:\n"+ " return getattr(result, self.last)\n"+ " return result\n"+ "\n"+ " def __get__(self, obj, type_):\n"+ " self._o = obj._o\n"+ " return self\n"+ "\n"+ "def register(cname, args, ret):\n"+ " ret2 = last = None\n"+ " if ret:\n"+ " if ret[0]>='A' and ret[0]<='Z':\n"+ " x = ret.find('<')\n"+ " if x != -1:\n"+ " ret = ret[0:x]\n"+ " last = 'contents'\n"+ " ret = 'POINTER('+ret+')'\n"+ " else:\n"+ " last = 'value'\n"+ " ret2 = ret\n"+ " \n"+ " method = WrappedRMethod(cname, args, ret)\n"+ " wrapped_method = WrappedApiMethod(method, ret2, last)\n"+ " return wrapped_method, method\n\n"); context.root.accept (this); stream.printf (ctc.to_string ()); stream.puts (delegatestr); } } valabind-1.8.0/cxxwriter.vala000066400000000000000000000306021376122300700162060ustar00rootroot00000000000000/* Copyright 2009-2015 -- pancake // nopcode.org */ using Vala; public class CxxWriter : ValabindWriter { public GLib.List includefiles = new GLib.List (); public GLib.List methods; string classname = ""; string classcname; string externs = ""; string statics = ""; string extends = ""; string enums = ""; string vectors = ""; string nspace; public CxxWriter () { } public override string get_filename (string base_name) { return base_name+".cxx"; } string get_alias (string name) { string oname = name; switch (name) { case "not_eq": case "or_eq": case "xor_eq": case "and_eq": case "or": case "xor": case "not": case "and": case "break": case "while": case "print": case "new": case "for": case "if": case "case": case "delete": case "continue": return "_"+name; } if (name != oname) warning ("%s.%s method renamed to %s.%s".printf ( classname, oname, classname, name)); return name; } string get_ctype (string _type) { string type = _type; string? iter_type = null; if (type == "null") error ("Cannot resolve type"); if (type.has_prefix (nspace)) type = type.substring (nspace.length) + "*"; type = type.replace (".", ""); if (is_generic (type)) { int ptr = type.index_of ("<"); iter_type = (ptr==-1)?type:type[ptr:type.length]; iter_type = iter_type.replace ("<", ""); iter_type = iter_type.replace (">", ""); iter_type = iter_type.replace (nspace, ""); type = type.split ("<", 2)[0]; } type = type.replace ("?",""); switch (type) { case "const gchar*": return "const char*"; case "G": /* generic type :: TODO: review */ case "gconstpointer": case "gpointer": return "void*"; case "gsize": return "size_t"; case "gdouble": return "double"; case "gfloat": return "float"; case "ut8": case "uint8": case "guint8": return "unsigned char"; case "gchar**": return "char **"; case "gchar": return "char"; case "gchar*": case "string": return "char *"; // ??? case "gint": return "int"; case "glong": return "long"; case "st64": case "int64": case "gint64": return "long long"; case "ut64": case "uint64": case "guint64": return "unsigned long long"; /* XXX swig does not support unsigned char* */ case "uint8*": case "guint8*": return "unsigned char*"; case "guint16": case "uint16": return "unsigned short"; case "ut32": case "uint32": case "guint32": return "unsigned int"; case "bool": // no conversion needed case "gboolean": return "bool"; // XXX bool? case "RFList": if (iter_type != null) return "std::vector<"+iter_type+">"; break; case "RList": if (iter_type != null) return "std::vector<"+iter_type+">"; break; case "SdbList": if (iter_type != null) return "std::vector<"+iter_type+">"; break; } return type; } bool is_target_file (string path) { // FIXME implement the new method with use_namespace instead foreach (var file in source_files) if (file == path) return true; return false; } public override void visit_source_file (SourceFile source) { if (is_target_file (source.filename)) source.accept_children (this); } public void process_includes (Symbol s) { foreach (var foo in Vala.get_ccode_header_filenames (s).split (",")) { var include = true; foreach (var inc in includefiles) { if (inc == foo) { include = false; break; } } if (include) includefiles.prepend (foo); } } public void walk_field (Field f) { if (f.get_attribute_string ("CCode", "type") == null) { //warning ( // "Cannot resolve type for field '%s'".printf (f.get_cname ())); } else { warning ("Type for %s\n".printf ( Vala.get_ccode_name (f))); } //if (f.access == Accessibility.PRIVATE) // print ("---> field is private XXX\n"); //if (Vala.get_ccode_array_length (f)) // print ("---> array without length\n"); } HashTable defined_classes = new HashTable (str_hash, str_equal); public void walk_class (string pfx, Class c) { foreach (var k in c.get_classes ()) walk_class (c.name, k); classname = pfx+c.name; classcname = Vala.get_ccode_name (c); process_includes (c); bool has_constructor = false; foreach (var m in c.get_methods ()) if (m is CreationMethod) { has_constructor = true; break; } //bool is_static = (c.static_constructor != null); bool has_destructor = !c.is_compact; //stdout.printf ("class %s %s\n", // classname, c.is_compact.to_string () ); if (context.profile == Profile.GOBJECT) classname = "%s_%s".printf (nspace, classname); if (defined_classes.lookup (classname)) return; defined_classes.insert (classname, true); if (context.profile == Profile.GOBJECT) extends += "class %s_%s {\n".printf (modulename, classcname); else extends += "class %s_%s {\n".printf (modulename, classname); //if (has_destructor && has_constructor) extends += " %s *self;\n".printf (classname); extends += " public:\n"; foreach (var e in c.get_enums ()) walk_enum (e); foreach (var f in c.get_fields ()) walk_field (f); //c.static_destructor!=null?"true":"false"); if (has_destructor && has_constructor) { if (Vala.is_reference_counting (c)) { string? freefun = Vala.get_ccode_unref_function (c); if (freefun != null) extends += " ~%s_%s() {\n %s (self);\n }\n".printf (modulename, classname, freefun); } else { string? freefun = Vala.get_ccode_free_function (c); if (freefun != null) extends += " ~%s_%s() {\n %s (self);\n }\n".printf (modulename, classname, freefun); } } foreach (var m in c.get_methods ()) walk_method (m); extends += "};\n"; classname = ""; } public void walk_enum (Vala.Enum e) { #if not_required var enumname = classname + e.name; var tmp = "%{\n"; enums += "/* enum: %s (%s) */\n".printf ( e.name, Vala.get_ccode_name (e)); enums += "enum %s {\n".printf (enumname); tmp += "#define %s long int\n".printf (enumname); // XXX: Use cname? foreach (var v in e.get_values ()) { enums += " %s_%s,\n".printf (e.name, v.name); tmp += "#define %s_%s %s\n".printf (e.name, v.name, Vala.get_ccode_name (v)); } enums += "};\n"; enums += tmp + "%}\n"; #endif } inline bool is_generic(string type) { return (type.index_of ("<") != -1 && type.index_of (">") != -1); } public void walk_method (Method m) { bool first = true; string cname = Vala.get_ccode_name (m); string alias = get_alias (m.name); string ret; string def_args = ""; string call_args = ""; bool void_return; bool is_static = (m.binding & MemberBinding.STATIC) != 0; bool is_constructor = (m is CreationMethod); // TODO: Implement contractual support // m.get_preconditions (); // m.get_postconditions (); ret = m.return_type.to_string (); ret = get_ctype (is_generic (ret)? ret : Vala.get_ccode_name (m.return_type)); if (ret == null) error ("Cannot resolve return type for %s\n".printf (cname)); void_return = (ret == "void"); if (m.is_private_symbol ()) return; string applys = ""; string clears = ""; string pfx = ""; foreach (var foo in m.get_parameters ()) { string arg_name = foo.name; //DataType? bar = foo.parameter_type; DataType? bar = foo.variable_type; if (bar == null) continue; string? arg_type = get_ctype (Vala.get_ccode_name (bar)); if (first) { pfx = ""; first = false; } else pfx = ", "; /* TODO: move to get_ctype */ if (foo.direction != ParameterDirection.IN) { var var_name = ""; if (foo.direction == ParameterDirection.OUT) var_name = "OUTPUT"; else if (foo.direction == ParameterDirection.REF) var_name = "INOUT"; if (arg_type.index_of ("*") == -1) arg_type += "*"; applys += " %%apply %s %s { %s %s };\n".printf ( arg_type, var_name, arg_type, arg_name); //clears += " %%clear %s %s;\n".printf (arg_type, arg_name); } call_args += "%s%s".printf (pfx, arg_name); def_args += "%s%s %s".printf (pfx, arg_type, arg_name); } /* object oriented shit */ if (classname == "") { externs += "extern %s %s (%s);\n".printf (ret, cname, def_args); is_constructor = false; is_static = true; classname = nspace; } //else { if (nspace == classname) alias = nspace+"_"+alias; if (is_constructor) { externs += "extern %s* %s (%s);\n".printf (classcname, cname, def_args); //extends += applys; extends += " %s_%s (%s) {\n".printf (modulename, classname, def_args); if (context.profile == Profile.GOBJECT) extends += " g_type_init ();\n"; extends += " self = %s (%s);\n }\n".printf (cname, call_args); extends += clears; } else { if (!is_static) call_args = (call_args == "")? "self": "self, " + call_args; // externs += "extern %s %s (%s*, %s);\n".printf (ret, cname, classname, def_args); // extends += applys; if (is_static) extends += " static %s %s (%s) {\n".printf (ret, alias, def_args); else extends += " %s %s (%s) {\n".printf (ret, alias, def_args); if (ret.index_of ("std::vector") != -1) { int ptr = ret.index_of ("<"); string iter_type = (ptr==-1)?ret:ret[ptr:ret.length]; iter_type = iter_type.replace ("<", ""); iter_type = iter_type.replace (">", ""); // TODO: Check if iter type exists before failing // instead of hardcoding the most common type '' // TODO: Do not construct a generic class if not supported // instead of failing. if (iter_type == "G*") /* No generic */ error ("Pancake's fault, no type support.\n"); // TODO: Do not recheck the return_type if (m.return_type.to_string ().index_of ("RFList") != -1) { extends += " %s ret;\n".printf (ret); extends += " void** array;\n"; extends += " %s *item;\n".printf (iter_type); extends += " array = %s (%s);\n".printf (cname, call_args); extends += " r_flist_rewind (array);\n"; extends += " while (*array != 0 && (item = (%s*)(*array++)))\n".printf (iter_type); extends += " ret.push_back(*item);\n"; extends += " return ret;\n"; extends += " }\n"; } else if (m.return_type.to_string ().index_of ("RList") != -1) { extends += " %s ret;\n".printf (ret); extends += " RList *list;\n"; extends += " RListIter *iter;\n"; extends += " %s *item;\n".printf (iter_type); extends += " list = %s (%s);\n".printf (cname, call_args); extends += " if (list)\n"; extends += " for (iter = list->head; iter && (item = (%s*)iter->data); iter = iter->n)\n".printf (iter_type); extends += " ret.push_back(*item);\n"; extends += " return ret;\n"; extends += " }\n"; } vectors += " %%template(%sVector) std::vector<%s>;\n".printf ( iter_type, iter_type); } else { extends += " %s %s (%s);\n }\n".printf ( void_return?"":"return", cname, call_args); } extends += clears; } //} } public override void visit_namespace (Namespace ns) { if (ns.name == null) return; classname = ""; SourceReference? sr = ns.source_reference; if (sr != null && !is_target_file (sr.file.filename)) return; nspace = ns.name; process_includes (ns); /* if (pkgmode && sr.file.filename.index_of (pkgname) == -1) return; */ foreach (var f in ns.get_fields ()) walk_field (f); foreach (var e in ns.get_enums ()) walk_enum (e); foreach (var c in ns.get_structs ()) { /* TODO: refactor to walk_struct */ foreach (var m in c.get_methods ()) walk_method (m); foreach (var f in c.get_fields ()) walk_field (f); } foreach (var m in ns.get_methods ()) walk_method (m); var classprefix = ns.name == modulename? ns.name: ""; foreach (var c in ns.get_classes ()) walk_class (classprefix, c); //ns.name, c); //ns.accept_children (this); } public override void write (string file) { var stream = FileStream.open (file, "w"); if (stream == null) error ("Cannot open %s for writing".printf (file)); context.accept (this); if (includefiles.length () > 0) { stream.printf ("extern \"C\" {\n"); foreach (var inc in includefiles) stream.printf ("#include <%s>\n", inc); stream.printf ("}\n#include \n"); } foreach (var inc in includefiles) stream.printf ("#include <%s>\n", inc); /* if (vectors != "") stream.printf ("namespace std {\n%s}\n", vectors); */ stream.printf ("%s\n", enums); stream.printf ("%s\n", statics); stream.printf ("%s\n", extends); } } valabind-1.8.0/dlangwriter.vala000066400000000000000000000325301376122300700164730ustar00rootroot00000000000000/* Copyright 2013-2015 -- pancake */ using Vala; public class DlangWriter : ValabindWriter { public GLib.List includefiles = new GLib.List (); public GLib.List methods; string classname = ""; string classcname; string defs = ""; string statics = ""; string extends = ""; string enums = ""; string vectors = ""; string nspace; public DlangWriter () { } public override string get_filename (string base_name) { return base_name+".d"; } string get_alias (string name) { string oname = name; switch (name) { case "not_eq": case "or_eq": case "xor_eq": case "and_eq": case "or": case "xor": case "not": case "and": case "break": case "while": case "print": case "new": case "for": case "if": case "case": case "delete": case "continue": return "_"+name; } if (name != oname) warning ("%s.%s method renamed to %s.%s".printf ( classname, oname, classname, name)); return name; } string get_ctype (string _type) { string type = _type; string? iter_type = null; if (type == "null") error ("Cannot resolve type"); if (type.has_prefix (nspace)) type = type.substring (nspace.length) + "*"; type = type.replace (".", ""); if (is_generic (type)) { int ptr = type.index_of ("<"); iter_type = (ptr==-1)?type:type[ptr:type.length]; iter_type = iter_type.replace ("<", ""); iter_type = iter_type.replace (">", ""); iter_type = iter_type.replace (nspace, ""); type = type.split ("<", 2)[0]; } type = type.replace ("?",""); switch (type) { case "G": /* generic type :: TODO: review */ case "gconstpointer": case "gpointer": case "void*": return "void*"; case "gsize": return "size_t"; case "gdouble": return "double"; case "gfloat": return "float"; case "ut8": case "uint8": case "guint8": return "byte"; case "gchar**": return "char **"; case "char": case "gchar": return "char"; case "gchar*": case "string": case "const gchar*": return "string"; // XXX lost const? case "void": return "void"; case "int[]": case "int": case "gint": return "int"; case "guint": return "uint"; case "glong": return "long"; case "st64": case "int64": case "gint64": return "long"; case "ut64": case "uint64": case "guint64": return "ulong"; /* XXX swig does not support unsigned char* */ case "uint8*": case "guint8*": return "byte*"; case "guint16": case "uint16": return "ushort"; case "ut32": case "uint32": case "guint32": return "unsigned int"; case "bool": // no conversion needed case "gboolean": return "bool"; // XXX bool? case "RFList": if (iter_type != null) return "std::vector<"+iter_type+">"; break; case "RList": if (iter_type != null) return "std::vector<"+iter_type+">"; break; case "SdbList": if (iter_type != null) return "std::vector<"+iter_type+">"; break; default: type = "_"+type; break; } return type; } bool is_target_file (string path) { // FIXME implement the new method with use_namespace instead foreach (var file in source_files) if (file == path) return true; return false; } public override void visit_source_file (SourceFile source) { if (is_target_file (source.filename)) source.accept_children (this); } public void process_includes (Symbol s) { foreach (var foo in Vala.get_ccode_header_filenames (s).split (",")) { var include = true; foreach (var inc in includefiles) { if (inc == foo) { include = false; break; } } if (include) includefiles.prepend (foo); } } public void walk_field (Field f) { if (f.get_attribute_string ("CCode", "type") == null) { //warning ( // "Cannot resolve type for field '%s'".printf (f.get_cname ())); } else { warning ("Type for %s\n".printf ( Vala.get_ccode_name (f))); } string type = f.variable_type.to_string (); string name = f.name; if (type != "G") if (type.index_of ("<") == -1) { type = get_ctype (type); if (f.variable_type is ArrayType) { ArrayType array = f.variable_type as ArrayType; int len = array_length(array); int sz = len < 0 ? 0 : len; defs += " %s %s[%d];\n".printf (type, name, sz); } else { defs += " %s %s;\n".printf (type, name); } } //if (f.access == Accessibility.PRIVATE) // print ("---> field is private XXX\n"); //if (Vala.get_ccode_array_length (f)) // print ("---> array without length\n"); } HashTable defined_classes = new HashTable (str_hash, str_equal); public void walk_struct (string pfx, Struct s) { defs += "struct _%s%s {\n".printf (pfx, s.name); foreach (var f in s.get_fields ()) walk_field (f); defs += "}\n"; } public void walk_class (string pfx, Class c) { foreach (var k in c.get_structs ()) { walk_struct (c.name, k); } foreach (var k in c.get_classes ()) walk_class (c.name, k); classname = pfx+c.name; classcname = "_"+Vala.get_ccode_name (c); process_includes (c); bool has_constructor = false; foreach (var m in c.get_methods ()) if (m is CreationMethod) { has_constructor = true; break; } //bool is_static = (c.static_constructor != null); bool has_destructor = !c.is_compact; //stdout.printf ("class %s %s\n", // classname, c.is_compact.to_string () ); /* if (context.profile == Profile.GOBJECT) classname = "%s_%s".printf (nspace, classname); */ if (defined_classes.lookup (classname)) return; defined_classes.insert (classname, true); //extends += "struct %s {\n".printf (classcname); // TODO: add fields here //extends += "}\n"; defs += "struct %s {\n".printf (classcname); foreach (var f in c.get_fields ()) walk_field (f); defs += "}\n"; extends += "class %s {\n".printf (classname); extends += " %s *self;\n".printf (classcname); //extends += " public:\n"; foreach (var e in c.get_enums ()) walk_enum (e); //c.static_destructor!=null?"true":"false"); if (has_destructor && has_constructor) { if (Vala.is_reference_counting (c)) { string? freefun = Vala.get_ccode_unref_function (c); if (freefun != null && freefun != "") extends += " ~this() { %s (o); }\n".printf (freefun); } else { string? freefun = Vala.get_ccode_free_function (c); if (freefun != null) extends += " ~this() { %s (o); }\n".printf (freefun); } } foreach (var m in c.get_methods ()) walk_method (m); extends += "};\n"; classname = ""; } public void walk_enum (Vala.Enum e) { #if not_required var enumname = classname + e.name; var tmp = "%{\n"; enums += "/* enum: %s (%s) */\n".printf ( e.name, Vala.get_ccode_name (e)); enums += "enum %s {\n".printf (enumname); tmp += "#define %s long int\n".printf (enumname); // XXX: Use cname? foreach (var v in e.get_values ()) { enums += " %s_%s,\n".printf (e.name, v.name); tmp += "#define %s_%s %s\n".printf (e.name, v.name, Vala.get_ccode_name (v)); } enums += "};\n"; enums += tmp + "%}\n"; #endif } inline bool is_generic(string type) { return (type.index_of ("<") != -1 && type.index_of (">") != -1); } public void walk_method (Method m) { bool first = true; string cname = Vala.get_ccode_name (m); string alias = get_alias (m.name); string ret; string def_args = ""; string cdef_args = ""; string call_args = ""; bool void_return; bool is_static = (m.binding & MemberBinding.STATIC) != 0; bool is_constructor = (m is CreationMethod); // TODO: Implement contractual support // m.get_preconditions (); // m.get_postconditions (); ret = m.return_type.to_string (); ret = get_ctype (is_generic (ret)? ret : Vala.get_ccode_name (m.return_type)); if (ret == null) error ("Cannot resolve return type for %s\n".printf (cname)); void_return = (ret == "void"); if (m.is_private_symbol ()) return; string pfx = ""; string cpfx = ""; //cdef_args += "%s%s".printf (pfx, "void*"); if (!is_static) { cdef_args += classcname+"*"; cpfx = ", "; pfx = ""; } foreach (var foo in m.get_parameters ()) { string arg_name = foo.name; //DataType? bar = foo.parameter_type; DataType? bar = foo.variable_type; if (bar == null) continue; string? arg_type = get_ctype (Vala.get_ccode_name (bar)); if (first) { first = false; } else cpfx = pfx = ", "; /* TODO: move to get_ctype */ if (foo.direction != ParameterDirection.IN) { var var_name = ""; if (foo.direction == ParameterDirection.OUT) var_name = "ref"; else if (foo.direction == ParameterDirection.REF) var_name = "ref"; if (arg_type.index_of ("*") == -1) arg_type += "*"; } if (arg_type=="string") { call_args += "%s toStringz(%s)".printf (pfx, arg_name); cdef_args += "%s%s %s".printf (cpfx, "immutable(char*)", arg_name); def_args += "%s%s %s".printf (pfx, arg_type, arg_name); } else { call_args += "%s%s".printf (pfx, arg_name); def_args += "%s%s %s".printf (pfx, arg_type, arg_name); cdef_args += "%s%s %s".printf (cpfx, arg_type, arg_name); } } /* object oriented shit */ if (classname == "") { //defs += " %s* %s(%s);\n".printf (ret, cname, cdef_args); is_constructor = false; is_static = true; classname = nspace; } if (nspace == classname) alias = nspace+"_"+alias; if (is_constructor) { defs += " %s* %s(%s);\n".printf (classcname, cname, def_args.replace("string","immutable(char*)")); extends += " this (%s) {\n".printf (def_args); extends += " self = %s (%s);\n }\n".printf (cname, call_args); } else { if (!is_static) call_args = (call_args == "")? "self": "self, " + call_args; if (is_static) { extends += " %s %s (%s) {\n".printf (ret, alias, def_args); //extends += " static %s %s (%s) {\n".printf (ret, alias, def_args); } else { string fret = ""; if (alias == "free") { alias= "~this"; } else fret = ret; extends += " %s %s (%s) {\n".printf (fret, alias, def_args); } if (ret.index_of ("std::vector") != -1) { int ptr = ret.index_of ("<"); string iter_type = (ptr==-1)?ret:ret[ptr:ret.length]; iter_type = iter_type.replace ("<", ""); iter_type = iter_type.replace (">", ""); // TODO: Check if iter type exists before failing // instead of hardcoding the most common type '' // TODO: Do not construct a generic class if not supported // instead of failing. if (iter_type == "G*") /* No generic */ error ("Pancake's fault, no type support.\n"); // TODO: Do not recheck the return_type if (m.return_type.to_string ().index_of ("RFList") != -1) { extends += " %s ret;\n".printf (ret); extends += " void** array;\n"; extends += " %s *item;\n".printf (iter_type); extends += " array = %s (%s);\n".printf (cname, call_args); extends += " r_flist_rewind (array);\n"; extends += " while (*array != 0 && (item = (%s*)(*array++)))\n".printf (iter_type); extends += " ret.push_back(*item);\n"; extends += " return ret;\n"; extends += " }\n"; } else if (m.return_type.to_string ().index_of ("RList") != -1) { extends += " %s ret;\n".printf (ret); extends += " RList *list;\n"; extends += " RListIter *iter;\n"; extends += " %s *item;\n".printf (iter_type); extends += " list = %s (%s);\n".printf (cname, call_args); extends += " if (list)\n"; extends += " for (iter = list->head; iter && (item = (%s*)iter->data); iter = iter->n)\n".printf (iter_type); extends += " ret.push_back(*item);\n"; extends += " return ret;\n"; extends += " }\n"; } vectors += " %%template(%sVector) std::vector<%s>;\n".printf ( iter_type, iter_type); } else { defs += " %s %s(%s);\n".printf (ret, cname, cdef_args); extends += " %s %s (%s);\n }\n".printf ( void_return?"":"return", cname, call_args); } } } public override void visit_namespace (Namespace ns) { if (ns.name == null) return; classname = ""; SourceReference? sr = ns.source_reference; if (sr != null && !is_target_file (sr.file.filename)) return; nspace = ns.name; process_includes (ns); /* if (pkgmode && sr.file.filename.index_of (pkgname) == -1) return; */ foreach (var f in ns.get_fields ()) walk_field (f); foreach (var e in ns.get_enums ()) walk_enum (e); foreach (var c in ns.get_structs ()) { /* TODO: refactor to walk_struct */ foreach (var m in c.get_methods ()) walk_method (m); foreach (var f in c.get_fields ()) walk_field (f); } foreach (var m in ns.get_methods ()) walk_method (m); var classprefix = ns.name == modulename? ns.name: ""; foreach (var c in ns.get_classes ()) walk_class (classprefix, c); //ns.name, c); //ns.accept_children (this); } public override void write (string file) { var stream = FileStream.open (file, "w"); if (stream == null) error ("Cannot open %s for writing".printf (file)); defs = "extern(C) {\n"; context.accept (this); defs += " alias int function(int, int) _RNumCallback;\n"; // HACK defs += "}\n"; stream.printf ("/* valabind autogenerated D bindings for %s */\n".printf (modulename)); stream.printf ("pragma(lib,\"%s\");\n".printf (modulename)); stream.printf ("pragma(lib,\"r_util\");\n"); stream.printf ("import std.string;\n"); stream.printf ("%s\n", defs); stream.printf ("%s\n", enums); stream.printf ("%s\n", statics); stream.printf ("%s\n", extends); } } valabind-1.8.0/getvv000077500000000000000000000004371376122300700143660ustar00rootroot00000000000000#!/bin/sh IFS=: [ -z "${VALAC}" ] && VALAC=valac for a in $PATH; do if [ -e "$a/valac" ]; then v=$(cat $a/${VALAC} | strings | grep vala- | grep -v lib | head -n1) if [ -n "$v" ]; then printf $v exit 0 fi fi done echo "Cannot find valac version string" >/dev/stderr exit 1 valabind-1.8.0/girwriter.vala000066400000000000000000000260731376122300700161740ustar00rootroot00000000000000/* Copyright 2011-2019 -- pancake */ using Vala; public class GirWriter : ValabindWriter { public GLib.List includefiles = new GLib.List (); public GLib.List methods; string classname = ""; string classcname; string externs = ""; string statics = ""; string extends = ""; string enums = ""; string nspace; public GirWriter () { } public override string get_filename (string base_name) { return base_name+".gir"; } public override void write(string file) { context.accept (this); } string get_alias (string name) { string oname = name; switch (name) { /* case "use": return "_use"; */ case "cmd": name = "_cmd"; break; case "def": name = "_def"; break; case "print": name = "_print"; break; case "del": name = "_del"; break; case "from": name = "_from"; break; case "continue": name = "cont"; break; } if (name != oname) warning ("%s.%s method renamed to %s.%s".printf ( classname, oname, classname, name)); return name; } string get_ctype (string _type) { string type = _type; string? iter_type = null; if (type == "null") error ("Cannot resolve type"); if (type.has_prefix (nspace)) type = type.substring (nspace.length) + "*"; type = type.replace (".", ""); if (is_generic (type)) { int ptr = type.index_of ("<"); iter_type = (ptr==-1)?type:type[ptr:type.length]; iter_type = iter_type.replace ("<", ""); iter_type = iter_type.replace (">", ""); iter_type = iter_type.replace (nspace, ""); type = type.split ("<", 2)[0]; } type = type.replace ("?", ""); switch (type) { case "const gchar*": return "const char*"; case "G": /* generic type :: TODO: review */ case "gconstpointer": case "gpointer": return "void*"; case "gdouble": return "double"; case "gfloat": return "float"; case "break": return "_break"; case "ut8": case "uint8": case "guint8": return "unsigned char"; case "gchar**": return "char **"; case "gchar": return "char"; case "gchar*": case "string": return "char *"; //return "char *"; // ??? case "gint": return "int"; case "glong": return "long"; case "st64": case "int64": case "gint64": return "long long"; case "ut64": case "uint64": case "guint64": return "unsigned long long"; /* XXX swig does not support unsigned char* */ case "uint8*": case "guint8*": return "unsigned char*"; case "guint16": case "uint16": return "unsigned short"; case "ut32": case "uint32": case "guint32": return "unsigned int"; case "bool": // no conversion needed case "gboolean": return "gboolean"; case "RFList": if (iter_type != null) return "std::vector<"+iter_type+">"; break; case "RList": if (iter_type != null) return "std::vector<"+iter_type+">"; break; case "SdbList": if (iter_type != null) return "std::vector<"+iter_type+">"; break; } return type; } static string girtype(string ret) { switch (ret) { case "int[]": return "gpointer"; // XXX case "string?": case "string": case "char*": case "char *": case "const char*": ret = "utf8"; break; case "uint": case "uint32": case "unsigned int": ret = "guint"; break; case "int": case "int32": ret = "gint"; break; case "unsigned long long": case "uint64": ret = "guint64"; break; case "void*": case "unsigned char*": case "uint8*": ret = "gpointer"; break; case "bool": ret = "gboolean"; break; } if (ret[ret.length-1] == '*') return "gpointer"; return ret; } bool is_target_file (string path) { // FIXME implement the new method with use_namespace instead foreach (var file in source_files) if (file == path) return true; return false; } public void walk_constant (Constant f) { var cname = Vala.get_ccode_name (f); var cvalue = "TODO"; var ctype = get_ctype (f.type_reference.to_string ()); var gtype = girtype (f.type_reference.to_string ()); extends += "\n"; extends += " \n"; extends += "\n"; //extends += "static const char *"+f.name+" = "+cname+";\n"; } public override void visit_source_file (SourceFile source) { if (is_target_file (source.filename)) source.accept_children (this); } public void process_includes (Symbol s) { foreach (var foo in Vala.get_ccode_header_filenames (s).split (",")) { var include = true; foreach (var inc in includefiles) { if (inc == foo) { include = false; break; } } if (include) includefiles.prepend (foo); } } public void walk_field (Field f) { var name = Vala.get_ccode_name (f); var type = f.variable_type.to_string (); type = get_ctype (type); externs += " \n"; externs += " \n"; externs += " \n"; } public void walk_struct (string pfx, Struct s) { var name = s.name; externs += " \n"; // TODO: parent="" type-name="" get-type="" /* TODO: refactor to walk_struct */ foreach (var m in s.get_methods ()) walk_method (m); foreach (var f in s.get_fields ()) walk_field (f); externs += " \n"; } public void walk_class (string pfx, Class c) { foreach (var k in c.get_classes ()) walk_class (c.name, k); classname = pfx+c.name; classcname = Vala.get_ccode_name (c); process_includes (c); if (context.profile == Profile.GOBJECT) classname = "%s%s".printf (nspace, classname); externs += " \n"; // TODO: parent="" type-name="" get-type="" // TODO: print ("PARENT FOR "+classname+" IS: "+c.parent_node.type_name+"\n"); // parent=\"\" foreach (var e in c.get_enums ()) walk_enum (e); foreach (var f in c.get_fields ()) walk_field (f); /* if (c.is_reference_counting ()) { string? freefun = c.get_unref_function (); if (freefun != null) extends += " ~%s%s() {\n %s (self);\n }\n".printf (modulename, classname, freefun); } else { string? freefun = c.get_free_function (); if (freefun != null) extends += " ~%s%s() {\n %s (self);\n }\n".printf (modulename, classname, freefun); } */ foreach (var m in c.get_methods ()) walk_method (m); externs += " \n"; classname = ""; } public void walk_enum (Vala.Enum e) { #if NOT_YET_IMPLEMENTED var enumname = classname + e.name; var tmp = " \n"; // type-name=\""+e.name+"\" get-type=\"\">\n"; //enums += "/* enum: %s (%s) */\n".printf ( e.name, e.get_cname ()); //enums += "enum %s {\n".printf (enumname); //tmp += "#define %s long int\n".printf (enumname); // XXX: Use cname? foreach (var v in e.get_values ()) { tmp += " \n"; //enums += " %s_%s,\n".printf (e.name, v.name); //tmp += "#define %s_%s %s\n".printf (e.name, v.name, v.get_cname ()); } tmp += " \n"; enums = tmp + "\n" + enums; #endif } inline bool is_generic(string type) { return (type.index_of ("<") != -1 && type.index_of (">") != -1); } public void walk_method (Method m) { //bool first = true; string cname = Vala.get_ccode_name (m); string alias = get_alias (m.name); string ret, vret; bool void_return; bool is_static = (m.binding & MemberBinding.STATIC) != 0; bool is_constructor = (m is CreationMethod); // TODO: Implement contractual support // m.get_preconditions (); // m.get_postconditions (); ret = vret = m.return_type.to_string (); if (is_generic (ret)) ret = get_ctype (vret); else ret = get_ctype (Vala.get_ccode_name (m.return_type)); if (ret == null) error ("Cannot resolve return type for %s\n".printf (cname)); void_return = (ret == "void"); if (m.is_private_symbol ()) return; string type = is_static?"function":"method"; if (classname != "" && !is_static) type = "method"; if (is_constructor) { type = "constructor"; alias = "new"; void_return = false; ret = nspace+"."+classname; } //externs += "<"+type+" name=\""+alias+"\" c:identifier=\""+cname+"\">\n"; externs += "<"+type+" name=\""+alias+"\" c:identifier=\""+cname+"\">\n"; //externs += " \n"; externs += " \n"; if (!void_return) { var rtype = get_ctype (ret); externs += " \n"; } else externs += " \n"; externs += " \n"; var parameters = m.get_parameters (); if (parameters.size>0) { externs += " \n"; foreach (var foo in parameters) { string arg_name = foo.name; DataType? bar = foo.variable_type; if (bar == null) continue; string? arg_type = girtype (bar.to_string ()); string? arg_ctype = get_ctype (Vala.get_ccode_name (bar)); externs += " \n"; externs += " \n"; externs += " \n"; } externs += " \n"; } externs += "\n"; //function>\n"; } public override void visit_namespace (Namespace ns) { if (ns.name == null) return; SourceReference? sr = ns.source_reference; if (sr != null && !is_target_file (sr.file.filename)) return; nspace = ns.name; process_includes (ns); //externs += "\n"; //if (pkgmode && sr.file.filename.index_of (pkgname) == -1) // return; foreach (var f in ns.get_constants ()) walk_constant (f); foreach (var f in ns.get_fields ()) walk_field (f); foreach (var e in ns.get_enums ()) walk_enum (e); foreach (var s in ns.get_structs ()) walk_struct ("", s); foreach (var m in ns.get_methods ()) walk_method (m); foreach (var c in ns.get_classes ()) walk_class ("", c); //ns.accept_children (this); //externs += "\n"; } public void write_file (string file) { var stream = FileStream.open (file, "w"); if (stream == null) error ("Cannot open %s for writing".printf (file)); context.accept (this); stream.printf ("\n"); stream.printf ("\n"); stream.printf ("\n"); stream.printf ("\n"); stream.printf (" \n"); if (includefiles.length () > 0) foreach (var inc in includefiles) stream.printf (" \n", inc); stream.printf (" \n"); stream.printf ("%s\n", enums); stream.printf ("%s\n", externs); stream.printf ("%s\n", statics); stream.printf ("%s\n", extends); stream.printf (" \n"); stream.printf ("\n"); } } valabind-1.8.0/gowriter.vala000066400000000000000000000707261376122300700160240ustar00rootroot00000000000000/* Copyleft 2014 -- williballenthin */ using Vala; // walks all the datatypes and collects instances of generic classes // we need this because i cannot figure out how to fetch the "is_generic" attribute // from a Vala.Class node object. // this way, we have to inspect all instances of objects to find what's actually used, // and then parse the type name (which includes the <...> specializer). public class GenericClassFinder : ValabindWriter { // map(base_class -> map(specialized instance string -> list(DataType))) // see: http://stackoverflow.com/questions/24072692/how-can-i-use-a-hashmap-of-string-in-vala GLib.HashTable>> generic_classes = new GLib.HashTable>> (GLib.str_hash, GLib.str_equal); inline bool is_generic(DataType d) { return (d.get_type_arguments().size > 0); } inline bool is_glib(DataType d) { // maybe should be .starts_with return d.to_string().index_of("GLib.") != -1; } // the base class name, no namespace inline string get_class_name(DataType d) { string s = d.to_string(); return s.substring(0, s.index_of_char('<')); } // `s` should not contain a specializer (<...>) inline string strip_namespace(string s) { int i1 = s.last_index_of_char('.') + 1; return s.substring(i1); } public override void visit_data_type(DataType d) { if (is_generic(d) && ( ! is_glib(d))) { string c = strip_namespace(get_class_name(d)); unowned GLib.HashTable>? inner_set = generic_classes[c]; if (inner_set == null) { var v = new GLib.HashTable> (GLib.str_hash, GLib.str_equal); inner_set = v; generic_classes.insert ((owned) c, (owned) v); } GLib.List args = new GLib.List(); foreach (var t in d.get_type_arguments()) { args.append(t); } inner_set.replace(d.to_string(), (owned) args); } } public override void visit_method(Method m) { m.accept_children (this); } public override void visit_field(Field f) { f.accept_children (this); } public override void visit_source_file (SourceFile source) { source.accept_children (this); } public override void visit_namespace(Namespace ns) { ns.accept_children (this); } public override void visit_class(Class c) { c.accept_children (this); } // `.write` is the method that actually does things in a ValabindWriter public override void write(string file) { context.accept (this); } // careful, the return object is mutable // you probably want to call this after `.write` // TODO: should use @get public GLib.HashTable>> get_generic_class_instances() { return this.generic_classes; } } // This class is responsible for figuring out *what* to call things, // like, what an appropriate Go symbol name is, or the source C symbol in a struct. // The GoWriter decides *where* to place the names generated by this class. public class GoNamer { private string pfx; private GLib.HashTable specializations = new GLib.HashTable(GLib.str_hash, GLib.str_equal); private GLib.List ordered_specializations = new GLib.List(); public GoNamer(string pfx) { this.pfx = pfx; } public void add_specialization(TypeParameter t, DataType d) { specializations.insert(t.name, d); ordered_specializations.append(d); } // converts symbol names with underscores to camelCase. // this function should not be called directly. See `camelcase`. // allows trailing '_' characters. private static string cleanup_underscores(string name) { if (name.length == 0) { return ""; } else if (name.length == 1) { // accept trailing '_' return name; } else if (name.index_of("_") == -1) { return name; } else { // there is a '_' here somewhere int i = name.index_of("_"); if (i == name.length - 1) { // accept trailing '_' return name; } // there must be at least one more character // everything before the '_' string before = ""; if (i != 0) { before = name.substring(0, i); } // find next non-'_' character uppercase, or all '_' if thats all thats left // j will be the index of this character string next; int j = i + 1; while (true) { before = name.substring(0, i); if (name[j] != '_') { next = name.substring(j, 1).up(); break; } j++; if (j == name.length) { // only '_' remain next = name.substring(i, j - i); // so catch them all break; } } if (j >= name.length - 1) { return before + next; } else { // do rest of string return before + next + cleanup_underscores(name.substring(j + 1)); } } } // see tests t/go/camelcase.vapi private static string camelcase(string name) { if (name.length == 0) { return ""; } else if (name.length == 1) { return name.up(); } else { return name.substring(0, 1).up() + cleanup_underscores(name.substring(1, name.length - 1)); } } public string get_field_name(Field f) { return camelcase(f.name); } // renames the C symbol for a field // useful because Go convention is to rename "type" --> "_type" public string get_field_cname(Field f) { string n = Vala.get_ccode_name(f); if (n == "type") { return "_type"; } else { return n; } } public string get_method_name(Method m) { return camelcase(m.name); } public string get_method_cname(Method m) { return Vala.get_ccode_name(m); } public string get_parameter_name(Vala.Parameter p) { return camelcase(p.name); } public string get_enum_name(Enum e) { return e.name; } public string get_enum_value_name(Vala.EnumValue v) { return v.name; } public string get_enum_value_cname(Vala.EnumValue v) { return v.name; } public string get_constructor_name(Class c, Method m) { string postfix = ""; if (m.name != ".new") { postfix = camelcase(m.name); } return "New%s%s".printf(get_class_name(c), postfix); } private string mangle_datatype(DataType d) { #if VALA_0_48 string ret = d.type_symbol.name; // i think should unify with get_type_declaration? #else string ret = d.data_type.name; // i think should unify with get_type_declaration? #endif if (d.get_type_arguments().size > 0) { foreach(var dd in d.get_type_arguments()) { ret += "_"; ret += mangle_datatype(dd); } } return ret; } // get the name of a class. If its a generic class, then // we use the set of specializations in our local context // to mangle the name. // this must keep in sync with get_specialized_type_declaration public string get_class_name(Class c) { bool has_specializations = false; foreach(var s in ordered_specializations) { has_specializations = true; break; } string postfix = ""; if (has_specializations) { foreach(DataType d in ordered_specializations) { postfix += "_"; postfix += mangle_datatype(d); } } return "%s%s%s".printf(this.pfx, camelcase(c.name), postfix); } // get the name of an already specialized generic class. That is, // turning something like vapi: List into go: List_int. // this must be kept in sync with get_class_name public string get_specialized_type_declaration(DataType d) { return mangle_datatype(d); } public string get_class_cname(Class c) { return Vala.get_ccode_name(c); } public string get_struct_name(Struct s) { return "%s%s".printf(this.pfx, camelcase(s.name)); } public string get_struct_cname(Struct s) { return Vala.get_ccode_name(s); } public string get_namespace_name(Namespace ns) { return ns.name; } inline bool is_generic(string type) { // TODO: fix things so we don't need this return (type.index_of ("<") != -1 && type.index_of (">") != -1); } private string get_ctype (string _type) { string type = _type; string? iter_type = null; if (type == "null") { error ("Cannot resolve type"); } if (is_generic (type)) { int ptr = type.index_of ("<"); iter_type = (ptr==-1)?type:type[ptr:type.length]; iter_type = iter_type.replace ("<", ""); iter_type = iter_type.replace (">", ""); type = type.split ("<", 2)[0]; } type = type.replace ("?",""); switch (type) { case "gconstpointer": case "gpointer": case "void*": return "void*"; case "gsize": return "size_t"; case "gdouble": return "double"; case "gfloat": return "float"; case "ut8": case "uint8": case "guint8": return "byte"; case "gchar**": return "char **"; case "char": case "gchar": return "char"; case "gchar*": case "string": case "const gchar*": return "string"; // XXX lost const? case "void": return "void"; case "int[]": case "int": case "gint": return "int"; case "guint": return "uint"; case "glong": return "long"; case "st64": case "int64": case "gint64": return "long"; case "ut64": case "uint64": case "guint64": return "ulong"; /* XXX swig does not support unsigned char* */ case "uint8*": case "guint8*": return "byte*"; case "guint16": case "uint16": return "ushort"; case "ut32": case "uint32": case "guint32": return "unsigned int"; case "bool": // no conversion needed case "gboolean": return "bool"; // XXX bool? default: break; } return type; } private inline string strip_non_class_name(string s) { return s.substring(0, s.index_of_char('<')); } // `s` should not contain a specializer (<...>) private inline string strip_namespace(string s) { int i1 = s.last_index_of_char('.') + 1; return s.substring(i1); } // given a DataType symbol, return a string that contains the Go source code for // a type specifier of that type. private string get_type_declaration(DataType type) { string basic_name = type.to_string(); if (specializations.lookup(basic_name) != null) { // replace type specializations (things like "public G member1;" // NOTE: doesn't support some complex specializations, like public List member1;" DataType dt = specializations.lookup(basic_name); basic_name = dt.to_string(); } else if (type.to_string().index_of ("<") != -1) { basic_name = get_specialized_type_declaration(type); } // guess basic_name = strip_namespace(strip_non_class_name(basic_name)); string typename = get_ctype (basic_name); // TODO: why are we using ctype here? // we can typecheck to determine if this is a pointer, so throw away '*' typename = typename.replace("*", "").strip(); // if `type` is a pointer, then this will contain the appropriate '*' string maybe_pointer_sym = ""; // if `type` is an array, then this will contain the appropriate "[]" string maybe_array_sym = ""; if (type is PointerType) { // I suspect we don't support pointer-to-pointer if (typename == "void") { typename = "unsafe.Pointer"; // go specific hack type for void * // TODO: need to re-enable this somehow // this.needs_unsafe = true; maybe_pointer_sym = ""; } else { maybe_pointer_sym = "*"; } } if (type is ArrayType) { maybe_array_sym = "[]"; } return "%s%s%s".printf(maybe_array_sym, maybe_pointer_sym, typename); } public string get_field_type_declaration(Field f) { return get_type_declaration(f.variable_type); } public string get_parameter_type_declaration(Vala.Parameter p) { return get_type_declaration(p.variable_type); } public string get_method_return_type_declaration(Method m) { return get_type_declaration(m.return_type); } } public class GoSrcWriter : ValabindWriter { public GLib.List includefiles = new GLib.List (); HashTable defined_classes = new HashTable (str_hash, str_equal); GLib.HashTable>> generic_classes = new GLib.HashTable>> (GLib.str_hash, GLib.str_equal); string classname = ""; string classcname; string defs = ""; string statics = ""; string extends = ""; string enums = ""; string nspace; bool needs_unsafe = false; // set to true if the 'unsafe' package needs to be imported because a void* pointer was encountered public GoSrcWriter () {} string _indent = ""; // TODO(wb): removeme void debug(string s) { notice(_indent + s); } void indent() { _indent = _indent + " "; } void dedent() { _indent = _indent.substring(0, _indent.length - 2); } public void set_generic_class_instances(GLib.HashTable>> generic_classes) { this.generic_classes = generic_classes; } private bool is_target_file (string path) { foreach (var file in source_files) if (file == path) return true; return false; } public override void visit_source_file (SourceFile source) { if (is_target_file (source.filename)) { source.accept_children (this); } } private void process_includes (Symbol s) { debug("process_includes(sym: %s)".printf(s.name)); indent(); foreach (var foo in Vala.get_ccode_header_filenames (s).split (",")) { debug("include(%s)".printf(foo)); var include = true; foreach (var inc in includefiles) { if (inc == foo) { include = false; break; } } if (include) { includefiles.prepend (foo); } } dedent(); } private bool is_string(CodeNode t) { if (t is DataType) { DataType a = t as DataType; return a.to_string() == "string"; } else if (t is Field) { Field a = t as Field; return a.variable_type.to_string() == "string"; } else if (t is Vala.Parameter) { Vala.Parameter a = t as Vala.Parameter; return a.variable_type.to_string() == "string"; } else { warning("unexpected type to is_string"); return false; } } // here, we use explicit accessors and mutators to fixup accessibility. private string walk_field (GoNamer namer, string owner_name, Field f) { string ret = ""; debug("walk_field(name: %s)".printf(f.name)); indent(); if (f.is_private_symbol()) { debug("private."); dedent(); return ret; } // TODO: handle generics. ATM, type of `public G data` becomes `func ... GetData() void` // TODO: make this a function `is_string` if (is_string(f)) { ret += "func (s %s) Get%s() %s {\n".printf(owner_name, namer.get_field_name(f), namer.get_field_type_declaration(f)); ret += " return C.GoString(s.%s)\n".printf(namer.get_field_cname(f)); ret += "}\n"; ret += "func (s *%s) Set%s(a %s) {\n".printf(owner_name, namer.get_field_name(f), namer.get_field_type_declaration(f)); ret += " s.%s = C.CString(a)\n".printf(namer.get_field_cname(f)); ret += " return\n"; ret += "}\n"; } else { ret += "func (s %s) Get%s() %s {\n".printf(owner_name, namer.get_field_name(f), namer.get_field_type_declaration(f)); ret += " return s.%s\n".printf(namer.get_field_cname(f)); ret += "}\n"; ret += "func (s *%s) Set%s(a %s) {\n".printf(owner_name, namer.get_field_name(f), namer.get_field_type_declaration(f)); ret += " s.%s = a\n".printf(namer.get_field_cname(f)); ret += " return\n"; ret += "}\n"; } dedent(); return ret; } private string walk_class_field(GoNamer namer, Class c, Field f) { return walk_field(namer, namer.get_class_name(c), f); } private string walk_struct_field(GoNamer namer, Struct s, Field f) { return walk_field(namer, namer.get_struct_name(s), f); } private string walk_namespace_field(GoNamer namer, Namespace ns, Field f) { return walk_field(namer, "nsimp" + namer.get_namespace_name(ns), f); } private string walk_struct (GoNamer namer, Struct s) { string ret = ""; debug("walk_struct(name: %s)".printf(s.name)); indent(); ret += "type %s C.%s\n".printf(namer.get_struct_name(s), namer.get_struct_cname(s)); foreach (var f in s.get_fields()) { ret += walk_struct_field(namer, s, f); } ret += "\n"; dedent(); return ret; } private string walk_enum (GoNamer namer, Vala.Enum e) { string ret = ""; var pfx = Vala.get_ccode_prefix(e); debug("walk_enum(pfx: %s, name: %s)".printf(pfx, e.name)); indent(); ret += "const (\n"; foreach (var v in e.get_values()) { debug("enum(name: %s)".printf(v.name)); ret += " %s%s = C.%s%s\n".printf(pfx, namer.get_enum_value_name(v), pfx, namer.get_enum_value_cname(v)); } ret += ")\n"; ret += "type %s int\n\n".printf(namer.get_enum_name(e)); dedent(); return ret; } // is_string: if the parameter is a string // arg_name: the C symbol parameter name // maybe_pointer_sym: might contain a '*' if needed for the Go symbol. Useful for `out` parameters. // arg_type: the parameter type in all its glory delegate string parameter_visitor(bool is_string, string maybe_pointer_sym, Vala.Parameter p); private string get_function_parameters(GoNamer namer, Method f, parameter_visitor v) { string args = ""; bool first = true; foreach (var p in f.get_parameters ()) { string maybe_pointer_sym = ""; if (p.direction != ParameterDirection.IN) { // TODO: exploit multiple return values? if (p.direction == ParameterDirection.OUT) { if (! is_string(p)) { maybe_pointer_sym = "*"; } } else if (p.direction == ParameterDirection.REF) { if (! is_string(p)) { maybe_pointer_sym = "*"; } } } if (first) { first = false; } else { args += ", "; } // TODO: consider special handling of `uint8 *buf, int len`? args += v(is_string(p), maybe_pointer_sym, p); } return args; } // BUG: doesn't support '...' parameters private string get_function_declaration_parameters(GoNamer namer, Method f) { parameter_visitor formatter = (is_string, maybe_pointer_sym, p) => { // what about array of char *? I think we have to let the caller deal with it // hopefully overflows don't happen here? return "%s %s%s".printf (namer.get_parameter_name(p), maybe_pointer_sym, namer.get_parameter_type_declaration(p)); }; return get_function_parameters(namer, f, formatter); } // BUG: doesn't support '...' parameters private string get_function_call_parameters(GoNamer namer, Method f) { parameter_visitor formatter = (is_string, maybe_pointer_sym, p) => { if (is_string) { // what about array of char *? I think we have to let the caller deal with it // hopefully overflows don't happen here? return "C.CString(%s)".printf (namer.get_parameter_name(p)); } else { return "%s".printf (namer.get_parameter_name(p)); } }; return get_function_parameters(namer, f, formatter); } private bool is_void_function(Method f) { return f.return_type.to_string() == "void"; } // see tests t/go/namespace_functions.vapi private string walk_function(GoNamer namer, Namespace ns, Method f) { string ret = ""; string nsname = namer.get_namespace_name(ns); string cname = namer.get_method_cname(f); debug("walk_function(ns: %s, name: %s)".printf(nsname, cname)); indent(); if (f is CreationMethod) { warning("constructor where function expected"); } if (f.is_private_symbol ()) { debug("private."); dedent(); return ret; } string def_args = get_function_declaration_parameters(namer, f); string call_args = get_function_call_parameters(namer, f); if ( ! is_void_function(f)) { ret += "func (_ nsimp%s) %s(%s) %s {\n".printf (nsname, namer.get_method_name(f), def_args, namer.get_method_return_type_declaration(f)); if (is_string(f.return_type)) { // we have to let the caller deal with array of char * // what happens if there are embedded nulls? ret += " return C.GoString(%s(%s))\n".printf (cname, call_args); } else { // TODO: what about void*? ret += " return %s(%s)\n".printf (cname, call_args); } } else { ret += "func (_ nsimp%s) %s(%s) {\n".printf (nsname, namer.get_method_name(f), def_args); ret += " %s(%s)\n".printf (cname, call_args); } ret += "}\n"; dedent(); return ret; } private string walk_method (GoNamer namer, Class c, Method m) { string ret = ""; string classname = namer.get_class_name(c); string cname = namer.get_method_cname(m); debug("walk_method(ns: %s, name: %s)".printf(classname, cname)); indent(); // TODO: "unowned"/static methods if (m is CreationMethod) { warning("constructor where function expected"); } if (m.is_private_symbol ()) { debug("private."); dedent(); return ret; } string def_args = get_function_declaration_parameters(namer, m); string call_args = get_function_call_parameters(namer, m); ret += "func (this *%s) %s(".printf(classname, namer.get_method_name(m)); if (def_args != "") { ret += "%s".printf(def_args); } ret += ") "; if ( ! is_void_function(m)) { ret += "%s ".printf(namer.get_method_return_type_declaration(m)); } ret += "{\n"; ret += " "; if ( ! is_void_function(m)) { ret += "return "; if (is_string(m.return_type)) { // TODO: use wrap_type function ret += "C.GoString("; } ret += "%s(this".printf(cname); if (call_args != "") { ret += ", %s".printf(call_args); } ret += ")"; if (is_string(m.return_type)) { ret += ")"; } ret += "\n"; } else { ret += "%s(this".printf(cname); if (call_args != "") { ret += ", %s".printf(call_args); } ret += ")\n"; } ret += "}\n"; dedent(); return ret; } private string walk_constructor(GoNamer namer, Class c, Method m, string free_function) { string ret = ""; string classname = namer.get_class_name(c); string cname = namer.get_method_cname(m); debug("walk_method(ns: %s, name: %s)".printf(classname, cname)); indent(); // TODO: "unowned"/static methods if (m.is_private_symbol ()) { debug("private."); dedent(); return ret; } ret += "func %s(".printf(namer.get_constructor_name(c, m)); ret += "%s".printf(get_function_declaration_parameters(namer, m)); ret += ") *%s {\n".printf(classname); ret += " var ret *%s\n".printf(classname); ret += " ret = C.%s(".printf(cname); ret += "%s".printf(get_function_call_parameters(namer, m)); ret += ")\n"; if (free_function != "") { ret += " SetFinalizer(ret, func(r *%s) {\n".printf(classname); ret += " C.%s(r)\n".printf(free_function); ret += " })\n"; } ret += " return ret\n"; ret += "}\n"; dedent(); return ret; } private string get_class_src(GoNamer namer, Class c) { string ret = ""; foreach (var k in c.get_structs ()) { ret += walk_struct (namer, k); } foreach (var k in c.get_classes ()) { ret += walk_class (k); } classname = namer.get_class_name(c); classcname = namer.get_class_cname(c); process_includes (c); if (defined_classes.lookup (classname)) { debug("already defined"); dedent(); return ret; } defined_classes.insert (classname, true); bool has_constructor = false; foreach (var m in c.get_methods ()) { if (m is CreationMethod) { has_constructor = true; break; } } ret += "type %s C.%s\n".printf(classname, classcname); foreach (var f in c.get_fields()) { ret += walk_class_field(namer, c, f); } foreach (var e in c.get_enums ()) { ret += walk_enum (namer, e); } foreach (var m in c.get_methods ()) { if ( ! (m is CreationMethod)) { ret += walk_method (namer, c, m); } else { string free_function = ""; if (Vala.is_reference_counting (c)) { string? freefun = Vala.get_ccode_unref_function (c); if (freefun != null && freefun != "") { free_function = freefun; } } else { // BUG?: this method always seems to return a free function (default: ${cprefix}_free) // even if there is no `free_function` defined in the `CCode` block // see test in t/go/classes.vapi string? freefun = Vala.get_ccode_free_function (c); if (freefun != null) { free_function = freefun; } } ret += walk_constructor(namer, c, m, free_function); } } ret += "\n"; dedent(); return ret; } private string walk_class (Class c) { string ret = ""; debug("walk_class(name: %s)".printf(c.name)); indent(); if (this.generic_classes.contains(c.name)) { debug("generic class"); indent(); unowned GLib.HashTable> specializations; specializations = this.generic_classes.lookup(c.name); specializations.foreach((k, v) => { debug("specialization: %s".printf(k)); indent(); // TODO: might need to change the prefix GoNamer namer = new GoNamer(""); GLib.List vv = v.copy(); foreach(var t in c.get_type_parameters()) { debug("%s -> %s".printf(t.name, vv.nth_data(0).to_string())); namer.add_specialization(t, vv.nth_data(0)); vv.delete_link(vv.nth(0)); // pop(0) } ret += "// %s<".printf(c.name); foreach(var t in v.copy()) { ret += t.to_string(); ret += ", "; } ret += ">\n"; ret += get_class_src(namer, c); dedent(); }); dedent(); } else { // TODO: might need to change the prefix GoNamer namer = new GoNamer(""); ret += get_class_src(namer, c); } dedent(); return ret; } // go doesn't really support namespaces. Often code is namespaced by // directory hierarchy, but thats for code organization. // we eat namespaces here, as they don't generate anything besides their children. public override void visit_namespace (Namespace ns) { string ret = ""; debug("walk_namespace(name: %s)".printf(ns.name)); indent(); if (ns.name == "") { return; } classname = ""; SourceReference? sr = ns.source_reference; if (sr == null || !is_target_file (sr.file.filename)) { // TODO: should this be &&? dedent(); return; } nspace = ns.name; process_includes (ns); foreach (var e in ns.get_enums ()) { // enums will float to the top-level "namespace" in Go, since we aren't doing namespaces. ret += walk_enum (new GoNamer(ns.name == modulename ? ns.name : ""), e); } foreach (var c in ns.get_structs()) { ret += walk_struct(new GoNamer(ns.name == modulename ? ns.name : ""), c); } if (ns.get_methods().size + ns.get_fields().size > 0) { // Go only does namespacing through file system paths, whish is // probably not appropriate/feasible here // so we fake it by creating a new type, and one instance of it, // and attach the functions to it. // Note, this doesn't work for nested namespaces, but its better than nothing. // // for example: // namespace N { public static void fn1(); } // // becomes: // type nsimptN int // func (_ nsimpN) Fn1() { fn1() } // var N nsimpN // // so a user can do: // import "/some/path/test" // test.N.Fn() string fake_ns_name = "nsimp%s".printf(ns.name); ret += "type %s int\n".printf(fake_ns_name); foreach (var c in ns.get_fields()) { ret += walk_namespace_field(new GoNamer(ns.name == modulename ? ns.name : ""), ns, c); } foreach (var m in ns.get_methods()) { ret += walk_function(new GoNamer(ns.name == modulename ? ns.name : ""), ns, m); } ret += "var %s %s\n".printf(ns.name, fake_ns_name); ret += "\n"; } foreach (var c in ns.get_classes ()) { ret += walk_class (c); //ns.name, c); } dedent(); defs += ret; } public override void write (string file) { var stream = FileStream.open (file, "w"); if (stream == null) { error ("Cannot open %s for writing".printf (file)); } // before the `pre` stuff because we need `includefiles` to be populated. context.accept (this); var pre = "package %s\n".printf(modulename); pre += "\n"; pre += "// #cgo LDFLAGS: -l%s\n".printf(modulename); // TODO(wb): how2get library name? foreach (var inc in includefiles) { pre += "// #include \"%s\"\n".printf(inc); } pre += "import \"C\"\n"; if (this.needs_unsafe) { pre += "import \"unsafe\"\n"; } stream.printf ("/* valabind autogenerated Go bindings for %s */\n".printf (modulename)); stream.printf ("%s\n", pre); stream.printf ("%s\n", enums); stream.printf ("%s\n", statics); stream.printf ("%s\n", defs); stream.printf ("%s\n", extends); } } public class GoWriter : ValabindWriter { public GoWriter() {} public override string get_filename (string base_name) { return base_name + ".go"; } private void clone_writer_config(ValabindWriter w) { w.modulename = this.modulename; w.library = this.library; w.include_dirs = this.include_dirs; w.namespaces = this.namespaces; w.init(this.vapidir, this.glibmode); foreach (var pkg in this.packages) { w.add_external_package(pkg); } foreach (var def in this.defines) { w.add_define(def); } foreach (var f in this.source_files) { w.add_source_file(f); } } public override void write (string file) { var f = new GenericClassFinder(); this.clone_writer_config(f); f.parse(); f.write(file); var g = new GoSrcWriter(); this.clone_writer_config(g); g.set_generic_class_instances(f.get_generic_class_instances()); g.parse(); g.write(file); } } valabind-1.8.0/main.vala000066400000000000000000000125151376122300700150760ustar00rootroot00000000000000/* Copyright GPL3 - 2009-2013 -- pancake */ private static string[] files; private static string vapidir; private static string library; private static bool show_version; private static bool glibmode; private static bool camelgetters; private static bool cxxmode; private static bool dlangoutput; private static bool cxxoutput; private static bool vlangoutput; private static bool nodeoutput; private static bool swigoutput; private static bool ctypesoutput; private static bool giroutput; private static bool gooutput; private static string modulename; private static string? output; [CCode (array_length = false, array_null_terminated = true)] private static string[] packages; [CCode (array_length = false, array_null_terminated = true)] private static string[] include_dirs; [CCode (array_length = false, array_null_terminated = true)] private static string[] namespaces; [CCode (array_length = false, array_null_terminated = true)] private static string[] defines; private const OptionEntry[] options = { { "define", 'D', 0, OptionArg.STRING_ARRAY, ref defines, "define SYMBOL", "SYMBOL" }, { "pkg", 0, 0, OptionArg.STRING_ARRAY, ref packages, "include binding for PACKAGE", "PACKAGE..." }, { "vapidir", 'V', 0, OptionArg.STRING, ref vapidir, "define alternative vapi directory", "VAPIDIR" }, { "include-dir", 'I', 0, OptionArg.STRING_ARRAY, ref include_dirs, "add include path", "INCLUDEDIR" }, { "version", 'v', 0, OptionArg.NONE, ref show_version, "show version information", null }, { "output", 'o', 0, OptionArg.STRING, ref output, "specify output file name", "OUTPUT" }, { "module", 'm', 0, OptionArg.STRING, ref modulename, "specify module name", "NAME" }, { "namespace", 'N', 0, OptionArg.STRING_ARRAY, ref namespaces, "include namespace in the output", "NSPACE" }, { "cxx-swig", 'x', 0, OptionArg.NONE, ref cxxmode, "generate C++ code for SWIG", null }, { "glib", 0, 0, OptionArg.NONE, ref glibmode, "call g_type_init before any constructor", null }, { "swig", 0, 0, OptionArg.NONE, ref swigoutput, "generate swig interface code", null }, { "camel-getters", 0, 0, OptionArg.NONE, ref camelgetters, "translate {get,set}_foo into {get,set}Foo", null }, { "node-ffi", 0, 0, OptionArg.NONE, ref nodeoutput, "generate node-ffi interface", null }, { "library", 'l', 0, OptionArg.STRING, ref library, "library to link", null }, { "ctypes", 0, 0, OptionArg.NONE, ref ctypesoutput, "generate python ctypes interface", null }, { "gir", 0, 0, OptionArg.NONE, ref giroutput, "generate GIR (GObject-Introspection-Runtime)", null }, { "cxx", 0, 0, OptionArg.NONE, ref cxxoutput, "generate C++ interface code", null }, { "dlang", 0, 0, OptionArg.NONE, ref dlangoutput, "generate D bindings", null }, { "go", 0, 0, OptionArg.NONE, ref gooutput, "generate Go bindings", null }, { "vlang", 0, 0, OptionArg.NONE, ref vlangoutput, "generate bindings for Vlang", null }, { "", 0, 0, OptionArg.FILENAME_ARRAY, ref files, "vala/vapi input files", "FILE FILE .." }, { null } }; int main (string[] args) { output = null; vapidir = "."; files = { "" }; try { var opt_context = new OptionContext ("- valabind"); opt_context.set_help_enabled (true); opt_context.add_main_entries (options, null); opt_context.parse (ref args); } catch (OptionError e) { stderr.printf ("%s\nTry --help\n", e.message); return 1; } if (show_version) { print ("%s\n", version_string); return 0; } if (modulename == null) error ("No modulename specified. Use --module or --help"); if (files.length == 0) error ("No files given"); ValabindWriter writer = null; int count = 0; if (swigoutput && count++ == 0) { writer = new SwigWriter (cxxmode); writer.add_define ("VALABIND_SWIG"); } if (nodeoutput && count++ == 0) { writer = new NodeFFIWriter (); writer.add_define ("VALABIND_NODEJS"); } if (ctypesoutput && count++ == 0) { writer = new CtypesWriter (); writer.add_define ("VALABIND_CTYPES"); } if (giroutput && count++ == 0) { writer = new GirWriter (); writer.add_define ("VALABIND_GIR"); } if (dlangoutput && count++ == 0) { writer = new DlangWriter (); writer.add_define ("VALABIND_DLANG"); } if (cxxoutput && count++ == 0) { writer = new CxxWriter (); writer.add_define ("VALABIND_CXX"); } if (vlangoutput && count++ == 0) { writer = new VlangWriter (); writer.add_define ("VALABIND_VLANG"); } if (gooutput && count++ == 0) { writer = new GoWriter (); writer.add_define ("VALABIND_GO"); } if (count == 0) error ("No output mode specified. Try --help\n"); else if (count > 1) error ("Cannot specify more than one output mode\n"); writer.modulename = modulename; writer.library = (library != null)? library: modulename; writer.include_dirs = include_dirs; writer.namespaces = namespaces; writer.camelgetters = camelgetters; writer.init (vapidir, glibmode); if (packages != null) foreach (var pkg in packages) writer.add_external_package (pkg); if (defines != null) { foreach (string define in defines) { writer.add_define (define); } } // TODO: passing more than one source doesnt seems to work :/ foreach (var file in files) { if (file.index_of (".vapi") == -1) { writer.pkgmode = true; writer.pkgname = file; } writer.add_source_file (file); } writer.parse (); if (output == null) output = writer.get_filename (modulename); writer.write (output); return 0; } valabind-1.8.0/meson.build000066400000000000000000000024661376122300700154530ustar00rootroot00000000000000project('valabind', 'c', 'vala', version: run_command('./configure', '-qV').stdout().strip()) add_project_arguments([ '--vapidir', join_paths(meson.current_source_dir(), 'vapi')], language: 'vala') files = [ 'config.vala', 'ctypeswriter.vala', 'cxxwriter.vala', 'dlangwriter.vala', 'vlangwriter.vala', 'girwriter.vala', 'gowriter.vala', 'nodeffiwriter.vala', 'swigwriter.vala', 'utils.vala', 'valabindwriter.vala', 'main.vala', ] cc = meson.get_compiler('c') valac = meson.get_compiler('vala') libvala_version = run_command(valac.cmd_array()[0], '--api-version').stdout().strip() libvala_dep = dependency('libvala-@0@'.format(libvala_version)) glib_dep = dependency('glib-2.0') gobject_dep = dependency('gobject-2.0') valaccodegen_dep = cc.find_library('valaccodegen', dirs : [libvala_dep.get_pkgconfig_variable('pkglibdir')]) executable( 'valabind', files, dependencies: [glib_dep, gobject_dep, libvala_dep, valaccodegen_dep], vala_args: ['--pkg', 'posix', '--includedir', '../private', '--vapidir', '../private', '--pkg', 'codegen'], include_directories: include_directories('../private'), install: true, install_rpath: libvala_dep.get_pkgconfig_variable('pkglibdir') ) install_data('valabind-cc', install_dir: get_option('bindir')) install_man('valabind.1', 'valabind-cc.1') valabind-1.8.0/nodeffiwriter.vala000066400000000000000000000354171376122300700170270ustar00rootroot00000000000000/* Copyright 2012-2015 -- pancake, eddyb, ritesh */ using Vala; public class NodeFFIWriter : ValabindWriter { GLib.List includefiles = new GLib.List (); string ?ns_pfx; string bind = ""; string enum_fmt = ""; string enum_vals = ""; public NodeFFIWriter () { } public override string get_filename (string base_name) { return base_name+".js"; } void add_includes (Symbol s) { foreach (string i in Vala.get_ccode_header_filenames (s).split (",")) { bool include = true; foreach (string j in includefiles) { if (i == j) { include = false; break; } } if (include) includefiles.prepend (i); } } string sep (string str, string separator) { if (str.length == 0) return str; char last = str[str.length-1]; if (last != '(' && last != '[' && last != '{') return str+separator; return str; } string type_name (DataType type, bool ignoreRef=false) { if (type == null) { warning ("Cannot resolve type"); return "throw TypeError('Unresolved type')"; } if (type is EnumValueType) return "_.int"; if (type is GenericType) return type.to_qualified_string (); if (type is DelegateType) { DelegateType _delegate = type as DelegateType; string ret = type_name (_delegate.get_return_type ()), args = ""; foreach (var param in _delegate.get_parameters ()) args = sep (args, ", ")+type_name (param.variable_type); return "_.delegate(%s, [%s])".printf (ret, args); } if (type is PointerType) return "_.ptr("+type_name ((type as PointerType).base_type, true)+")"; if (type is ArrayType) { ArrayType array = type as ArrayType; string element = type_name (array.element_type); int len = array_length(array); if (len < 0) return "_.ptr("+element+")"; return "_.array("+element+", %d)".printf (len); } if (!ignoreRef && (type is ReferenceType)) { string unref_type = type_name (type, true); // HACK just check for the string class instead (how?) if (unref_type == "_.CString") return unref_type; return "_.ref("+unref_type+")"; } string generic = ""; foreach (DataType t in type.get_type_arguments ()) generic = sep (generic, ", ") + type_name (t); string _type = type.to_string (); string local_ns_pfx = ns_pfx; #if VALA_0_48 if (type.type_symbol != null && type.type_symbol.parent_symbol is Namespace) { Namespace local_ns = (Namespace)type.type_symbol.parent_symbol; #else if (type.data_type != null && type.data_type.parent_symbol is Namespace) { Namespace local_ns = (Namespace)type.data_type.parent_symbol; #endif if (use_namespace(local_ns)) local_ns_pfx = local_ns.get_full_name()+"."; } // HACK find a better way to remove generic type args _type = _type.split ("<", 2)[0]; _type = _type.replace (local_ns_pfx, "").replace (".", ""); _type = _type.replace ("?",""); _type = _type.replace ("unsigned ", "u"); switch (_type) { case "gconstpointer": case "gpointer": return "_.ptr(_.void)"; case "gboolean": return "_.bool"; case "gchar": return "_.char"; case "gint": return "_.int"; case "guint": return "_.uint"; case "glong": return "_.long"; case "ut8": case "guint8": return "_.uint8"; case "ut16": case "guint16": return "_.uint16"; case "st32": case "gint32": return "_.int32"; case "ut32": case "guint32": return "_.uint32"; case "st64": case "gint64": return "_.int64"; case "ut64": case "guint64": return "_.uint64"; case "gfloat": return "_.float"; case "gdouble": return "_.double"; case "string": return "_.CString"; } _type = "_."+_type; if (generic != "") _type += "("+generic+")"; return _type; } new void visit_enum (Vala.Enum e, string pfx="") { add_includes (e); notice (">\x1b[1menum\x1b[0m "+e.get_full_name ()); if (pfx == "") enum_fmt += "exports.%s = {}/*types.Enum*/;\\n".printf (e.name); else bind = sep (bind, ",")+"\n\t\t$%s: {}/*types.Enum*/".printf (e.name); foreach (var v in e.get_values ()) { enum_fmt += "exports.%s%s.%s = %%d;\\n".printf (pfx, e.name, v.name); enum_vals += ","+Vala.get_ccode_name (v); } } public override void visit_struct (Struct s) { add_includes (s); notice (">\x1b[1mstruct\x1b[0m "+s.get_full_name ()); string name = s.get_full_name ().replace (ns_pfx, "").replace (".", ""); bind = sep (bind, ",\n")+"\t%s: function() {return [{".printf (name); foreach (Field f in s.get_fields ()) f.accept (this); bind = sep (bind, "\n\t")+"}, {"; // NOTE if m.accept (this) is used, it might try other functions than visit_method foreach (Method m in s.get_methods ()) m.accept (this); bind = sep (bind, "\n\t")+"}];}"; } public override void visit_class (Class c) { bool is_generic = false; add_includes (c); notice (">\x1b[1mclass\x1b[0m "+c.get_full_name ()); string name = c.get_full_name ().replace (ns_pfx, "").replace (".", ""); foreach (Struct s in c.get_structs ()) s.accept (this); foreach (Class k in c.get_classes ()) k.accept (this); bind = sep (bind, ",\n")+"\t%s: function(".printf (name); foreach (TypeParameter t in c.get_type_parameters ()) { is_generic = true; bind = sep (bind, ", ")+t.name; } bind += ") {return [{"; foreach (Field f in c.get_fields ()) f.accept (this); bind = sep (bind, "\n\t")+"}, {"; foreach (Vala.Enum e in c.get_enums ()) visit_enum (e, name+"."); // TODO use node-weak to call the free function on GC string? freefun = null; if (Vala.is_reference_counting (c)) freefun = Vala.get_ccode_unref_function (c); else freefun = Vala.get_ccode_free_function (c); if (freefun != null && freefun != "") { if (is_generic) name = name +"(G)"; bind = sep (bind, ",")+"\n\t\tdelete: ['%s', _.void, [_.ref(_.%s)]]".printf (freefun, name); } // NOTE if m.accept (this) is used, it might try other functions than visit_method foreach (Method m in c.get_methods ()) visit_method (m); bind = sep (bind, "\n\t")+"}];}"; } public override void visit_field (Field f) { string name = f.name; // HACK cannot use buffer as a field name with latest ref. if (name == "buffer") name = "buf"; bind = sep (bind, ",")+"\n\t\t%s: %s".printf (name, type_name (f.variable_type)); } public override void visit_method (Method m) { if (m.is_private_symbol () || m.name == "cast") return; add_includes (m); //notice (">\x1b[1mmethod\x1b[0m "+m.get_full_name ()); var parent = m.parent_symbol; string cname = Vala.get_ccode_name (m), name = m.name; bool is_static = (m.binding & MemberBinding.STATIC) != 0, is_constructor = (m is CreationMethod); bool parent_is_class = parent is Class || parent is Struct; // TODO: Implement contractual support // m.get_preconditions (); // m.get_postconditions (); if (parent_is_class && is_static) name = "$"+name; DataType this_type = m.this_parameter == null ? null : m.this_parameter.variable_type; string func = "\n\t\t"; if (is_constructor) { func += "$constructor: ['%s', %s, [".printf (cname, type_name (this_type)); } else { func += "%s: ['%s', %s, [".printf (name, cname, type_name (m.return_type)); if (this_type != null) func += type_name (this_type); } bool variadic = false; foreach (Vala.Parameter param in m.get_parameters ()) { // HACK is this the right way to detect variadic functions? if (param.ellipsis) { variadic = true; continue; } func = sep (func, ", ")+type_name (param.variable_type); } func += variadic ? "], 'variadic']" : "]]"; bind = sep (bind, ",")+func; if (parent_is_class && name == "iterator") bind += ",\n\t\tforEach: defaults.forEach"; } public override void visit_namespace (Namespace ns) { string name = ns.get_full_name (); bool use = use_namespace (ns); if (use) ns_pfx = name+"."; if (ns_pfx != null) { notice (">\x1b[1mns\x1b[0m "+name); add_includes (ns); } foreach (Namespace n in ns.get_namespaces ()) n.accept (this); if (ns_pfx != null) { if (!use) { name = name.replace (ns_pfx, "").replace (".", ""); bind = sep (bind, ",\n")+"\t$%s: function() {return {".printf (name); foreach (Method m in ns.get_methods ()) m.accept (this); foreach (Vala.Enum e in ns.get_enums ()) visit_enum (e, name+"."); bind = sep (bind, "\n\t")+"};}"; } else foreach (Vala.Enum e in ns.get_enums ()) visit_enum (e); foreach (Struct s in ns.get_structs ()) s.accept (this); foreach (Class c in ns.get_classes ()) c.accept (this); } //if (ns_pfx != null) // notice ("<\x1b[1mns\x1b[0m "+name); if (use) ns_pfx = null; } public override void write (string file) { var stream = FileStream.open (file, "w"); if (stream == null) error ("Cannot open %s for writing".printf (file)); context.root.accept (this); stream.puts (" /* DO NOT EDIT. Automatically generated by valabind from "+modulename+" */ var ffi = require('ffi'), ref = require('ref'), Struct = require('ref-struct'); var lib = new ffi.DynamicLibrary('lib"+modulename+"'+ffi.LIB_EXT); function Tname(T) { return T.hasOwnProperty('$name') ? T.$name : T.name; } var types = exports.type = {}; for(var i in ref.types) if(i != 'Utf8String') // Try not to trip the deprecated warning. types[i] = ref.types[i]; types.staticCString = function staticCString(N) { var r = Object.create(types.char); r.name = 'char['+N+']'; r.size *= N; r.get = function get(buf, offset) { if(buf.isNull()) return null; // TODO enforce maxLength of N return buf.readCString(offset); }; r.set = function set(buf, offset, val) { // TODO enforce maxLength of N return buf.writeCString(val, offset); }; return r; }; var ptrCache = [], ptrCacheTo = []; types.ptr = function PointerType(T) { T = ref.coerceType(T); if(T == types.char) return types.CString; var i = ptrCache.indexOf(T); return i === -1 ? ptrCacheTo[ptrCache.push(T)-1] = ref.refType(T) : ptrCacheTo[i]; }; var refCache = [], refCacheTo = []; types.ref = function ReferenceType(T) { T = ref.coerceType(T); var i = refCache.indexOf(T); if(i !== -1) return refCacheTo[i]; var p = types.ptr(T), r = refCacheTo[refCache.push(T)-1] = Object.create(p); r.indirection = 1; r.size = ref.sizeof.pointer; r.alignment = ref.alignof.pointer; r.name = Tname(T)+'&'; r.ffi_type = ffi.FFI_TYPES.pointer; r.get = function get(buf, offset) { buf = ref.get(buf, offset, p); if(buf.isNull()) return null; return buf.deref(); }; r.set = function set(buf, offset, val) { if(!val) return ref.set(buf, offset, null, p); if(!val.buffer) throw new TypeError('valabind ['+r.name+']#set got a bad value'); return ref.set(buf, offset, val.buffer, p); }; return r; }; types.array = function ArrayType(T, N) { T = ref.coerceType(T); if(T == types.char) return types.staticCString(N); var r = Object.create(T); r.size *= N; r.name = Tname(T)+'['+N+']'; function ArrayType(buffer, base) { this.buffer = buffer; this._base = base; } ArrayType.prototype = []; ArrayType.prototype.constructor = ArrayType; for(var i = 0; i < N; i++) Object.defineProperty(ArrayType.prototype, i, { get: function get() { return ref.get(this.buffer, this._base+T.size*i, T); }, set: function set(val) { return ref.set(this.buffer, this._base+T.size*i, val, T); }, enumerable: true }); r.get = function get(buf, offset) { return new ArrayType(buf, offset); }; r.set = function set(buf, offset, val) { for(var i in val) { if(isNaN(i = +i) || i >= N) continue; ref.set(buf, offset+T.size*i, val[i], T); } }; return r; }; types.delegate = function DelegateType(ret, args) { var p = types.ptr(types.void), r = Object.create(p); r.indirection = 1; r.name = Tname(ret)+'('+args.map(function(T) {return Tname(T);}).join(', ')+')'; r.get = function get(buf, offset) { buf = ref.get(buf, offset, p); if(buf.isNull()) return null; return ffi.ForeignFunction(buf, ret, args); }; r.set = function set(buf, offset, val) { return ref.set(buf, offset, ffi.Callback(ret, args, void(0), val)); }; return r; }; var defaults = { forEach: function forEach(callback, thisArg) { if({}.toString.call(callback) != '[object Function]') throw new TypeError(callback + ' is not a function'); for(var T = thisArg || T, iter = this.iterator(); iter; iter = iter.get_next()) callback.call(T, iter.get_data(), iter, this); } }; function bindings(s) { function method(name, ret, args, static, more) { var f = (more == 'variadic' ? ffi.VariadicForeignFunction : ffi.ForeignFunction)(lib.get(name), ret, args); if(static) return f; return function() { [].unshift.call(arguments, this); return f.apply(null, arguments); }; } function define(base, n, m) { var static = n[0] == '$' && ((n = n.slice(1)), true); static = static || base[0] == '$' && ((base = base.slice(1)), true); if(Array.isArray(m)) m = method(m[0], m[1], m[2], static, m[3]); static ? exports[base][n] = m : types[base].prototype[n] = m; } function makeGeneric(G, n) { var cache = [], cacheTo = []; types[n] = function() { var l = arguments.length, args = [], c; // Coerce all type arguments. for(var i = 0; i < l; i++) args[i] = ref.coerceType(arguments[i].$type || arguments[i]); // Look in the cache, if the generic was already built. for(var i = 0; i < cache.length; i++) { if((c = cache[i]).length !== l) continue; for(var j = 0; j < l && c[j] === args[j]; j++); if(j === l) return cacheTo[i]; } // Create the new generic. var generic = cacheTo[cache.push(args)-1] = Struct(), g = G.apply(null, args); generic.$name = n+'<'+args.map(function(T) {return Tname(T);}).join(', ')+'>'; // Define all the generic's propoerties. for(var i in g[0]) generic.defineProperty(i, g[0][i]); // Insert all the generic's methods. if(g[1]) for(var i in g[1]) { var m = g[1][i]; if(Array.isArray(m)) m = method(m[0], m[1], m[2], false, m[3]); generic.prototype[i] = m; } return generic; }; } for(var i in s) { if(s[i].length) makeGeneric(s[i], i); else if(i[0] == '$') exports[i.slice(1)] = {}; else exports[i] = types[i] = Struct(), types[i].$name = i; } for(var i in s) { if(s[i].length) { // TODO insert constructor delete s[i]; continue; } s[i] = s[i](); if(Array.isArray(s[i])) { for(var j in s[i][0]) types[i].defineProperty(j, s[i][0][j]); s[i] = s[i][1]; } } for(var i in s) { if('$constructor' in s[i]) { var ctor = s[i].$constructor; exports[i] = method(ctor[0], ctor[1], ctor[2], true, ctor[3]), exports[i].$type = types[i]; delete s[i].$constructor; } for(var j in s[i]) define(i, j, s[i][j]); } } var _ = types; bindings({\n"+bind+"\n}); " ); if (enum_fmt != "") { string enums_out = get_enums_for ("printf(\"%s\"%s)".printf ( enum_fmt, enum_vals), includefiles); stream.puts (enums_out); } } } valabind-1.8.0/private/000077500000000000000000000000001376122300700147535ustar00rootroot00000000000000valabind-1.8.0/private/codegen.vapi000066400000000000000000000153121376122300700172420ustar00rootroot00000000000000/* codegen.vapi generated by valac, do not modify. */ namespace Vala { [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_array_length (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string? get_ccode_array_length_expr (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string? get_ccode_array_length_name (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static double get_ccode_array_length_pos (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string? get_ccode_array_length_type (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_array_null_terminated (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_concrete_accessor (Vala.Property p); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_const_name (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_constructv_name (Vala.CreationMethod m); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_copy_function (Vala.TypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_default_value (Vala.TypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_delegate_target (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_delegate_target_name (Vala.Variable variable); [CCode (cheader_filename = "valacodegen.h")] public static double get_ccode_delegate_target_pos (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_destroy_function (Vala.TypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static double get_ccode_destroy_notify_pos (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string? get_ccode_dup_function (Vala.TypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_finish_instance (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_finish_name (Vala.Method m); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_finish_real_name (Vala.Method m); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_finish_vfunc_name (Vala.Method m); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_free_function (Vala.TypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_free_function_address_of (Vala.Class cl); [CCode (cheader_filename = "valacodegen.h")] public static double get_ccode_generic_type_pos (Vala.Method m); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_get_value_function (Vala.CodeNode sym); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_has_copy_function (Vala.Struct st); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_has_destroy_function (Vala.Struct st); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_has_generic_type_parameter (Vala.Method m); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_has_new_function (Vala.Method m); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_has_type_id (Vala.TypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_header_filenames (Vala.Symbol sym); [CCode (cheader_filename = "valacodegen.h")] public static double get_ccode_instance_pos (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_is_gboxed (Vala.TypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_lower_case_name (Vala.CodeNode node, string? infix = null); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_lower_case_prefix (Vala.Symbol sym); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_lower_case_suffix (Vala.Symbol sym); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_marshaller_type_name (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_name (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_no_accessor_method (Vala.Property p); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_param_spec_function (Vala.CodeNode sym); [CCode (cheader_filename = "valacodegen.h")] public static double get_ccode_pos (Vala.Parameter param); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_prefix (Vala.Symbol sym); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_quark_name (Vala.ErrorDomain edomain); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_real_name (Vala.Symbol sym); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_ref_function (Vala.TypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_ref_function_void (Vala.Class cl); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_ref_sink_function (Vala.ObjectTypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_sentinel (Vala.Method m); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_set_value_function (Vala.CodeNode sym); [CCode (cheader_filename = "valacodegen.h")] public static bool get_ccode_simple_generics (Vala.Method m); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_take_value_function (Vala.CodeNode sym); [CCode (cheader_filename = "valacodegen.h")] public static string? get_ccode_type (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_type_check_function (Vala.TypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_type_id (Vala.CodeNode node); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_type_name (Vala.Interface iface); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_unref_function (Vala.ObjectTypeSymbol sym); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_upper_case_name (Vala.Symbol sym, string? infix = null); [CCode (cheader_filename = "valacodegen.h")] public static string get_ccode_vfunc_name (Vala.Method m); [CCode (cheader_filename = "valacodegen.h")] public static bool is_reference_counting (Vala.TypeSymbol sym); } valabind-1.8.0/private/valacodegen.h000066400000000000000000000074311376122300700174010ustar00rootroot00000000000000/* valacodegen.h generated by valac, the Vala compiler, do not modify */ #ifndef __VALACODEGEN_H__ #define __VALACODEGEN_H__ #include #include #include #include #include #include #include #include G_BEGIN_DECLS gchar* vala_get_ccode_name (ValaCodeNode* node); gchar* vala_get_ccode_const_name (ValaCodeNode* node); gchar* vala_get_ccode_type_name (ValaInterface* iface); gchar* vala_get_ccode_lower_case_name (ValaCodeNode* node, const gchar* infix); gchar* vala_get_ccode_upper_case_name (ValaSymbol* sym, const gchar* infix); gchar* vala_get_ccode_header_filenames (ValaSymbol* sym); gchar* vala_get_ccode_prefix (ValaSymbol* sym); gchar* vala_get_ccode_lower_case_prefix (ValaSymbol* sym); gchar* vala_get_ccode_lower_case_suffix (ValaSymbol* sym); gchar* vala_get_ccode_ref_function (ValaTypeSymbol* sym); gchar* vala_get_ccode_quark_name (ValaErrorDomain* edomain); gboolean vala_is_reference_counting (ValaTypeSymbol* sym); gboolean vala_get_ccode_ref_function_void (ValaClass* cl); gboolean vala_get_ccode_free_function_address_of (ValaClass* cl); gchar* vala_get_ccode_unref_function (ValaObjectTypeSymbol* sym); gchar* vala_get_ccode_ref_sink_function (ValaObjectTypeSymbol* sym); gchar* vala_get_ccode_copy_function (ValaTypeSymbol* sym); gchar* vala_get_ccode_destroy_function (ValaTypeSymbol* sym); gchar* vala_get_ccode_dup_function (ValaTypeSymbol* sym); gchar* vala_get_ccode_free_function (ValaTypeSymbol* sym); gboolean vala_get_ccode_is_gboxed (ValaTypeSymbol* sym); gboolean vala_get_ccode_finish_instance (ValaCodeNode* node); gchar* vala_get_ccode_type_id (ValaCodeNode* node); gchar* vala_get_ccode_marshaller_type_name (ValaCodeNode* node); gchar* vala_get_ccode_get_value_function (ValaCodeNode* sym); gchar* vala_get_ccode_set_value_function (ValaCodeNode* sym); gchar* vala_get_ccode_take_value_function (ValaCodeNode* sym); gchar* vala_get_ccode_param_spec_function (ValaCodeNode* sym); gchar* vala_get_ccode_type_check_function (ValaTypeSymbol* sym); gchar* vala_get_ccode_default_value (ValaTypeSymbol* sym); gboolean vala_get_ccode_has_copy_function (ValaStruct* st); gboolean vala_get_ccode_has_destroy_function (ValaStruct* st); gdouble vala_get_ccode_instance_pos (ValaCodeNode* node); gboolean vala_get_ccode_array_length (ValaCodeNode* node); gchar* vala_get_ccode_array_length_type (ValaCodeNode* node); gboolean vala_get_ccode_array_null_terminated (ValaCodeNode* node); gchar* vala_get_ccode_array_length_name (ValaCodeNode* node); gchar* vala_get_ccode_array_length_expr (ValaCodeNode* node); gdouble vala_get_ccode_array_length_pos (ValaCodeNode* node); gdouble vala_get_ccode_delegate_target_pos (ValaCodeNode* node); gdouble vala_get_ccode_destroy_notify_pos (ValaCodeNode* node); gboolean vala_get_ccode_delegate_target (ValaCodeNode* node); gchar* vala_get_ccode_delegate_target_name (ValaVariable* variable); gdouble vala_get_ccode_pos (ValaParameter* param); gchar* vala_get_ccode_type (ValaCodeNode* node); gboolean vala_get_ccode_simple_generics (ValaMethod* m); gchar* vala_get_ccode_real_name (ValaSymbol* sym); gchar* vala_get_ccode_constructv_name (ValaCreationMethod* m); gchar* vala_get_ccode_vfunc_name (ValaMethod* m); gchar* vala_get_ccode_finish_name (ValaMethod* m); gchar* vala_get_ccode_finish_vfunc_name (ValaMethod* m); gchar* vala_get_ccode_finish_real_name (ValaMethod* m); gboolean vala_get_ccode_no_accessor_method (ValaProperty* p); gboolean vala_get_ccode_concrete_accessor (ValaProperty* p); gboolean vala_get_ccode_has_type_id (ValaTypeSymbol* sym); gboolean vala_get_ccode_has_new_function (ValaMethod* m); gboolean vala_get_ccode_has_generic_type_parameter (ValaMethod* m); gdouble vala_get_ccode_generic_type_pos (ValaMethod* m); gchar* vala_get_ccode_sentinel (ValaMethod* m); G_END_DECLS #endif valabind-1.8.0/swigwriter.vala000066400000000000000000000340701376122300700163600ustar00rootroot00000000000000/* Copyright 2009-2017 -- pancake, eddyb, ritesh */ using Vala; public class SwigWriter : ValabindWriter { public GLib.List includefiles = new GLib.List (); bool cxx_mode; string statics = ""; string structs = ""; string extends = ""; string enums = ""; string vectors = ""; string ?ns_pfx; public SwigWriter (bool cxx_mode) { this.cxx_mode = cxx_mode; } public override string get_filename (string base_name) { return base_name+".i"; } // FIXME duplicate from NodeFFIWriter and ctypeswriter void add_includes (Symbol s) { foreach (string i in Vala.get_ccode_header_filenames (s).split (",")) { bool include = true; foreach (string j in includefiles) { if (i == j) { include = false; break; } } if (include) includefiles.prepend (i); } } // FIXME duplicate from NodeFFIWriter string sep (string str, string separator) { if (str.length == 0) return str; char last = str[str.length-1]; if (last != '(' && last != '[' && last != '{') return str+separator; return str; } string get_alias (string oname) { string name = oname; if (this.camelgetters) { if (oname.has_prefix ("set_")) { var capital = "%c".printf (oname[4].toupper ()); return "set" + capital + oname.substring (5); } else if (oname.has_prefix ("get_")) { var capital = "%c".printf (oname[4].toupper ()); return "get" + capital + oname.substring (5); } } switch (oname) { case "call": case "lock": case "base": case "clone": case "break": case "delete": name = "_" + oname; break; case "continue": name = "cont"; break; } if (name != oname) { warning ("Method %s renamed to %s (don't ask where)".printf (oname, name)); } return name; } string type_name (DataType type, bool retType=false, bool ignoreRef=false) { if (type == null) { warning ("Cannot resolve type"); return "__UNRESOLVED_TYPE_OH_PLEASE_KILL_ME_NOW__"; } // HACK is this required? if (type is EnumValueType) { return "long int"; } // HACK needs proper generic support if (type is GenericType) { return "void*"; //return type.to_qualified_string (); } if (type is PointerType) { return type_name ((type as PointerType).base_type, retType, true)+"*"; } if (type is ArrayType) { ArrayType array = type as ArrayType; string element = type_name (array.element_type, retType); int len = array_length(array); if (len < 0 ) return element+"*"; // FIXME should this be element+"[]"? return element+"[%d]".printf (len); // FIXME will this work? } if (!ignoreRef && (type is ReferenceType)) { string unref_type = type_name (type, retType, true); // HACK just check for the string class instead (how?) if (unref_type == "char*" || unref_type == "const char*") return unref_type; // FIXME should it be & under C++? return unref_type+"*"; } string generic = ""; foreach (DataType t in type.get_type_arguments ()) { generic = sep (generic, ", ") + type_name (t); } string _type = type.to_string (); // HACK find a better way to remove generic type args _type = _type.split ("<", 2)[0]; _type = _type.replace (ns_pfx, "").replace (".", ""); _type = _type.replace ("?",""); _type = _type.replace ("unsigned ", "u"); switch (_type) { case "bool": case "gboolean": return "bool"; case "gconstpointer": case "gpointer": return "void*"; case "gchar": return "char"; /* Hack to bypass namespace rules in r2-bindings */ case "SDBSdb": return "Sdb"; case "gint": case "st32": case "int32": case "gint32": return "int"; case "uint": case "guint": case "ut32": case "uint32": case "guint32": return "unsigned int"; case "glong": return "long"; case "ut8": case "uint8": case "guint8": return "unsigned char"; case "guint16": case "uint16": return "unsigned short"; case "st64": case "int64": case "gint64": return "long long"; case "ut64": case "uint64": case "guint64": // HACK uint64_t doesn't work here because radare2 doesn't use the right type return "unsigned long long"; case "gdouble": return "double"; case "gfloat": return "float"; case "string": return retType ? "const char*" : "char*"; //case "const gchar*": // return "const char*"; // HACK needs proper generic support case "RList": if (generic != "") { return "std::vector<"+generic+">"; } break; case "SdbList": if (generic != "") { return "std::vector<"+generic+">"; } break; } return _type; } public override void visit_constant (Constant c) { var cname = Vala.get_ccode_name (c); extends += "%immutable "+c.name+";\n"; extends += "static const char *"+c.name+" = "+cname+";\n"; } public override void visit_enum (Vala.Enum e) { add_includes (e); /*extends += "enum %s {\n".printf (e.name); foreach (var v in e.get_values ()) extends += "\t%s = %s,\n".printf (v.name, Vala.get_ccode_name (v)); extends += "};\n";*/ } public override void visit_struct (Struct s) { add_includes (s); // FIXME does SWIG support actual namespaces? string name = s.get_full_name ().replace (ns_pfx, "").replace (".", ""); string cname = Vala.get_ccode_name (s); structs += "typedef struct %s {\n".printf (cname); foreach (Field f in s.get_fields ()) f.accept (this); structs += "} %s;\n".printf (name); var methods = s.get_methods (); if (methods.size > 0) { extends += "%%extend %s {\n".printf (name); // NOTE if m.accept (this) is used, it might try other functions than visit_method foreach (Method m in methods) visit_method (m); extends += "};\n"; } } public override void visit_class (Class c) { add_includes (c); // FIXME does SWIG support actual namespaces? string name = c.get_full_name ().replace (ns_pfx, "").replace (".", ""); string cname = Vala.get_ccode_name (c); structs += "typedef struct %s {\n".printf (cname); foreach (Field f in c.get_fields ()) f.accept (this); structs += "} %s;\n".printf (name); foreach (Vala.Enum e in c.get_enums ()) e.accept (this); string? freefun = null; if (Vala.is_reference_counting (c)) freefun = Vala.get_ccode_unref_function (c); else freefun = Vala.get_ccode_free_function (c); if (freefun == "") freefun = null; var methods = c.get_methods (); if (freefun != null || methods.size > 0) { extends += "%%extend %s {\n".printf (name); if (freefun != null && freefun != "") extends += "\t~%s() {\n\t\t%s(self);\n\t}\n".printf (name, freefun); // NOTE if m.accept (this) is used, it might try other functions than visit_method foreach (Method m in methods) visit_method (m); extends += "};\n"; } foreach (Struct s in c.get_structs ()) s.accept (this); foreach (Class k in c.get_classes ()) k.accept (this); } public override void visit_field (Field f) { if (f.is_private_symbol ()) return; // HACK don't output fields with C++ keywords as names. if (f.name == "class") return; string field = ""; DataType type = f.variable_type; if (type is ArrayType) { ArrayType array = type as ArrayType; string element = type_name (array.element_type); int len = array_length(array); if (len < 0) field = element + "* " + f.name; // FIXME should this be element+"[]"? field = element + " " + f.name + "[%d]".printf (len); // FIXME will this work? } else { /* HACK to support generics. this is r2 specific */ string _type = type.to_string (); if (_type.index_of ("RListIter") != -1) { field = "RListIter* " + f.name; } else if (_type.index_of ("RList") != -1) { field = "RList* " + f.name; } else if (_type.index_of ("SdbListIter") != -1) { field = "SdbListIter* " + f.name; } else if (_type.index_of ("SdbList") != -1) { field = "SdbList* " + f.name; } else { field = type_name (type) + " " + f.name; } } structs += "\t" + field + ";\n"; } public override void visit_method (Method m) { if (m.is_private_symbol ()) { return; } add_includes (m); string cname = Vala.get_ccode_name (m), alias = get_alias (m.name); var parent = m.parent_symbol; bool is_static = (m.binding & MemberBinding.STATIC) != 0, is_constructor = (m is CreationMethod); bool parent_is_class = parent is Class || parent is Struct; // TODO: Implement contractual support // m.get_preconditions (); // m.get_postconditions (); string ret = type_name (m.return_type, true); string def_args = "", call_args = ""; string applys = "", clears = ""; foreach (var foo in m.get_parameters ()) { //DataType? bar = foo.parameter_type; DataType? bar = foo.variable_type; if (bar == null) continue; string arg_name = get_alias (foo.name); string? arg_type = type_name (bar); /* TODO: move to type_name */ if (foo.direction != ParameterDirection.IN) { var var_name = ""; if (foo.direction == ParameterDirection.OUT) var_name = "OUTPUT"; else if (foo.direction == ParameterDirection.REF) var_name = "INOUT"; if (arg_type.index_of ("*") == -1) arg_type += "*"; applys += "\t%%apply %s %s { %s %s };\n".printf (arg_type, var_name, arg_type, arg_name); clears += "\t%%clear %s %s;\n".printf (arg_type, arg_name); } call_args = sep (call_args, ", ") + arg_name; def_args = sep (def_args, ", ") + arg_type + " " + arg_name; } if (is_constructor) { //externs += "extern %s* %s (%s);\n".printf (classcname, cname, def_args); var classname = parent.get_full_name ().replace (ns_pfx, "").replace (".", ""); extends += applys; extends += "\t%s (%s) {\n".printf (classname, def_args); if (context.is_defined ("GOBJECT")) extends += "\t\tg_type_init ();\n"; extends += "\t\treturn %s (%s);\n\t}\n".printf (cname, call_args); extends += clears; } else { string func = ""; string fbdy = ""; //if (is_static) //statics += "extern %s %s (%s);\n".printf (ret, cname, def_args); //else { if (!is_static) { if (call_args == "") call_args = "self"; else call_args = "self, " + call_args; } //externs += "extern %s %s (%s*, %s);\n".printf (ret, cname, classname, def_args); func += applys; //BEGIN HACK HACK HACK DIE IN A FIRE if (cxx_mode && ret.index_of ("std::vector") != -1) { ret = ret.replace (">*", ">").replace ("*>",">"); int ptr = ret.index_of ("<"); string iter_type = (ptr==-1) ? ret : ret[ptr : ret.length]; iter_type = iter_type.replace ("<", ""); iter_type = iter_type.replace (">", ""); iter_type = iter_type.replace ("*", ""); //ret = ret.replace ("*>", ">"); // TODO: Check if iter type exists before failing // instead of hardcoding the most common type '' // TODO: Do not construct a generic class if not supported // instead of failing. if (iter_type == "G*") /* No generic */ error ("Oops. No type support.\n"); // TODO: Do not recheck the return_type if (m.return_type.to_string ().index_of ("RList") != -1) { fbdy += "\t\t%s ret;\n".printf (ret); fbdy += "\t\tRList *list;\n"; fbdy += "\t\tRListIter *iter;\n"; fbdy += "\t\t%s *item;\n".printf (iter_type); fbdy += "\t\tlist = %s (%s);\n".printf (cname, call_args); fbdy += "\t\tif (list)\n"; fbdy += "\t\tfor (iter = list->head; iter && (item = (%s*)iter->data); iter = iter->n)\n".printf (iter_type); fbdy += "\t\t\tret.push_back(*item);\n"; fbdy += "\t\treturn ret;\n"; fbdy += "\t}\n"; } if (m.return_type.to_string ().index_of ("SdbList") != -1) { fbdy += "\t\t%s ret;\n".printf (ret); fbdy += "\t\tSdbList *list;\n"; fbdy += "\t\tSdbListIter *iter;\n"; fbdy += "\t\t%s *item;\n".printf (iter_type); fbdy += "\t\tlist = %s (%s);\n".printf (cname, call_args); fbdy += "\t\tif (list)\n"; fbdy += "\t\tfor (iter = list->head; iter && (item = (%s*)iter->data); iter = iter->n)\n".printf (iter_type); fbdy += "\t\t\tret.push_back(*item);\n"; fbdy += "\t\treturn ret;\n"; fbdy += "\t}\n"; } vectors += "\t%%template(%sVector) std::vector<%s>;\n".printf ( iter_type, iter_type); } else //END HACK HACK HACK DIE IN A FIRE fbdy += "\t\t%s%s(%s);\n\t}\n".printf ((ret == "void")?"":"return ", cname, call_args); if (is_static) func += "\tstatic %s %s(%s) {\n".printf (ret, alias, def_args); else func += "\t%s %s(%s) {\n".printf (ret, alias, def_args); func += fbdy; func += clears; if (!parent_is_class) { statics += func; extends += "\tstatic %s %s(%s);\n".printf (ret, alias, def_args); } else extends += func; } } public override void visit_namespace (Namespace ns) { string name = ns.get_full_name (); bool use = use_namespace (ns); if (use) ns_pfx = name+ "."; if (ns_pfx != null) add_includes (ns); foreach (var n in ns.get_namespaces ()) n.accept (this); if (ns_pfx != null) { foreach (Constant c in ns.get_constants ()) c.accept (this); //foreach (Field f in ns.get_fields ()) // f.accept (this); foreach (Vala.Enum e in ns.get_enums ()) e.accept (this); foreach (Struct s in ns.get_structs ()) s.accept (this); foreach (Class c in ns.get_classes ()) c.accept (this); //foreach (Method m in ns.get_methods ()) // m.accept (this); } if (use) ns_pfx = null; } public override void write (string file) { var stream = FileStream.open (file, "w"); if (stream == null) error ("Cannot open %s for writing".printf (file)); context.root.accept (this); stream.printf ("%%module %s\n%%{\n", modulename); if (!cxx_mode) stream.printf ( "\t#define bool int\n"+ "\t#define true 1\n"+ "\t#define false 0\n"); if (statics != "" || includefiles.length () > 0) { if (cxx_mode) stream.printf ("\textern \"C\" {\n"); foreach (string inc in includefiles) stream.printf ("\t#include <%s>\n", inc); stream.printf ("%s", statics); if (cxx_mode) stream.printf ("\t}\n\t#include \n"); } stream.printf ("%%}\n"); if (cxx_mode && vectors != "") stream.printf ("%%include \"std_vector.i\"\n\nnamespace std {\n%s}\n", vectors); stream.printf ("%s\n", structs); stream.printf ("%s\n", enums); stream.printf ("%s\n", extends); } } valabind-1.8.0/t/000077500000000000000000000000001376122300700135445ustar00rootroot00000000000000valabind-1.8.0/t/gir/000077500000000000000000000000001376122300700143255ustar00rootroot00000000000000valabind-1.8.0/t/gir/Makefile000066400000000000000000000000751376122300700157670ustar00rootroot00000000000000VB=../../valabind all: ${VB} --gir --module=Test Test.vapi valabind-1.8.0/t/gir/Test.vapi000066400000000000000000000004001376122300700161170ustar00rootroot00000000000000namespace Test { public static void hello (); [CCode (cname="getenv")] public static string getenv (string k); public class Animal { int legs; public Animal (); public bool can_walk (); } public struct Ball { int size; string color; } } valabind-1.8.0/t/go/000077500000000000000000000000001376122300700141515ustar00rootroot00000000000000valabind-1.8.0/t/go/camelcase.vapi000066400000000000000000000006501376122300700167500ustar00rootroot00000000000000// test for converting lowercase symbol names with a bunch of '_' // to CamelCase namespace Test { [CCode (lower_case_cprefix="test_")] namespace N { public static void fn1(); // --> Fn1 public static void fn_fn2(); // --> FnFn2 public static void fn_fn3_(); // --> FnFn3_ public static void fn_fn4_a(); // --> FnFn4A public static void fn6__(); // --> Fn6__ public static void fn_f7(); // --> FnF7 } } valabind-1.8.0/t/go/classes.vapi000066400000000000000000000011561376122300700164720ustar00rootroot00000000000000namespace Test { [Compact] [CCode (cprefix="a_", cname="A", free_function="a_free")] public class AA { public int m1; public char m2; public string m3; public int type; public AA(); public AA.from_string(string p1); public int f1(); public void f2(); public int f3(int p1); public string f4(string p1); public void *f5(void *p1); } // has no free function [Compact] [CCode (cprefix="b_", cname="B")] public class BB { public BB(); } // has unusually named free function [Compact] [CCode (cprefix="c_", cname="C", free_function="free_at_last")] public class CC { public CC(); } } valabind-1.8.0/t/go/enums.vapi000066400000000000000000000001231376122300700161550ustar00rootroot00000000000000namespace Test { [CCode (cprefix="NN_")] public enum N { A, B, C, D } } valabind-1.8.0/t/go/generic_names.vapi000066400000000000000000000007731376122300700176400ustar00rootroot00000000000000namespace Test { [Compact] [CCode (cprefix="l_", cname="L", free_function="l_free")] public class List { public List(); } [Compact] [CCode (cprefix="m_", cname="M", free_function="m_free")] public class Map { public Map(); } [Compact] [CCode (cprefix="a_", cname="A", free_function="a_free")] public class AA { public List m1; public Map m2; public List> m3; public Map> m4; public Map, int> m5; public AA(); } } valabind-1.8.0/t/go/generics.vapi000066400000000000000000000020111376122300700166230ustar00rootroot00000000000000namespace Test { [Compact] [CCode (cprefix="a_", cname="A", free_function="a_free")] public class AA { public int m1; public char m2; public string m3; public int type; public AA(); public AA.from_it(G p1); public G f1(); public void f2(); public G f3(G p1); public void f4(G *p1); public G *f5(); } [Compact] [CCode (cprefix="b_", cname="B", free_function="b_free")] public class BB { public AA m1; } [Compact] [CCode (cprefix="c_", cname="C", free_function="c_free")] public class CC { public G m1; public H m2; public CC(); } [Compact] [CCode (cprefix="D_", cname="D", free_function="d_free")] public class DD { public CC m1; } [Compact] [CCode (cprefix="e_", cname="E", free_function="e_free")] public class EE { public CC> m1; // note, AA already used [Compact] [CCode (cprefix="f_", cname="F", free_function="f_free")] public class FF { public CC> m1; // note, AA not yet defined } } } valabind-1.8.0/t/go/namespace_function.vapi000066400000000000000000000004761376122300700207020ustar00rootroot00000000000000namespace Test { [CCode (lower_case_cprefix="test_")] namespace N { public static void fn1(); public static int fn2(int p1, char p2, char *p3, int *p4); public static void fn3(out int p1); public static void fn4(string? p1=null); public static void fn5(out int p1=null); public static string fn6(); } } valabind-1.8.0/t/go/structs.vapi000066400000000000000000000002111376122300700165330ustar00rootroot00000000000000namespace Test { [CCode (cname="NN")] public struct N { public int f1; public char f2; public string f3; public int type; } } valabind-1.8.0/t/java/000077500000000000000000000000001376122300700144655ustar00rootroot00000000000000valabind-1.8.0/t/java/AsmExample.java000066400000000000000000000007631376122300700173720ustar00rootroot00000000000000import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Platform; import com.sun.jna.Pointer; import com.sun.jna.Structure; public class AsmExample { public static void main(String[] args) { RAsm a = new RAsm (); a.use ("x86"); a.set_bits (32); RAsmCode code = a.mdisassemble_hexstr ("909090"); System.out.println ("LEN "+ code.len); System.out.println ("CODE "+ code.buf_asm); code = a.massemble ("mov eax, 33"); System.out.println ("HEX "+code.buf_hex); } } valabind-1.8.0/t/java/Makefile000066400000000000000000000004111376122300700161210ustar00rootroot00000000000000WGET=wget --no-check-certificate all: jna.jar javac -cp jna.jar:. AsmExample.java RAsmCode.java RAsm.java java -cp jna.jar:. AsmExample jna.jar: ${WGET} https://raw.github.com/twall/jna/3.4.1/dist/jna.jar clean: rm -f *.class mrproper: clean rm -f jna.jar valabind-1.8.0/t/java/RAsm.java000066400000000000000000000016071376122300700161760ustar00rootroot00000000000000 import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Platform; import com.sun.jna.Pointer; import com.sun.jna.Structure; public class RAsm { public interface C extends Library { C lib = (C) Native.loadLibrary ("r_asm", C.class); Pointer r_asm_new (); int r_asm_use (Pointer p, String s); int r_asm_set_bits (Pointer p, int b); RAsmCode r_asm_mdisassemble_hexstr (Pointer p, String s); RAsmCode r_asm_massemble (Pointer p, String s); } Pointer self = null; public RAsm() { self = C.lib.r_asm_new (); } public boolean use (String str) { return (C.lib.r_asm_use (self, str) == 1); } public boolean set_bits (int b) { return (C.lib.r_asm_set_bits (self, b) == 1); } public RAsmCode mdisassemble_hexstr (String s) { return C.lib.r_asm_mdisassemble_hexstr (self, s); } public RAsmCode massemble(String s) { return C.lib.r_asm_massemble (self, s); } } valabind-1.8.0/t/java/RAsmCode.java000066400000000000000000000004201376122300700167610ustar00rootroot00000000000000import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Platform; import com.sun.jna.Pointer; import com.sun.jna.Structure; public class RAsmCode extends Structure { public int len; public String buf; public String buf_hex; public String buf_asm; } valabind-1.8.0/t/python/000077500000000000000000000000001376122300700150655ustar00rootroot00000000000000valabind-1.8.0/t/python/example.py000066400000000000000000000035401376122300700170740ustar00rootroot00000000000000# RAsm ctypes example # from ctypes import * from ctypes.util import find_library # helper functions lib = CDLL (find_library ("r_asm")) free = getattr (lib, "free") def register (self, name, cname, args, ret): g = globals () g['self'] = self if (ret!='' and ret[0]>='A' and ret[0]<='Z'): last = ".contents" ret = "POINTER("+ret+")" ret2 = "" else: last = "" ret2 = ret setattr (self,cname, getattr (lib, cname)) exec ("self.%s.argtypes = [%s]"%(cname, args)) if ret != "": exec ("self.%s.restype = %s"%(cname, ret), g) exec ("self.%s = lambda x: %s(self.%s(self._o, x))%s"% (name, ret2, cname, last),g) # define classes class RAsmCode(Structure): _fields_ = [ ("len", c_int), ("buf", c_char_p), ("buf_hex", c_char_p), ("buf_asm", c_char_p) ] class RAsm(Structure): _fields_ = [ ("bits", c_int), ("big_endian", c_int), ("syntax", c_int), ("pc", c_ulonglong) ] def __init__(self): r_asm_new = getattr (lib, "r_asm_new"); r_asm_new.restype = c_void_p self._o = r_asm_new () register (self, 'use', 'r_asm_use', 'c_void_p, c_char_p', 'c_bool') register (self, '__del__', 'r_asm_free', 'c_void_p', '') register (self, 'set_pc', 'r_asm_set_pc', 'c_void_p, c_ulonglong', 'c_bool') register (self, 'set_bits', 'r_asm_set_bits', 'c_void_p, c_int', 'c_bool') register (self, 'massemble', 'r_asm_massemble', 'c_void_p, c_char_p', 'RAsmCode') register (self, 'mdisassemble_hexstr', 'r_asm_mdisassemble_hexstr', 'c_void_p, c_char_p', 'RAsmCode') # Example a = RAsm() ok0 = a.use ("x86") ok1 = a.set_bits (32) ok2 = a.mdisassemble_hexstr ("909090") ok4 = a.set_pc (0x8048000) print (ok0, ok1, a, ok4) print ("Disasm len: ",ok2.len) print ("Disasm buf: ",ok2.buf_hex) print ("Disasm asm: ",ok2.buf_asm) print (ok2.buf_asm) # print (a.SYNTAX.INTEL) ok3 = a.massemble ("mov eax, 33") print ("Assemble hex:", ok3.buf_hex) a = None valabind-1.8.0/t/r2/000077500000000000000000000000001376122300700140675ustar00rootroot00000000000000valabind-1.8.0/t/r2/Makefile000066400000000000000000000007271376122300700155350ustar00rootroot00000000000000# XXX: Hardcoded path # HACK(eddyb): Relative path, more chance of success :) R2PATH:=../../../radare2 MOD:=r_bp NS:=Radare FLAGS:=$(MOD) $(MOD) -N$(NS) -I$(R2PATH)/libr/include --vapidir=$(R2PATH)/r2-bindings/vapi -l$(MOD) all: perl ruby python csharp perl: valabind-cc perl $(FLAGS) ruby: valabind-cc ruby $(FLAGS) python: rm -f r_bp.so valabind-cc python $(FLAGS) csharp: valabind-cc csharp $(FLAGS) mcs -main:test *.cs .PHONY: all perl ruby python csharp valabind-1.8.0/t/r2/test.cs000066400000000000000000000003241376122300700153740ustar00rootroot00000000000000using System; public class test { public static void Main () { Console.WriteLine ("Hello World\n"); RBreakpoint bp = new RBreakpoint (); bp.use ("x86"); bp.add_hw (0x8048400, 0, 0); bp.list (0); } } valabind-1.8.0/t/r2/test.java000066400000000000000000000003631376122300700157130ustar00rootroot00000000000000//import java.math; class test { public static void main (String[] args) { System.loadLibrary ("r_bp"); rBreakpoint bp = new rBreakpoint (); bp.use ("x86"); bp.add_sw (new java.math.BigInteger("0x804800"), 0, 0); bp.list (0); } } valabind-1.8.0/t/r2/test.pl000077500000000000000000000002411376122300700154030ustar00rootroot00000000000000#!/usr/bin/perl require 'r_bp.pm'; $a = new r_bp::RBreakpoint (); $a->use ("x86"); $a->add_hw (0x8048000, 10, 0); $a->add_sw (0x8048000, 10, 0); $a->list (0); valabind-1.8.0/t/r2/test.py000077500000000000000000000002171376122300700154230ustar00rootroot00000000000000#!/usr/bin/python from r_bp import * a = RBreakpoint () a.use ('x86') a.add_hw (0x8048000, 10, 0) a.add_sw (0x8048000, 10, 0) a.list (False) valabind-1.8.0/t/r2/test.rb000077500000000000000000000001601376122300700153730ustar00rootroot00000000000000#!/usr/bin/ruby require 'r_bp' bp = R_bp::RBreakpoint.new bp.use('x86'); bp.add_hw(0x8048400,0,0); bp.list(0) valabind-1.8.0/t/v/000077500000000000000000000000001376122300700140115ustar00rootroot00000000000000valabind-1.8.0/t/v/Makefile000066400000000000000000000002121376122300700154440ustar00rootroot00000000000000all: make -C ../.. ../../valabind -m system --vlang system.vapi rm -rf system mkdir -p system mv system.v system/lib.v v run main.v valabind-1.8.0/t/v/main.v000066400000000000000000000000711376122300700151220ustar00rootroot00000000000000import system fn main() { system.execute('uname -a') } valabind-1.8.0/t/v/system.vapi000066400000000000000000000001201376122300700162070ustar00rootroot00000000000000namespace System { [CCode (cname="system")] static int execute(string str); } valabind-1.8.0/t/vala/000077500000000000000000000000001376122300700144675ustar00rootroot00000000000000valabind-1.8.0/t/vala/Makefile000066400000000000000000000016621376122300700161340ustar00rootroot00000000000000VAPI=vstest.vapi VALBINDCCFLAGS=-I. `pkg-config --cflags --libs gobject-2.0` -I/usr/include -L. -lvstest all: valac -H vstest.h -C --vapi=${VAPI} --library=libvstest vstest.vala ${CC} -fPIC -shared vstest.c -o libvstest.so `pkg-config --cflags --libs gobject-2.0` valabind-cc python vstest -NFood ${VAPI} ${VALBINDCCFLAGS} -x cxx: valac -H vstest.h -C --vapi=${VAPI} --library=libvstest vstest.vala valabind-cc python vstest -NFood -x ${VAPI} ${VALBINDCCFLAGS} # compile vstest.cxx as included in test.cxx gcc -c vstest.c -I. `pkg-config gobject-2.0 --cflags --libs` g++ vstest.o test.cxx -I. `pkg-config gobject-2.0 --cflags --libs` #g++ test.cxx -I. `pkg-config gobject-2.0 --cflags --libs` test: LD_LIBRARY_PATH=$${PWD} python test.py foo: valabind-cc python vstest -NFood ${VAPI} -I. `pkg-config --cflags --libs gobject-2.0` clean: rm -f vstest.vapi vstest.h *.so vstest.cxx *.o *.i a.out vstest.c vstest.py* vstest_wrap.c* valabind-1.8.0/t/vala/test.cxx000066400000000000000000000002431376122300700161710ustar00rootroot00000000000000#include "vstest.cxx" int main () { vstestFoodElement *foo = new vstestFoodElement (); foo->say ("world"); foo->say ("cruel world"); delete foo; return 0; } valabind-1.8.0/t/vala/test.py000066400000000000000000000003041376122300700160150ustar00rootroot00000000000000import vstest #import gobject a = vstest.Element () a.say ("world") print ("--") a.say ("cruel world") print ("--") # Creating a 2nd element make it segfault b=vstest.Element () b.say ("salsa") valabind-1.8.0/t/vala/vstest.vala000066400000000000000000000004171376122300700166660ustar00rootroot00000000000000using GLib; public class Food.Element { public enum Counter { START, STOP, RESET } public Element () { print ("Element constructed\n"); } ~Element () { print ("Element destroyed\n"); } public void say (string str) { print (@"Hello $(str)\n"); } } valabind-1.8.0/utils.vala000066400000000000000000000042421376122300700153100ustar00rootroot00000000000000/* Copyright 2009-2015 -- pancake, ritesh */ #if W32 using Windows; #endif public void notice (string msg) { stderr.printf ("\x1b[34;1mNOTICE\x1b[0m %s\n", msg); } public void warning (string msg) { stderr.printf ("\x1b[33;1mWARNING\x1b[0m %s\n", msg); } public void error (string msg) { stderr.printf ("\x1b[31;1mERROR\x1b[0m %s\n", msg); #if W32 Windows.exit (1); #else Posix.exit (1); #endif } // TODO: check out if this is really required ? public int array_length (Vala.ArrayType array) { /* If valac >= 0.25 use this boilerplate to resolve the array length */ if (array.fixed_length && array.length is Vala.IntegerLiteral) { Vala.IntegerLiteral lit = (Vala.IntegerLiteral) array.length; return int.parse (lit.value); } return -1; } // TODO: make it reusable for other backends public string get_enums_for (string str, GLib.List includefiles) { string enums_exec, enums_out = ""; try { FileUtils.close (FileUtils.open_tmp ("vbeXXXXXX", out enums_exec)); } catch (FileError e) { error (e.message); } string[] gcc_args = {"gcc", "-x", "c", "-o", enums_exec, "-"}; foreach (var i in include_dirs) gcc_args += "-I"+i; try { Pid gcc_pid; int gcc_stdinfd; Process.spawn_async_with_pipes (null, gcc_args, null, SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD, null, out gcc_pid, out gcc_stdinfd); var gcc_stdin = FileStream.fdopen (gcc_stdinfd, "w"); if (gcc_stdin == null) throw new SpawnError.IO ("Cannot open gcc's stdin"); foreach (string i in includefiles) gcc_stdin.printf ("#include <%s>\n", i); gcc_stdin.printf ("int main(){%s;return 0;}\n", str); gcc_stdin = null; int status; #if W32 status = Windows.waitpid (gcc_pid); #else Posix.waitpid (gcc_pid, out status, 0); #endif Process.close_pid (gcc_pid); if (status != 0) throw new SpawnError.FAILED ("gcc exited with status %d", status); Process.spawn_sync (null, {enums_exec}, null, 0, null, out enums_out, null, out status); if (status != 0) throw new SpawnError.FAILED ("enums helper exited with status %d", status); } catch (SpawnError e) { FileUtils.unlink (enums_exec); error (e.message); } FileUtils.unlink (enums_exec); return enums_out; } valabind-1.8.0/valabind-cc000077500000000000000000000255051376122300700154010ustar00rootroot00000000000000#!/bin/sh # Copyleft valabind 2009-2017 pancake LANG=$1 MOD=$2 show_help () { echo "Usage: valabind-cc [lang] [module-name] [-flags] vapifile .." echo "Example: valabind-cc python r_bp -I/usr/include/r_bp r_bp.vapi" echo " lang: ctypes, python, dlang, nodejs, ocaml, guile, go, ruby," echo " perl, lua, java, csharp, ..." echo " --help,-h show this help message" echo " --version show version of valabind" echo " --vapidir=dir specify path to vapi files" echo " --glib assume vapi source is glib/gobject based" echo " --test [lang] test if it is possible to build" echo " -x generate C++ swig code" echo " -X output C++ instead of SWIG interface" echo " -I[path] add includepath for SWIGFLAGS and CFLAGS" echo " -V[path] add includepath for vapi files" echo " -L[path] append library path to LDFLAGS" echo " -l[lib] append to LDFLAGS to link a library" echo " -C do not compile, just let the .c/.cxx and .i files" echo " -n do not generate .i/.c/.cxx code, but compile it" echo " -N[nspace] include namespace in the output" echo " -D[SYMBOL] define vala symbol Symbol" echo " --nolibpython do not include libpython in Python flags" echo " Environment:" echo " VALABIND_DEBUG if not empty show stderr of commands" echo " PYTHON_CONFIG path to python-config program (select py2 or py3)" echo " SWIGFLAGS extra flags to be passed to swig" echo " SOEXT force extension for shared library (so, dll, dylib)" echo " SWIG path to swig program" exit 0 } OMOD=${MOD} [ -z "${SWIG}" ] && SWIG=swig [ -z "${LANG}" ] && show_help [ -z "${CC}" ] && CC=gcc [ -z "${CXX}" ] && CXX=g++ COMPILE=Yes ARG_VAPIDIR="" EXT="c" CXXOUT=0 NOGEN=0 if [ -z "${SOEXT}" ]; then if [ -n "`uname -a | grep -i darwin`" ]; then SOEXT="dylib" elif [ -n "`echo ${CC} | grep mingw`" ]; then SOEXT="dll" else SOEXT="so" fi fi if [ -z "${VALABIND_DEBUG}" ]; then NULLPIPE=">/dev/null" else NULLPIPE="" fi use_cxx() { CC="${CXX}" EXT="cxx" CFLAGS="${CFLAGS} ${CXXFLAGS}" SWIGFLAGS="-c++ ${SWIGFLAGS}" VALABINDFLAGS="-x ${VALABINDFLAGS}" } TEST=0 case "$1" in "--test") TEST=1 LANG=$2 ;; "--version") printf "valabind " ; valabind --version ${SWIG} -version | grep SWIG ${CC} --version | grep ${CC} exit 0 ;; "--help"|"-h") show_help ;; esac SWIG="${SWIG} -small" case "${LANG}" in ctypes) python2 --version >/dev/null 2>&1 || \ python --version > /dev/null 2>&1 || \ exit 1 ;; dlang) dmd --help >/dev/null 2>&1 || \ ldc2 --help >/dev/null 2>&1 || \ exit 1 ;; nodejs|node|node-ffi) node --version >/dev/null 2>&1 || exit 1 ;; ocaml) use_cxx echo "SWIG is buggy. Please set in ocamldec.swg the following line:" echo "#define caml_array_length swig_caml_array_length" OCAMLPATH=`ocamlc -where` CFLAGS="${CFLAGS} -I${OCAMLPATH}/ -Dcaml_array_length=caml_array_length__" LDFLAGS="${LDFLAGS} -L${OCAMLPATH} -lcamlrun" ;; guile) use_cxx CFLAGS="${CFLAGS} `guile-config compile 2>/dev/null`" LDFLAGS="${LDFLAGS} `guile-config link 2>/dev/null`" ;; python) use_cxx LDFLAGS="${LDFLAGS} -L/usr/local/lib -L/usr/pkg/lib" if [ -n "`echo ${CXX} | grep mingw`" ]; then CFLAGS="${CFLAGS} -I${HOME}/.wine/drive_c/Python27/include" LDFLAGS="${LDFLAGS} -L${HOME}/.wine/drive_c/Python27/libs -lpython27" else PYCFG="" for a in ${PYTHON_CONFIG} python-config python2-config python3-config ; do $a --help >/dev/null 2>&1 if [ $? = 0 ]; then PYCFG=$a break fi done if [ -z "$PYCFG" ]; then echo "No valid PYTHON_CONFIG command found" >&2 exit 1 fi CFLAGS="${CFLAGS} `$PYCFG --cflags | sed -e 's,-arch [^ ]*,,g'`" LDFLAGS="${LDFLAGS} `$PYCFG --ldflags| sed -e 's,-arch [^ ]*,,g'`" fi OMOD="_${MOD}" # XXX SWIGFLAGS="${SWIGFLAGS} -threads" ;; ruby) if [ "`ruby --version 2>/dev/null | grep 1.8`" ]; then RB_CFLAGS=`ruby -e 'require "mkmf"; print "-I" + RbConfig::CONFIG["archdir"];' 2>/dev/null` else if [ "`ruby --version 2>/dev/null | grep 1.9`" ]; then RB_CFLAGS=`ruby -e 'require "mkmf"; a=RbConfig::CONFIG["rubyhdrdir"]; print "-I#{a} -I#{a}/" + RbConfig::CONFIG["arch"];'` else if [ "`ruby --version 2>/dev/null | grep 2.0`" ]; then RB_CFLAGS=`ruby -e 'require "mkmf"; a=RbConfig::CONFIG["rubyhdrdir"]; print "-I#{a} -I#{a}/" + RbConfig::CONFIG["arch"];'` else if [ "`ruby --version 2>/dev/null | grep 2.1`" ]; then RB_CFLAGS=`ruby -e 'require "mkmf"; a=RbConfig::CONFIG["rubyhdrdir"]; print "-I#{a} -I#{a}/" + RbConfig::CONFIG["arch"];'` fi ; fi ; fi ; fi CFLAGS="${CFLAGS} ${RB_CFLAGS}" ;; perl) LC_ALL=C # fix anoying perl warning export LC_ALL CFLAGS="${CFLAGS} `perl -MExtUtils::Embed -e ccopts 2>/dev/null | sed -e 's,-arch [^ ]*,,g'`" LDFLAGS="${LDFLAGS} `perl -MExtUtils::Embed -e ldopts 2>/dev/null | sed -e 's,-arch [^ ]*,,g'`" ;; java) if [ -n "$JAVA_HOME" ]; then [ "`uname`" = Darwin ] && osname=darwin || osname=linux CFLAGS="${CFLAGS} -I${JAVA_HOME}/include -I${JAVA_HOME}/include/$osname" elif [ -f /opt/java/include/jni.h ]; then CFLAGS="${CFLAGS} -I/opt/java/include -I/opt/java/include/linux" fi ;; php5) CFLAGS="${CFLAGS} `php-config --includes 2>/dev/null` `pkg-config --libs libpng 2>/dev/null`" LDFLAGS="${LDFLAGS} `php-config --libs 2>/dev/null`" ;; lua) SOEXT=so LUAPKG=`pkg-config --list-all|awk '/lua|lua-/{print $1;}'` if [ -n "${LUAPKG}" ]; then CFLAGS="${CFLAGS} `pkg-config --cflags ${LUAPKG}`" LDFLAGS="${LDFLAGS} `pkg-config --libs ${LUAPKG}`" fi ;; go) ;; csharp) VALABINDFLAGS="--camel-getters ${VALABINDFLAGS}" ;; node-swig) SWIGFLAGS="-javascript" CFLAGS="${CFLAGS} -I/usr/include/node" ;; esac shift shift while : ; do [ -z "$1" ] && break if [ "`echo $1 | grep -- '^-I'`" ]; then CFLAGS="${CFLAGS} $1" SWIGFLAGS="$1 ${SWIGFLAGS}" VALABINDFLAGS="`echo $1|sed -e 's,^-I,-I ,'` ${VALABINDFLAGS}" elif [ "`echo $1 | grep -- '^-V'`" ]; then CFLAGS="${CFLAGS} $1" VALABINDFLAGS="`echo $1|sed -e 's,^-V,-V ,'` ${VALABINDFLAGS}" elif [ "`echo $1 | grep -- '--vapidir'`" ]; then ARG_VAPIDIR="`echo $1|sed -e 's,=, ,'`" elif [ "`echo $1 | grep -- '^-x'`" ]; then use_cxx elif [ "`echo $1 | grep -- '^-n'`" ]; then NOGEN=1 elif [ "`echo $1 | grep -- '^-N'`" ]; then VALABINDFLAGS="`echo $1|sed -e 's,^-N,-N ,'` ${VALABINDFLAGS}" elif [ "`echo $1 | grep -- '^-X'`" ]; then EXT="cxx" CXXOUT=1 elif [ "`echo $1 | grep -- '^-l'`" ]; then LDFLAGS="$1 ${LDFLAGS}" elif [ "`echo $1 | grep -- '^--glib'`" ]; then SWIGFLAGS="$1 ${SWIGFLAGS}" elif [ "`echo $1 | grep -- '^-L'`" ]; then LDFLAGS="$1 ${LDFLAGS}" elif [ "`echo $1 | grep -- '^-C'`" ]; then COMPILE="" elif [ "`echo $1 | grep -- '^-pthread'`" ]; then echo ignored $1 elif [ "`echo $1 | grep -- '^-D'`" ]; then VALABINDFLAGS="`echo $1|sed -e 's,^-D,-D ,'` ${VALABINDFLAGS}" elif [ "`echo $1 | grep -- '^--nolibpython'`" ]; then SEDFLAGS="-r" if [ -z "`sed --version 2>/dev/null | grep GNU`" ]; then SEDFLAGS="-E" fi LDFLAGS="$(echo ${LDFLAGS} | sed ${SEDFLAGS} 's,-lpython[0-9.]+,,g')" else FILES="$1 ${FILES}" fi shift done SWIGCPP="-DG_BEGIN_DECLS -DG_END_DECLS -DG_GNUC_CONST -DSWIG_PYTHON_SILENT_MEMLEAK" # strip problematic cflags. can be problematic if not used CFLAGS="`echo "${CFLAGS}" | sed -e 's,-pie,,g' -e 's,-PIE,,g'`" LDFLAGS="`echo "${LDFLAGS}" | sed -e 's,-pie,,g' -e 's,-PIE,,g'`" if [ "$CXXOUT" = 1 ]; then echo valabind -X ${VALABINDFLAGS} ${ARG_VAPIDIR} -o ${MOD}.i -m ${MOD} ${FILES} valabind -X ${VALABINDFLAGS} ${ARG_VAPIDIR} -o ${MOD}.cxx -m ${MOD} ${FILES} || exit 1 #TODO: #if [ -n "${COMPILE}" ]; then # echo ${CC} ${MOD}.cxx -fPIC -shared ${MOD}_wrap.${EXT} ${CFLAGS} -o ${OMOD}.${SOEXT} ${LDFLAGS} # ${CC} $@ -fPIC -shared ${MOD}_wrap.${EXT} ${CFLAGS} -o ${OMOD}.${SOEXT} ${LDFLAGS} || exit 1 #fi # echo ${CXX} ${MOD}.cxx $@ -fPIC -shared ${MOD}.cxx ${CXXFLAGS} ${CFLAGS} -o ${OMOD}.${SOEXT} ${LDFLAGS} # ${CXX} ${MOD}.cxx $@ -fPIC -shared ${MOD}.cxx ${CXXFLAGS} ${CFLAGS} -o ${OMOD}.${SOEXT} ${LDFLAGS} > /dev/null 2>&1 elif [ "$TEST" = 1 ]; then case "${LANG}" in ctypes) python2 --version > /dev/null 2>&1 || \ python --version > /dev/null 2>&1 || \ exit 1 ;; dlang) dmd --help >/dev/null 2>&1 || \ ldc2 --help >/dev/null 2>&1 || \ exit 1 ;; "nodejs"|"node"|"node-ffi") exec node --version > /dev/null 2>&1 ;; *) DIR=`mktemp -d /tmp/tmp.XXXXXX` if [ ! $? = 0 ]; then echo "Cannot create temporary directory" exit 1 fi cd ${DIR} MOD=test # hack to fix guile echo "%module ${MOD}" > ${MOD}.i eval echo ${SWIG} -O -o ${MOD}_wrap.${EXT} ${SWIGCPP} ${SWIGFLAGS} -${LANG} ${MOD}.i ${NULLPIPE} eval ${SWIG} -O -o ${MOD}_wrap.${EXT} ${SWIGCPP} ${SWIGFLAGS} -${LANG} ${MOD}.i ${NULLPIPE} if [ ! $? = 0 ]; then rm -rf ${DIR} ; exit 1 ; fi if [ "${EXT}" = cxx ]; then CFLAGS="${CFLAGS} ${CXXFLAGS}" fi eval echo ${CC} $@ -fPIC -shared ${MOD}_wrap.${EXT} ${CFLAGS} -o ${OMOD}.${SOEXT} ${LDFLAGS} ${NULLPIPE} eval ${CC} $@ -fPIC -shared ${MOD}_wrap.${EXT} ${CFLAGS} -o ${OMOD}.${SOEXT} ${LDFLAGS} ${NULLPIPE} if [ ! $? = 0 ]; then rm -rf ${DIR} ; exit 1 ; fi rm -rf ${DIR} ;; esac else case "${LANG}" in "ctypes") eval echo valabind --ctypes ${VALABINDFLAGS} ${ARG_VAPIDIR} -o ${MOD}.py -m ${MOD} ${FILES} eval valabind --ctypes ${VALABINDFLAGS} ${ARG_VAPIDIR} -o ${MOD}.py -m ${MOD} ${FILES} ${NULLPIPE} exit $? ;; "nodejs"|node|"node-ffi") eval echo valabind --node-ffi ${VALABINDFLAGS} ${ARG_VAPIDIR} -o ${MOD}.js -m ${MOD} ${FILES} eval valabind --node-ffi ${VALABINDFLAGS} ${ARG_VAPIDIR} -o ${MOD}.js -m ${MOD} ${FILES} ${NULLPIPE} exit $? ;; *) [ "${LANG}" = node-swig ] && LANG=node if [ "${NOGEN}" = 0 ]; then echo valabind --swig ${VALABINDFLAGS} ${ARG_VAPIDIR} -o ${MOD}.i -m ${MOD} ${FILES} valabind --swig ${VALABINDFLAGS} ${ARG_VAPIDIR} -o ${MOD}.i -m ${MOD} ${FILES} || exit 1 eval echo ${SWIG} -O -o ${MOD}_wrap.cxx ${SWIGCPP} ${SWIGFLAGS} -${LANG} ${MOD}.i ${SWIG} -O -o ${MOD}_wrap.cxx ${SWIGCPP} ${SWIGFLAGS} -${LANG} ${MOD}.i || exit 1 fi if [ -n "${COMPILE}" ]; then # Damn Python flags! CFLAGS="`echo ${CFLAGS} | sed -e 's,-mno[^\ ]*,,g' -e 's,-f[^\ ]*,,g'`" LDFLAGS="`echo ${LDFLAGS} | sed -e 's,-pagezero_size [^\ ]*,,g'`" LDFLAGS="`echo ${LDFLAGS} | sed -e 's,-image_base [^\ ]*,,g'`" if [ "${EXT}" = cxx ]; then CFLAGS="${CFLAGS} ${CXXFLAGS}" fi echo ${CC} $@ -fPIC -shared ${MOD}_wrap.${EXT} ${SWIGCPP} ${CFLAGS} -o ${OMOD}.${SOEXT} ${LDFLAGS} ${CC} $@ -fPIC -shared ${MOD}_wrap.${EXT} ${SWIGCPP} ${CFLAGS} -o ${OMOD}.${SOEXT} ${LDFLAGS} || exit 1 fi esac fi valabind-1.8.0/valabind-cc.1000066400000000000000000000016521376122300700155320ustar00rootroot00000000000000.Dd Nov 15,2012 .Dt valabind-cc \&1 "Valabind compiler frontend" .Os valabind-cc .Sh NAME . .Dd .Nm valabind-cc .Nd Vala to swig interface compiler .Pp .Sh SYNOPSIS .Nm valabind-cc .Ar language .Ar modname .Op Fl -version .Op Fl -vapidir Ar dir .Op Fl -glib .Op Fl -test Ar lang .Op Fl n .Op Fl x .Op Fl X .Op Fl I Ar path .Op Fl L Ar path .Op Fl l Ar libname .Op Fl D Ar SYMBOL .Op Fl C .Ar vapifile .Sh DESCRIPTION valabind-cc is a frontend for valabind, swig and the C compiler (gcc by default). .Pp It aims to simplify the use of all the wrapped tools and compile usable bindings for many programming languages. .Pp .Sh EXAMPLE valabind-cc python r_bp \-I/usr/include/r_bp r_bp.vapi .Pp .Sh ENVIRONMENT .Bl -tag -width Fl .Ar XDG_DATA_DIRS Standard freedesktop environment variable to point to the share prefix directory where vala looks for vapi files. .El .Sh SEE ALSO .Pp .Xr valabind(1) .Pp .Sh AUTHORS .Pp pancake <@nopcode.org> valabind-1.8.0/valabind.1000066400000000000000000000027521376122300700151510ustar00rootroot00000000000000.Dd Nov 15, 2012 .Dt valabind \&1 "Valabind manual page" .Os radare .Sh NAME .Nm valabind .Nd vala to swig interface conversor .Pp .Sh SYNOPSIS .Nm valabind .Op Fl h .Op Fl x .Op Fl v .Op Fl V Ar vapidir .Op Fl o Ar ofile .Op Fl m Ar modname .Op Fl p Ar profile .Op Fl N Ar namespace .Op Fl D Ar SYMBOL .Op Fl -swig .Op Fl -node-ffi .Op Fl -ctypes .Op Fl -gir .Op Fl -cxx .Ar vapifile .Sh DESCRIPTION Valabind is a program written in Vala that aims to generate nodejs, c++ or SWIG interfaces (.i) from a vala-generated or hand-made vapi files. .Pp SWIG opens the door to create bindings for Python, Perl, ruby, lua, and many other scripting languages. .Pp .Bl -tag -width Fl .It Fl h show help message .It Fl o Ar OUTPUT specify output file name .It Fl m Ar NAME specify module name .It Fl N Ar NS include given namespace for processing .It Fl D Ar SYMBOL define a preprocessor symbol inside Vala code .It Fl p Ar PROFILE select Vala profile (posix, gobject, dova) .It Fl x generate c++ code for SWIG bindings .It Fl v show version information .It Fl V Ar PATH specify an alternative vapidir path .El .Sh ENVIRONMENT .Bl -tag -width Fl .It XDG_DATA_DIRS Standard freedesktop environment variable to point to the share prefix directory where vala looks for vapi files. .El . .Sh HYPER-REFERENCES .Bl -tag -width Fl .It Vala http://live.gnome.org/Vala .It SWIG http://www.swig.org .El . .Sh SEE ALSO .Pp .Xr valabind-cc(1) .Pp . .Sh AUTHORS .Pp pancake .Pp Eduard Burtescu valabind-1.8.0/valabindwriter.vala000066400000000000000000000102571376122300700171700ustar00rootroot00000000000000/* Copyright 2009-2015 -- pancake */ using Vala; public class ValabindWriter : CodeVisitor { public string modulename; public string library; public bool pkgmode; public bool camelgetters; public string pkgname; [CCode (array_length = false, array_null_terminated = true)] public string[] include_dirs; [CCode (array_length = false, array_null_terminated = true)] public string[] namespaces; protected CodeContext context = new CodeContext (); protected string vapidir; protected GLib.List source_files = new GLib.List (); protected GLib.List packages = new GLib.List (); protected GLib.List defines = new GLib.List (); protected bool glibmode; public ValabindWriter () { } public void init (string vapidir, bool glibmode) { CodeContext.push (context); this.vapidir = vapidir; this.glibmode = glibmode; context.vapi_directories = { vapidir }; add_package (context, "glib-2.0"); add_package (context, "gobject-2.0"); /* vala 0.17 only support gobject profile */ if (glibmode) { context.add_define ("GOBJECT"); } #if VALA_0_50 // required to avoid ugly runtime errors #else context.profile = Profile.GOBJECT; #endif } public void parse () { var parser = new Parser (); parser.parse (context); if (!check ()) error ("Problems found, aborting..."); } public bool check () { context.check (); return (context.report.get_errors () == 0); } public void add_define (string define) { notice ("Symbol defined "+define); this.defines.append(define); context.add_define(define); } public bool add_external_package (string pkg) { notice ("Adding dependency "+pkg); this.packages.append(pkg); return context.add_external_package (pkg); } public bool add_source_file (string path) { if (path == "") { error ("Missing path to source vapi"); return false; } path.replace (".vapi", ""); foreach (string f in source_files) if (path == f) return false; bool found = FileUtils.test (path, FileTest.IS_REGULAR); if (found) { if (!pkgmode) context.add_source_file (new SourceFile ( context, SourceFileType.PACKAGE, path)); source_files.append(path); } else if (!add_package (context, path)) error ("Cannot find '%s'".printf (path)); return found; } /* Ripped from Vala Compiler */ private bool add_package (CodeContext context, string pkg) { if (pkg == "") { warning ("Empty add_package()?"); return true; } // ignore multiple occurences of the same package if (context.has_package (pkg)) return true; notice ("Adding dependency package "+pkg); var package_path = context.get_vapi_path (pkg); if (package_path == null) { warning ("Cannot find package path '%s'".printf (pkg)); return false; } if (pkgmode) add_source_file (package_path); context.add_source_file (new SourceFile (context, SourceFileType.PACKAGE, package_path)); context.add_package (pkg); var deps_filename = Path.build_filename (Path.get_dirname ( package_path), "%s.deps".printf (pkg)); if (FileUtils.test (deps_filename, FileTest.EXISTS)) { try { string deps_content; size_t deps_len; FileUtils.get_contents (deps_filename, out deps_content, out deps_len); foreach (string dep in deps_content.split ("\n")) { dep = dep.strip (); if (dep != "") { if (!add_package (context, dep)) Report.error (null, "%s, dependency of %s, not found in specified Vala API directories".printf (dep, pkg)); } } } catch (FileError e) { Report.error (null, "Unable to read dependency file: %s".printf (e.message)); } } return true; } protected bool use_namespace (Namespace ns) { if (namespaces == null) return true; string name = ns.get_full_name (); foreach (string i in namespaces) if(name == i) return true; return false; } public virtual void write (string file) { error ("ValabindWriter.write not implemented"); } public virtual string get_filename (string base_name) { warning ("ValabindWriter.get_filename not implemented"); return base_name; } /*public void emit_vapi (string? output, string file) { var vapi_writer = new CodeWriter (); vapi_writer.write_file (context, file); }*/ } valabind-1.8.0/vlangwriter.vala000066400000000000000000000637561376122300700165330ustar00rootroot00000000000000/* Copyleft 2020 -- pancake - this code is based on the gowriter */ using Vala; // This class is responsible for figuring out *what* to call things, // like, what an appropriate Go symbol name is, or the source C symbol in a struct. // The GoWriter decides *where* to place the names generated by this class. public class VlangNamer { private string pfx; private GLib.HashTable specializations = new GLib.HashTable(GLib.str_hash, GLib.str_equal); private GLib.List ordered_specializations = new GLib.List(); public VlangNamer(string pfx) { this.pfx = pfx; } public void add_specialization(TypeParameter t, DataType d) { specializations.insert(t.name, d); ordered_specializations.append(d); } // converts symbol names with underscores to camelCase. // this function should not be called directly. See `camelcase`. // allows trailing '_' characters. private static string cleanup_underscores(string name) { if (name.length == 0) { return ""; } else if (name.length == 1) { // accept trailing '_' return name; } else if (name.index_of("_") == -1) { return name; } else { // there is a '_' here somewhere int i = name.index_of("_"); if (i == name.length - 1) { // accept trailing '_' return name; } // there must be at least one more character // everything before the '_' string before = ""; if (i != 0) { before = name.substring(0, i); } // find next non-'_' character uppercase, or all '_' if thats all thats left // j will be the index of this character string next; int j = i + 1; while (true) { before = name.substring(0, i); if (name[j] != '_') { next = name.substring(j, 1); // .up(); break; } j++; if (j == name.length) { // only '_' remain next = name.substring(i, j - i); // so catch them all break; } } if (j >= name.length - 1) { return before + next; } else { // do rest of string return before + next + cleanup_underscores(name.substring(j + 1)); } } } public string get_field_name(Field f) { return f.name; } // renames the C symbol for a field // useful because Go convention is to rename "type" --> "_type" public string get_field_cname(Field f) { string n = Vala.get_ccode_name(f); if (n == "type") { return "_type"; } else { return n; } } public string get_method_name(Method m) { return m.name; } public string get_method_cname(Method m) { return Vala.get_ccode_name(m); } public string get_parameter_name(Vala.Parameter p) { return p.name; } public string get_enum_name(Enum e) { return e.name; } public string get_enum_value_name(Vala.EnumValue v) { return v.name; } public string get_enum_value_cname(Vala.EnumValue v) { return v.name; } public string get_constructor_name(Class c, Method m) { string postfix = ""; if (m.name != ".new") { postfix = m.name; } return "New%s%s".printf(get_class_name(c), postfix); } private string mangle_datatype(DataType d) { #if VALA_0_48 string ret = d.type_symbol.name; // i think should unify with get_type_declaration? #else string ret = d.data_type.name; // i think should unify with get_type_declaration? #endif if (d.get_type_arguments().size > 0) { foreach(var dd in d.get_type_arguments()) { ret += "_"; ret += mangle_datatype(dd); } } return ret; } // get the name of a class. If its a generic class, then // we use the set of specializations in our local context // to mangle the name. // this must keep in sync with get_specialized_type_declaration public string get_class_name(Class c) { bool has_specializations = false; foreach(var s in ordered_specializations) { has_specializations = true; break; } string postfix = ""; if (has_specializations) { foreach(DataType d in ordered_specializations) { postfix += "_"; postfix += mangle_datatype(d); } } return "%s%s%s".printf(this.pfx, c.name, postfix); } // get the name of an already specialized generic class. That is, // turning something like vapi: List into go: List_int. // this must be kept in sync with get_class_name public string get_specialized_type_declaration(DataType d) { return mangle_datatype(d); } public string get_class_cname(Class c) { return Vala.get_ccode_name(c); } public string get_struct_name(Struct s) { return "%s%s".printf(this.pfx, s.name); } public string get_struct_cname(Struct s) { return Vala.get_ccode_name(s); } public string get_namespace_name(Namespace ns) { return ns.name; } inline bool is_generic(string type) { // TODO: fix things so we don't need this return (type.index_of ("<") != -1 && type.index_of (">") != -1); } private string get_ctype (string _type) { string type = _type; string? iter_type = null; if (type == "null") { error ("Cannot resolve type"); } if (is_generic (type)) { int ptr = type.index_of ("<"); iter_type = (ptr==-1)?type:type[ptr:type.length]; iter_type = iter_type.replace ("<", ""); iter_type = iter_type.replace (">", ""); type = type.split ("<", 2)[0]; } type = type.replace ("?",""); switch (type) { case "gconstpointer": case "gpointer": case "void*": return "void*"; case "gsize": return "size_t"; case "gdouble": return "double"; case "gfloat": return "float"; case "ut8": case "uint8": case "guint8": return "byte"; case "gchar**": return "char **"; case "char": case "gchar": return "char"; case "gchar*": case "string": case "const gchar*": return "string"; // XXX lost const? case "void": return "void"; case "int[]": case "int": case "gint": return "int"; case "guint": return "uint"; case "glong": return "long"; case "st64": case "int64": case "gint64": return "long"; case "ut64": case "uint64": case "guint64": return "ulong"; /* XXX swig does not support unsigned char* */ case "uint8*": case "guint8*": return "byte*"; case "guint16": case "uint16": return "ushort"; case "ut32": case "uint32": case "guint32": return "unsigned int"; case "bool": // no conversion needed case "gboolean": return "bool"; // XXX bool? default: break; } return type; } private inline string strip_non_class_name(string s) { return s.substring(0, s.index_of_char('<')); } // `s` should not contain a specializer (<...>) private inline string strip_namespace(string s) { int i1 = s.last_index_of_char('.') + 1; return s.substring(i1); } // given a DataType symbol, return a string that contains the Go source code for // a type specifier of that type. private string get_type_declaration(DataType type) { string basic_name = type.to_string(); if (specializations.lookup(basic_name) != null) { // replace type specializations (things like "public G member1;" // NOTE: doesn't support some complex specializations, like public List member1;" DataType dt = specializations.lookup(basic_name); basic_name = dt.to_string(); } else if (type.to_string().index_of ("<") != -1) { basic_name = get_specialized_type_declaration(type); } // guess basic_name = strip_namespace(strip_non_class_name(basic_name)); string typename = get_ctype (basic_name); // TODO: why are we using ctype here? // we can typecheck to determine if this is a pointer, so throw away '*' typename = typename.replace("*", "").strip(); // if `type` is a pointer, then this will contain the appropriate '*' string maybe_pointer_sym = ""; // if `type` is an array, then this will contain the appropriate "[]" string maybe_array_sym = ""; if (type is PointerType) { // I suspect we don't support pointer-to-pointer if (typename == "void") { typename = "unsafe.Pointer"; // go specific hack type for void * // TODO: need to re-enable this somehow // this.needs_unsafe = true; maybe_pointer_sym = ""; } else { maybe_pointer_sym = "*"; } } if (type is ArrayType) { maybe_array_sym = "[]"; } return "%s%s%s".printf(maybe_array_sym, maybe_pointer_sym, typename); } public string get_field_type_declaration(Field f) { return get_type_declaration(f.variable_type); } public string get_parameter_type_declaration(Vala.Parameter p) { return get_type_declaration(p.variable_type); } public string get_method_return_type_declaration(Method m) { return get_type_declaration(m.return_type); } } // This class is responsible for figuring out *what* to call things, // like, what an appropriate V symbol name is, or the source C symbol in a struct. // The VWriter decides *where* to place the names generated by this class. public class VSrcWriter : ValabindWriter { public GLib.List includefiles = new GLib.List (); HashTable defined_classes = new HashTable (str_hash, str_equal); GLib.HashTable>> generic_classes = new GLib.HashTable>> (GLib.str_hash, GLib.str_equal); string classname = ""; string classcname; string defs = ""; string statics = ""; string extends = ""; string enums = ""; string nspace; bool needs_unsafe = false; // set to true if the 'unsafe' package needs to be imported because a void* pointer was encountered public VSrcWriter () {} string _indent = ""; // TODO(wb): removeme void debug(string s) { notice(_indent + s); } void indent() { _indent = _indent + " "; } void dedent() { _indent = _indent.substring(0, _indent.length - 2); } public void set_generic_class_instances(GLib.HashTable>> generic_classes) { this.generic_classes = generic_classes; } private bool is_target_file (string path) { foreach (var file in source_files) if (file == path) return true; return false; } public override void visit_source_file (SourceFile source) { if (is_target_file (source.filename)) { source.accept_children (this); } } private void process_includes (Symbol s) { debug("process_includes(sym: %s)".printf(s.name)); indent(); foreach (var foo in Vala.get_ccode_header_filenames (s).split (",")) { debug("include(%s)".printf(foo)); var include = true; foreach (var inc in includefiles) { if (inc == foo) { include = false; break; } } if (include) { includefiles.prepend (foo); } } dedent(); } private bool is_string(CodeNode t) { if (t is DataType) { DataType a = t as DataType; return a.to_string() == "string"; } else if (t is Field) { Field a = t as Field; return a.variable_type.to_string() == "string"; } else if (t is Vala.Parameter) { Vala.Parameter a = t as Vala.Parameter; return a.variable_type.to_string() == "string"; } else { warning("unexpected type to is_string"); return false; } } // here, we use explicit accessors and mutators to fixup accessibility. private string walk_field (VlangNamer namer, string owner_name, Field f) { string ret = ""; debug("walk_field(name: %s)".printf(f.name)); indent(); if (f.is_private_symbol()) { debug("private."); dedent(); return ret; } // TODO: handle generics. ATM, type of `public G data` becomes `func ... GetData() void` // TODO: make this a function `is_string` if (is_string(f)) { ret += "fn (s %s) Get%s() %s {\n".printf(owner_name, namer.get_field_name(f), namer.get_field_type_declaration(f)); ret += " return C.VString(s.%s)\n".printf(namer.get_field_cname(f)); ret += "}\n"; ret += "fn (s *%s) Set%s(a %s) {\n".printf(owner_name, namer.get_field_name(f), namer.get_field_type_declaration(f)); ret += " s.%s = C.CString(a)\n".printf(namer.get_field_cname(f)); ret += " return\n"; ret += "}\n"; } else { ret += "fn (s %s) Get%s() %s {\n".printf(owner_name, namer.get_field_name(f), namer.get_field_type_declaration(f)); ret += " return s.%s\n".printf(namer.get_field_cname(f)); ret += "}\n"; ret += "fn (s *%s) Set%s(a %s) {\n".printf(owner_name, namer.get_field_name(f), namer.get_field_type_declaration(f)); ret += " s.%s = a\n".printf(namer.get_field_cname(f)); ret += " return\n"; ret += "}\n"; } dedent(); return ret; } private string walk_class_field(VlangNamer namer, Class c, Field f) { return walk_field(namer, namer.get_class_name(c), f); } private string walk_struct_field(VlangNamer namer, Struct s, Field f) { return walk_field(namer, namer.get_struct_name(s), f); } private string walk_namespace_field(VlangNamer namer, Namespace ns, Field f) { return walk_field(namer, "Vns" + namer.get_namespace_name(ns), f); } private string walk_struct (VlangNamer namer, Struct s) { string ret = ""; debug("walk_struct(name: %s)".printf(s.name)); indent(); ret += "type %s C.%s\n".printf(namer.get_struct_name(s), namer.get_struct_cname(s)); foreach (var f in s.get_fields()) { ret += walk_struct_field(namer, s, f); } ret += "\n"; dedent(); return ret; } private string walk_enum (VlangNamer namer, Vala.Enum e) { string ret = ""; var pfx = Vala.get_ccode_prefix(e); debug("walk_enum(pfx: %s, name: %s)".printf(pfx, e.name)); indent(); ret += "const (\n"; foreach (var v in e.get_values()) { debug("enum(name: %s)".printf(v.name)); ret += " %s%s = C.%s%s\n".printf(pfx, namer.get_enum_value_name(v), pfx, namer.get_enum_value_cname(v)); } ret += ")\n"; ret += "type %s int\n\n".printf(namer.get_enum_name(e)); dedent(); return ret; } // is_string: if the parameter is a string // arg_name: the C symbol parameter name // maybe_pointer_sym: might contain a '*' if needed for the V symbol. Useful for `out` parameters. // arg_type: the parameter type in all its glory delegate string parameter_visitor(bool is_string, string maybe_pointer_sym, Vala.Parameter p); private string get_function_parameters(VlangNamer namer, Method f, parameter_visitor v) { string args = ""; bool first = true; foreach (var p in f.get_parameters ()) { string maybe_pointer_sym = ""; if (p.direction != ParameterDirection.IN) { // TODO: exploit multiple return values? if (p.direction == ParameterDirection.OUT) { if (! is_string(p)) { maybe_pointer_sym = "*"; } } else if (p.direction == ParameterDirection.REF) { if (! is_string(p)) { maybe_pointer_sym = "*"; } } } if (first) { first = false; } else { args += ", "; } // TODO: consider special handling of `uint8 *buf, int len`? args += v(is_string(p), maybe_pointer_sym, p); } return args; } // BUG: doesn't support '...' parameters private string get_function_declaration_parameters(VlangNamer namer, Method f) { parameter_visitor formatter = (is_string, maybe_pointer_sym, p) => { // what about array of char *? I think we have to let the caller deal with it // hopefully overflows don't happen here? return "%s %s%s".printf (namer.get_parameter_name(p), maybe_pointer_sym, namer.get_parameter_type_declaration(p)); }; return get_function_parameters(namer, f, formatter); } // BUG: doesn't support '...' parameters private string get_function_call_parameters(VlangNamer namer, Method f) { parameter_visitor formatter = (is_string, maybe_pointer_sym, p) => { if (is_string) { // what about array of char *? I think we have to let the caller deal with it // hopefully overflows don't happen here? // return "C.CString(%s)".printf (namer.get_parameter_name(p)); return "%s.str".printf (namer.get_parameter_name(p)); } else { return "%s".printf (namer.get_parameter_name(p)); } }; return get_function_parameters(namer, f, formatter); } private bool is_void_function(Method f) { return f.return_type.to_string() == "void"; } // see tests t/go/namespace_functions.vapi private string walk_function(VlangNamer namer, Namespace ns, Method f) { string ret = ""; string nsname = namer.get_namespace_name(ns); string cname = namer.get_method_cname(f); debug("walk_function(ns: %s, name: %s)".printf(nsname, cname)); indent(); if (f is CreationMethod) { warning("constructor where function expected"); } if (f.is_private_symbol ()) { debug("private."); dedent(); return ret; } string def_args = get_function_declaration_parameters(namer, f); string call_args = get_function_call_parameters(namer, f); if ( ! is_void_function(f)) { ret += "pub fn %s(%s) %s {\n".printf (namer.get_method_name(f), def_args, namer.get_method_return_type_declaration(f)); // ret += "fn (_ Vns%s) %s(%s) %s {\n".printf (nsname, namer.get_method_name(f), def_args, namer.get_method_return_type_declaration(f)); if (is_string(f.return_type)) { // we have to let the caller deal with array of char * // what happens if there are embedded nulls? // ret += " return C.VString(%s(%s))\n".printf (cname, call_args); ret += " return string(%s(%s))\n".printf (cname, call_args); } else { // TODO: what about void*? ret += " unsafe {return C.%s(%s)}\n".printf (cname, call_args); } } else { ret += "fn (_ Vns%s) %s(%s) {\n".printf (nsname, namer.get_method_name(f), def_args); ret += " %s(%s)\n".printf (cname, call_args); } ret += "}\n"; dedent(); return ret; } private string walk_method (VlangNamer namer, Class c, Method m) { string ret = ""; string classname = namer.get_class_name(c); string cname = namer.get_method_cname(m); debug("walk_method(ns: %s, name: %s)".printf(classname, cname)); indent(); // TODO: "unowned"/static methods if (m is CreationMethod) { warning("constructor where function expected"); } if (m.is_private_symbol ()) { debug("private."); dedent(); return ret; } string def_args = get_function_declaration_parameters(namer, m); string call_args = get_function_call_parameters(namer, m); ret += "fn (this *%s) %s(".printf(classname, namer.get_method_name(m)); if (def_args != "") { ret += "%s".printf(def_args); } ret += ") "; if ( ! is_void_function(m)) { ret += "%s ".printf(namer.get_method_return_type_declaration(m)); } ret += "{\n"; ret += " "; if ( ! is_void_function(m)) { ret += "return "; if (is_string(m.return_type)) { // TODO: use wrap_type function ret += "C.VString("; } ret += "%s(this".printf(cname); if (call_args != "") { ret += ", %s".printf(call_args); } ret += ")"; if (is_string(m.return_type)) { ret += ")"; } ret += "\n"; } else { ret += "%s(this".printf(cname); if (call_args != "") { ret += ", %s".printf(call_args); } ret += ")\n"; } ret += "}\n"; dedent(); return ret; } private string walk_constructor(VlangNamer namer, Class c, Method m, string free_function) { string ret = ""; string classname = namer.get_class_name(c); string cname = namer.get_method_cname(m); debug("walk_method(ns: %s, name: %s)".printf(classname, cname)); indent(); // TODO: "unowned"/static methods if (m.is_private_symbol ()) { debug("private."); dedent(); return ret; } ret += "fn %s(".printf(namer.get_constructor_name(c, m)); ret += "%s".printf(get_function_declaration_parameters(namer, m)); ret += ") *%s {\n".printf(classname); ret += " var ret *%s\n".printf(classname); ret += " ret = C.%s(".printf(cname); ret += "%s".printf(get_function_call_parameters(namer, m)); ret += ")\n"; if (free_function != "") { ret += " SetFinalizer(ret, func(r *%s) {\n".printf(classname); ret += " C.%s(r)\n".printf(free_function); ret += " })\n"; } ret += " return ret\n"; ret += "}\n"; dedent(); return ret; } private string get_class_src(VlangNamer namer, Class c) { string ret = ""; foreach (var k in c.get_structs ()) { ret += walk_struct (namer, k); } foreach (var k in c.get_classes ()) { ret += walk_class (k); } classname = namer.get_class_name(c); classcname = namer.get_class_cname(c); process_includes (c); if (defined_classes.lookup (classname)) { debug("already defined"); dedent(); return ret; } defined_classes.insert (classname, true); bool has_constructor = false; foreach (var m in c.get_methods ()) { if (m is CreationMethod) { has_constructor = true; break; } } ret += "type %s C.%s\n".printf(classname, classcname); foreach (var f in c.get_fields()) { ret += walk_class_field(namer, c, f); } foreach (var e in c.get_enums ()) { ret += walk_enum (namer, e); } foreach (var m in c.get_methods ()) { if ( ! (m is CreationMethod)) { ret += walk_method (namer, c, m); } else { string free_function = ""; if (Vala.is_reference_counting (c)) { string? freefun = Vala.get_ccode_unref_function (c); if (freefun != null && freefun != "") { free_function = freefun; } } else { // BUG?: this method always seems to return a free function (default: ${cprefix}_free) // even if there is no `free_function` defined in the `CCode` block // see test in t/go/classes.vapi string? freefun = Vala.get_ccode_free_function (c); if (freefun != null) { free_function = freefun; } } ret += walk_constructor(namer, c, m, free_function); } } ret += "\n"; dedent(); return ret; } private string walk_class (Class c) { string ret = ""; debug("walk_class(name: %s)".printf(c.name)); indent(); if (this.generic_classes.contains(c.name)) { debug("generic class"); indent(); unowned GLib.HashTable> specializations; specializations = this.generic_classes.lookup(c.name); specializations.foreach((k, v) => { debug("specialization: %s".printf(k)); indent(); // TODO: might need to change the prefix VlangNamer namer = new VlangNamer(""); GLib.List vv = v.copy(); foreach(var t in c.get_type_parameters()) { debug("%s -> %s".printf(t.name, vv.nth_data(0).to_string())); namer.add_specialization(t, vv.nth_data(0)); vv.delete_link(vv.nth(0)); // pop(0) } ret += "// %s<".printf(c.name); foreach(var t in v.copy()) { ret += t.to_string(); ret += ", "; } ret += ">\n"; ret += get_class_src(namer, c); dedent(); }); dedent(); } else { // TODO: might need to change the prefix VlangNamer namer = new VlangNamer(""); ret += get_class_src(namer, c); } dedent(); return ret; } // go doesn't really support namespaces. Often code is namespaced by // directory hierarchy, but thats for code organization. // we eat namespaces here, as they don't generate anything besides their children. public override void visit_namespace (Namespace ns) { string ret = ""; debug("walk_namespace(name: %s)".printf(ns.name)); indent(); if (ns.name == "") { return; } classname = ""; SourceReference? sr = ns.source_reference; if (sr == null || !is_target_file (sr.file.filename)) { // TODO: should this be &&? dedent(); return; } nspace = ns.name; process_includes (ns); foreach (var e in ns.get_enums ()) { // enums will float to the top-level "namespace" in V, since we aren't doing namespaces. ret += walk_enum (new VlangNamer(ns.name == modulename ? ns.name : ""), e); } foreach (var c in ns.get_structs()) { ret += walk_struct(new VlangNamer(ns.name == modulename ? ns.name : ""), c); } if (ns.get_methods().size + ns.get_fields().size > 0) { // V only does namespacing through file system paths, whish is // probably not appropriate/feasible here // so we fake it by creating a new type, and one instance of it, // and attach the functions to it. // Note, this doesn't work for nested namespaces, but its better than nothing. // // for example: // namespace N { public static void fn1(); } // // becomes: // type VnstN int // func (_ VnsN) Fn1() { fn1() } // var N VnsN // // so a user can do: // import "/some/path/test" // test.N.Fn() string fake_ns_name = "Vns%s".printf(ns.name); ret += "struct %s {}\n".printf(fake_ns_name); foreach (var c in ns.get_fields()) { ret += walk_namespace_field(new VlangNamer(ns.name == modulename ? ns.name : ""), ns, c); } foreach (var m in ns.get_methods()) { ret += walk_function(new VlangNamer(ns.name == modulename ? ns.name : ""), ns, m); } // ret += "var %s %s\n".printf(ns.name, fake_ns_name); ret += "type %s = %s\n".printf(ns.name, fake_ns_name); ret += "\n"; } foreach (var c in ns.get_classes ()) { ret += walk_class (c); //ns.name, c); } dedent(); defs += ret; } public override void write (string file) { var stream = FileStream.open (file, "w"); if (stream == null) { error ("Cannot open %s for writing".printf (file)); } // before the `pre` stuff because we need `includefiles` to be populated. context.accept (this); var pre = "module %s\n".printf(modulename); pre += "\n"; // pre += "#pkgconfig %s\n".printf(modulename); foreach (var inc in includefiles) { pre += "#include \"%s\"\n".printf(inc); } if (this.needs_unsafe) { // pre += "import \"unsafe\"\n"; } stream.printf ("/* valabind autogenerated V bindings for %s */\n".printf (modulename)); stream.printf ("%s\n", pre); stream.printf ("%s\n", enums); stream.printf ("%s\n", statics); stream.printf ("%s\n", defs); stream.printf ("%s\n", extends); } } public class VlangWriter : ValabindWriter { public VlangWriter() {} public override string get_filename (string base_name) { return base_name + ".v"; } private void clone_writer_config(ValabindWriter w) { w.modulename = this.modulename; w.library = this.library; w.include_dirs = this.include_dirs; w.namespaces = this.namespaces; w.init(this.vapidir, this.glibmode); foreach (var pkg in this.packages) { w.add_external_package(pkg); } foreach (var def in this.defines) { w.add_define(def); } foreach (var f in this.source_files) { w.add_source_file(f); } } public override void write (string file) { var f = new GenericClassFinder(); this.clone_writer_config(f); f.parse(); f.write(file); var g = new VSrcWriter(); this.clone_writer_config(g); g.set_generic_class_instances(f.get_generic_class_instances()); g.parse(); g.write(file); } } valabind-1.8.0/windows.c000066400000000000000000000006151376122300700151410ustar00rootroot00000000000000/* Copyleft 2015 -- pancake */ #include void w32_exit(int x) { ExitProcess (x); } int w32_waitpid (int processId) { HANDLE nProc; DWORD dwExitCode; nProc = OpenProcess (PROCESS_ALL_ACCESS, TRUE, processId); if (nProc != NULL) { GetExitCodeProcess (nProc, &dwExitCode); if (dwExitCode == STILL_ACTIVE ) return dwExitCode; //RC_PROCESS_EXIST; } return -1; } valabind-1.8.0/windows.vapi000066400000000000000000000002211376122300700156470ustar00rootroot00000000000000[CCode (cheader_filename="windows.h", cname="w32")] namespace Windows { public static int waitpid(int pid); public static void exit(int rc); }