Compare commits

...

9 Commits

22 changed files with 2193 additions and 1358 deletions

233
LICENSE
View File

@ -1,232 +1,7 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (c) 2026 Zongor
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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.
undar-lang
Copyright (C) 2025 zongor
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
undar-lang Copyright (C) 2025 zongor
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -71,7 +71,7 @@ cd undar-lang && ./build
* License
[[./LICENSE][GPLv3]]
[[./LICENSE][MIT]]
* Inspirations
@ -79,9 +79,9 @@ cd undar-lang && ./build
- [[https://en.wikipedia.org/wiki/Lisp_(programming_language)][Lisp]] : REPL, introspection.
- [[https://fortran-lang.org/][Fortran]] : Array semantics.
- [[https://en.wikipedia.org/wiki/C_(programming_language)][C]] / [[https://ziglang.org/][Zig]] : Efficentcy, simplicity.
- [[https://lua.org][Lua]] - Friendly syntax, portable, and minimalism.
- [[https://www.craftinginterpreters.com/the-lox-language.html][Lox]] - The start of my programming language creation journey.
- [[https://wiki.xxiivv.com/site/uxn.html][Uxn]] - Major inspiration, espeically around the design for devices.
- [[http://duskos.org/][Dusk OS]] - A much better system for doing permacomputing.
- [[https://lua.org][Lua]] - Friendly syntax, portable, embedable, and minimalist.
- [[https://wiki.xxiivv.com/site/uxn.html][Uxn]] - Major inspiration, compatability for 2D icons, fonts, and the like.
- [[http://duskos.org/][Dusk OS]] - Ideas about permacomputing.
- [[https://doc.cat-v.org/inferno/4th_edition/dis_VM_specification][Dis VM]] - Ideas on VM structure
- [[https://www.craftinginterpreters.com/the-lox-language.html][Crafting Interpreters]] - Fantastic book about creating a compiler. Adapted code for the parser and compiler.
- Retro Systems - N64, PS1, Mac Classic, Windows 95, Especially Classic MacOS UI esthetics

View File

@ -1,26 +1,76 @@
#include "../../../vm/vm.h"
#include "../../../tools/compiler/compiler.h"
#include <SDL2/SDL.h>
#include <stdio.h>
#include <string.h>
#define CODE_SIZE 8192
#define MEMORY_SIZE 65536
#define CODE_SIZE 8192
#define STACK_SIZE 1024
u8 lmem[MEMORY_SIZE] = {0};
u32 lcode[CODE_SIZE] = {0};
u8 lcode[CODE_SIZE] = {0};
u32 lstack[STACK_SIZE] = {0};
Frame lframes[STACK_SIZE] = {0};
void reset() {
pc = 0;
cp = 0;
mp = 0;
fp = 0;
sp = 0;
interrupt = 0;
status = 0;
}
bool init_vm() {
mem = lmem;
memset(mem, 0, MEMORY_SIZE*sizeof(u8));
code = lcode;
mp = 0;
cp = 0;
pc = 0;
interrupt = 0;
stack = lstack;
frames = lframes;
reset();
return true;
}
u32 syscall(u32 id, u32 args, u32 mem_ptr) {
return 0; // success
void error(const char* msg) {
printf("%s", msg);
}
bool table_realloc(ScopeTable *table) {
USED(table);
// static so do nothing;
return true;
}
u32 syscall(u32 id, u32 mem_ptr) {
u32 size;
switch(id) {
case SYSCALL_CONSOLE_WRITE: {
u32 size = *(u32*)&mem[mem_ptr];
u8 *ptr = &mem[mem_ptr + 4];
for (u32 i = 0; i < size; i++) {
putchar(*(ptr++));
}
return 0;
}
case SYSCALL_CONSOLE_READ: {
u8 *ptr = &mem[mp];
mcpy(ptr, &size, sizeof(u32));
ptr += 4;
for (u32 i = 0; i < size; i++) {
u8 ch = getchar();
if (ch == '\0')
break;
if (ch == '\n')
break;
*(ptr++) = ch;
}
ptr[size] = '\0';
mp += 4 + size + 1;
}
}
return 1; // generic error
}
i32 main() {

View File

@ -1,27 +1,47 @@
#include "../../../vm/vm.h"
#include "../../../tools/compiler/compiler.h"
#include <stdio.h>
#include <string.h>
#define CODE_SIZE 8192
#define MEMORY_SIZE 65536
#define CODE_SIZE 8192
#define STACK_SIZE 1024
u8 lmem[MEMORY_SIZE] = {0};
u32 lcode[CODE_SIZE] = {0};
u8 lcode[CODE_SIZE] = {0};
u32 lstack[STACK_SIZE] = {0};
Frame lframes[STACK_SIZE] = {0};
void reset() {
pc = 0;
cp = 0;
mp = 0;
fp = 0;
sp = 0;
interrupt = 0;
status = 0;
}
bool init_vm() {
mem = lmem;
memset(mem, 0, MEMORY_SIZE*sizeof(u8));
code = lcode;
lc = 0;
mp = 0;
cp = 0;
pc = 0;
interrupt = 0;
status = 0;
stack = lstack;
frames = lframes;
reset();
return true;
}
u32 syscall(u32 id, u32 size, u32 mem_ptr) {
USED(size);
void error(const char* msg) {
printf("%s", msg);
}
bool table_realloc(ScopeTable *table) {
USED(table);
// static so do nothing;
return true;
}
u32 syscall(u32 id, u32 mem_ptr) {
u32 size;
switch(id) {
case SYSCALL_CONSOLE_WRITE: {
u32 size = *(u32*)&mem[mem_ptr];
@ -51,81 +71,86 @@ u32 syscall(u32 id, u32 size, u32 mem_ptr) {
return 1; // generic error
}
void test_add_two_num() {
i32 main_local_count = 5;
mp += (4 * main_local_count);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 0, 1);
code[cp++] = ENCODE_B(OP_PUSH, 0, 0);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 1, 1);
code[cp++] = ENCODE_B(OP_PUSH, 1, 0);
i32 add = cp + 5;
code[cp++] = ENCODE_B(OP_LOAD_IMM, 2, add);
//static void repl() {
// ScopeTable st;
// char line[1024];
// for (;;) {
// printf("> ");
//
// if (!fgets(line, sizeof(line), stdin)) {
// printf("\n");
// break;
// }
//
// reset();
//
// compile(&st, line);
//
// while(step_vm()) {}
//
// syscall(SYSCALL_CONSOLE_WRITE, stack[0]);
// }
//}
code[cp++] = ENCODE_A(OP_CALL, 2, 3, 0);
code[cp++] = ENCODE_A(OP_INT_TO_STR, 4, 3, 0);
code[cp++] = ENCODE_A(OP_SYSCALL, SYSCALL_CONSOLE_WRITE, 1, 4);
code[cp++] = ENCODE_A(OP_HALT, 0, 0, 0);
void fib() {
u8 fib_ptr = 10;
code[cp++] = OP_PUSH_8;
code[cp++] = 35;
code[cp++] = OP_PUSH_8;
code[cp++] = fib_ptr;
code[cp++] = OP_CALL;
code[cp++] = OP_INT_TO_STR;
code[cp++] = OP_PUSH_8;
code[cp++] = SYSCALL_CONSOLE_WRITE;
code[cp++] = OP_SYSCALL;
code[cp++] = OP_HALT;
/* fib (int n) int */
code[cp++] = OP_SET_IMM;
code[cp++] = 0;
/* if (n < 2) { */
code[cp++] = OP_GET_IMM;
code[cp++] = 0;
code[cp++] = OP_PUSH_8;
code[cp++] = 2;
code[cp++] = OP_LTS;
code[cp++] = OP_PUSH_8;
u8 if_true = cp + 5;
code[cp++] = if_true;
code[cp++] = OP_JNZ;
code[cp++] = OP_PUSH_8;
u8 if_false = cp + 5;
code[cp++] = if_false;
code[cp++] = OP_JMP;
code[cp++] = OP_GET_IMM;
code[cp++] = 0;
code[cp++] = OP_RETURN;
code[cp++] = OP_GET_IMM;
code[cp++] = 0;
code[cp++] = OP_PUSH_8;
code[cp++] = 2;
code[cp++] = OP_SUB_INT;
code[cp++] = OP_PUSH_8;
code[cp++] = fib_ptr;
code[cp++] = OP_CALL;
code[cp++] = OP_GET_IMM;
code[cp++] = 0;
code[cp++] = OP_PUSH_8;
code[cp++] = 1;
code[cp++] = OP_SUB_INT;
code[cp++] = OP_PUSH_8;
code[cp++] = fib_ptr;
code[cp++] = OP_CALL;
code[cp++] = OP_ADD_INT;
code[cp++] = OP_RETURN;
/* add */
code[cp++] = ENCODE_A(OP_ADD_INT, 2, 1, 0);
code[cp++] = ENCODE_B(OP_RETURN, 2, 0);
}
void test_fibonacci() {
i32 fib = 7;
i32 base_case = 21;
/* function main() */
i32 main_local_count = 4;
mp += (4 * main_local_count);
/* fib(35) */
code[cp++] = ENCODE_B(OP_LOAD_IMM, 0, 35);
code[cp++] = ENCODE_B(OP_PUSH, 0, 0);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 1, fib);
code[cp++] = ENCODE_A(OP_CALL, 1, 9, 2);
/* print */
code[cp++] = ENCODE_A(OP_INT_TO_STR, 3, 2, 0);
code[cp++] = ENCODE_A(OP_SYSCALL, SYSCALL_CONSOLE_WRITE, 1, 3);
code[cp++] = ENCODE_A(OP_HALT, 0, 0, 0);
/* function fib (int n) int */
//code[cp++] = ENCODE_A(OP_SYSCALL, SYSCALL_DBG_PRINT, 1, 0);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 8, fib);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 1, 2);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 2, base_case);
code[cp++] = ENCODE_A(OP_JLT_INT, 2, 0, 1);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 3, 2);
code[cp++] = ENCODE_A(OP_SUB_INT, 4, 0, 3);
code[cp++] = ENCODE_B(OP_PUSH, 4, 0);
code[cp++] = ENCODE_A(OP_CALL, 8, 9, 5);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 3, 1);
code[cp++] = ENCODE_A(OP_SUB_INT, 4, 0, 3);
code[cp++] = ENCODE_B(OP_PUSH, 4, 0);
code[cp++] = ENCODE_A(OP_CALL, 8, 9, 6);
code[cp++] = ENCODE_A(OP_ADD_INT, 7, 6, 5);
code[cp++] = ENCODE_B(OP_RETURN, 7, 0);
code[cp++] = ENCODE_B(OP_RETURN, 0, 0);
}
void test_hello() {
u32 hello =str_alloc("nuqneH 'u'?", 12);
u32 new_line = str_alloc("\n", 1);
fp = mp;
/* function main() */
i32 main_local_count = 3;
mp += (4 * main_local_count);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 0, hello);
code[cp++] = ENCODE_A(OP_SYSCALL, SYSCALL_CONSOLE_WRITE, 12, 0);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 0, new_line);
code[cp++] = ENCODE_A(OP_SYSCALL, SYSCALL_CONSOLE_WRITE, 1, 0);
code[cp++] = ENCODE_A(OP_HALT, 0, 0, 0);
while(step_vm()) {}
}
i32 main() {
init_vm();
test_hello();
fib();
//repl();
while(step_vm()) {
// do stuff
}
return 0;
}

10
build
View File

@ -102,10 +102,18 @@ VM_BUILD_FLAGS="$BUILD_FLAGS -std=c89 -ffreestanding -nostdlib -fno-builtin"
${CC} -c vm/libc.c -o $BUILD_DIR/libc.o $VM_BUILD_FLAGS
${CC} -c vm/vm.c -o $BUILD_DIR/vm.o $VM_BUILD_FLAGS
# build the compiler
case $ARCH in
"linux")
${CC} -c tools/compiler/parser.c -o $BUILD_DIR/parser.o $BUILD_FLAGS
${CC} -c tools/compiler/compiler.c -o $BUILD_DIR/compiler.o $BUILD_FLAGS
;;
esac
# Set up the final build command
case $ARCH in
"linux")
BUILD_CMD="$CC -o $BUILD_DIR/undar $SRC_DIR/main.c $LINK_FLAGS $BUILD_DIR/libc.o $BUILD_DIR/vm.o $BUILD_FLAGS $LINK_FLAGS"
BUILD_CMD="$CC -o $BUILD_DIR/undar $SRC_DIR/main.c $LINK_FLAGS $BUILD_DIR/libc.o $BUILD_DIR/vm.o $BUILD_DIR/parser.o $BUILD_DIR/compiler.o $BUILD_FLAGS $LINK_FLAGS"
;;
"web")
BUILD_CMD="$CC $SRC_DIR/main.c $BUILD_DIR/libc.o $BUILD_DIR/vm.o -o $BUILD_DIR/undar.html $BUILD_FLAGS $LINK_FLAGS"

31
test/add.ul Normal file
View File

@ -0,0 +1,31 @@
/**
* Constants
*/
const str nl = "\n";
plex Terminal {
nat handle;
}
/**
* Main function
*/
function main() {
pln(add(1, 1).str);
}
/**
* Add two numbers together
*/
function add(int a, int b) int {
return a + b;
}
/**
* Print with a newline
*/
function pln(str message) {
Terminal term = open("term::/0", 0);
write(term, message, message.length);
write(term, nl, nl.length);
}

32
test/fib.ul Normal file
View File

@ -0,0 +1,32 @@
/**
* Constants
*/
const str nl = "\n";
plex Terminal {
nat handle;
}
/**
* Main function
*/
function main() {
pln(fib(35).str);
}
/**
* Recursively calculate fibonacci
*/
function fib(int n) int {
if (n < 2) { return n; }
return fib(n - 2) + fib(n - 1);
}
/**
* Print with a newline
*/
function pln(str message) {
Terminal term = open("term::/0", 0);
write(term, message, message.length);
write(term, nl, nl.length);
}

23
test/hello.ul Normal file
View File

@ -0,0 +1,23 @@
/**
* Plexes
*/
plex Terminal {
nat handle;
}
/**
* Main function
*/
function main() {
pln("nuqneH 'u'?");
}
/**
* Print with a newline
*/
function pln(str message) {
Terminal term = open("term::/0", 0);
write(term, message, message.length);
const str nl = "\n";
write(term, nl, nl.length);
}

26
test/malloc.ul Normal file
View File

@ -0,0 +1,26 @@
/**
* Constants
*/
const str nl = "\n";
plex Terminal {
nat handle;
}
/**
* Main function
*/
function main() {
Terminal term = open("term::/0", 0);
pln(term, "Enter a string: ");
pln(term, term.read(32));
return 0;
}
/**
* Print with a newline
*/
function pln(Terminal term, str message) {
write(term, message, message.length);
write(term, nl, nl.length);
}

109
test/paint.ul Normal file
View File

@ -0,0 +1,109 @@
/**
* Constants
*/
const byte BLACK = 0;
const byte WHITE = 255;
const byte DARK_GRAY = 73;
const byte GRAY = 146;
const byte LIGHT_GRAY = 182;
byte selected_color = 255;
trait Device {
nat handle;
}
plex Screen implements Device {
nat handle;
nat width;
nat height;
byte[] buffer;
draw() {
write(this, this.buffer, this.buffer.length);
}
}
plex Mouse implements Device {
nat handle;
nat x;
nat y;
bool left;
bool right;
bool middle;
bool btn4;
}
/**
* Main function
*/
function main() {
Screen screen = open("screen::/0", 0);
Mouse mouse = open("mouse::/0", 0);
outline_swatch(screen, BLACK, 1, 1);
outline_swatch(screen, WHITE, 21, 1);
screen.draw();
loop {
mouse.refresh();
if (!mouse.left) continue;
int box_size = 20;
int x = 1;
int y = 1;
byte color = BLACK;
outlined_swatch(screen, color, x, y);
set_color(box_size, x, y, mouse.x, mouse.y, color);
color = WHITE;
x = 21;
outlined_swatch(screen, color, x, y);
set_color(box_size, x, y, mouse.x, mouse.y, color);
screen.draw();
rectangle(screen, selected_color, x, y, 5, 5);
}
exit(0);
}
/**
* Checks if the click is within the bound and update the selected color if so.
*/
function set_color(int box_size, int bx, int by, int mx, int my, byte color) {
int right = bx + box_size;
int bottom = by + box_size;
if (mx < bx) return;
if (mx > right) return;
if (my < by) return;
if (my > bottom) return;
selected_color = color;
}
/**
* Draw a color box with a grey outline, if selected use a darker color
*/
function outline_swatch(Device screen, byte color, int x, int y) {
byte bg_color = GRAY;
if (selected_color == color) {
bg_color = DARK_GRAY;
}
rectangle(screen, bg_color, x, y, 20, 20);
rectangle(screen, color, x + 2, y + 2, 17, 17);
}
/**
* Draw a rectangle
*/
function rectangle(Device screen, byte color, int x, int y, int width, int height) {
int base = y * screen.width + x + screen.buffer.ptr + 4;
do (int i = height; i > 0; i--) {
int row = base + width;
memset(screen.buffer, row, color, width);
base += screen.width;
}
}

25
test/simple.ul Normal file
View File

@ -0,0 +1,25 @@
/**
* Constants
*/
const str nl = "\n";
plex Terminal {
nat handle;
}
/**
* Main function
*/
function main() {
pln((1.0 + 1.0) as str);
exit(0);
}
/**
* Print with a newline
*/
function pln(str message) {
Terminal term = open("term::/0", 0);
write(term, message, message.length);
write(term, nl, nl.length);
}

72
test/window.ul Normal file
View File

@ -0,0 +1,72 @@
/**
* Constants
*/
const str screen_namespace = "screen::/0"
const str mouse_namespace = "mouse::/0"
const str terminal_namespace = "term::/0"
const str new_line = "\n"
const byte WHITE = 255
/**
* Devices
*/
plex Terminal {
nat handle;
}
plex Screen {
nat handle;
nat width;
nat height;
byte[] buffer;
draw() {
write(this, this.buffer, this.buffer_size);
}
}
plex Mouse {
nat handle;
nat x;
nat y;
bool left;
bool right;
bool middle;
bool btn4;
nat size;
}
/**
* Main function
*/
function main() {
Screen screen = open(screen_namespace, 0);
pln(screen.handle as str);
pln(screen.width as str);
pln(screen.size as str);
unsafe {
pln(screen.screen_buffer.ptr as str);
}
Mouse mouse = open(mouse_namespace, 0);
screen.draw();
loop {
if (mouse.left) {
unsafe {
screen.buffer[mouse.y * width + mouse.x +
screen.buffer.ptr + 4] = WHITE;
screen.draw();
}
}
}
}
/**
* Print with a newline
*/
function pln(str message) {
Terminal term = open(terminal_namespace, 0);
write(term, message, message.length);
write(term, nl, nl.length);
}

View File

@ -1,7 +0,0 @@
#include "assembler.h"
/**
* Emit bytecode to the VM from the source string.
*/
void assemble(char *source, ScopeTable *st) {
}

View File

@ -1,55 +0,0 @@
#ifndef UNDAR_IR_ASSEMBLER_H
#define UNDAR_IR_ASSEMBLER_H
#include "../../vm/libc.h"
#include "lexer.h"
typedef enum { GLOBAL, LOCAL, VAR } ScopeType;
typedef enum {
VOID,
BOOL,
I8,
I16,
I32,
U8,
U16,
U32,
F8,
F16,
F32,
STR,
PLEX,
ARRAY,
FUNCTION
} SymbolType;
typedef struct symbol_s Symbol;
typedef struct symbol_tab_s SymbolTable;
typedef struct scope_tab_s ScopeTable;
#define MAX_SYMBOL_NAME_LENGTH 64
struct symbol_s {
char name[MAX_SYMBOL_NAME_LENGTH];
u8 name_length;
SymbolType type;
ScopeType scope;
u32 ref; // vm->mp if global, vm->pc local, register if var
u32 size; // size of symbol
};
struct symbol_tab_s {
Symbol symbols[256];
u8 count;
i32 parent;
};
struct scope_tab_s {
SymbolTable *scopes;
u32 count;
u32 capacity;
i32 scope_ref;
};
void assemble(char *source, ScopeTable *st);
#endif

View File

@ -1,401 +0,0 @@
#include <string.h>
#include "../../vm/libc.h"
#include "lexer.h"
typedef struct {
const char *start;
const char *current;
i32 line;
} Lexer;
Lexer lexer;
void init_lexer(const char *source) {
lexer.start = source;
lexer.current = source;
lexer.line = 1;
}
static bool is_alpha(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}
static bool is_digit(char c) { return c >= '0' && c <= '9'; }
static bool is_at_end() { return *lexer.current == '\0'; }
static char advance() {
lexer.current++;
return lexer.current[-1];
}
static char peek() { return *lexer.current; }
static char peek_next() {
if (is_at_end())
return '\0';
return lexer.current[1];
}
static bool match(char expected) {
if (is_at_end())
return false;
if (*lexer.current != expected)
return false;
lexer.current++;
return true;
}
static Token make_token(TokenType type) {
Token token;
token.type = type;
token.start = lexer.start;
token.length = (i32)(lexer.current - lexer.start);
token.line = lexer.line;
return token;
}
static Token error_token(const char *message) {
Token token;
token.type = TOKEN_ERROR;
token.start = message;
token.length = (i32)strlen(message);
token.line = lexer.line;
return token;
}
static void skip_whitespace() {
for (;;) {
char c = peek();
switch (c) {
case ' ':
case '\r':
case '\t':
advance();
break;
case '\n':
lexer.line++;
advance();
break;
case '/':
if (peek_next() == '/') {
// Single-line comment: skip until newline or end of file
advance();
while (peek() != '\n' && !is_at_end())
advance();
} else if (peek_next() == '*') {
// Multi-line comment: skip until '*/' or end of file
advance();
advance();
while (!is_at_end()) {
if (peek() == '\n')
lexer.line++;
if (peek() == '*' && peek_next() == '/') {
advance();
advance();
break; // Exit loop, comment ended
}
advance();
}
} else {
return; // Not a comment, let tokenization handle it
}
break;
default:
return;
}
}
}
static TokenType check_keyword(i32 start, i32 length, const char *rest,
TokenType type) {
if (lexer.current - lexer.start == start + length &&
memcmp(lexer.start + start, rest, length) == 0) {
return type;
}
return TOKEN_IDENTIFIER;
}
static TokenType identifierType() {
switch (lexer.start[0]) {
case 'a':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'n':
return check_keyword(2, 1, "d", TOKEN_OPERATOR_AND);
case 's':
return check_keyword(2, 0, "", TOKEN_KEYWORD_AS);
}
}
break;
case 'c':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'l':
return check_keyword(2, 3, "ose", TOKEN_KEYWORD_CLOSE);
case 'o':
return check_keyword(2, 3, "nst", TOKEN_KEYWORD_CONST);
}
}
break;
case 'e':
return check_keyword(1, 3, "lse", TOKEN_KEYWORD_ELSE);
case 'f':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'a':
return check_keyword(2, 3, "lse", TOKEN_KEYWORD_FALSE);
case 'o':
return check_keyword(2, 1, "r", TOKEN_KEYWORD_FOR);
case '3':
return check_keyword(1, 1, "2", TOKEN_TYPE_REAL);
}
return check_keyword(1, 7, "unction", TOKEN_KEYWORD_FN);
}
break;
case 'i':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'f':
return check_keyword(2, 0, "", TOKEN_KEYWORD_IF);
case 's':
return check_keyword(2, 0, "", TOKEN_KEYWORD_IS);
case '8':
return check_keyword(2, 0, "", TOKEN_TYPE_I8);
case '1':
return check_keyword(2, 1, "6", TOKEN_TYPE_I16);
case '3':
return check_keyword(2, 1, "2", TOKEN_TYPE_INT);
case 'n':
if (lexer.current - lexer.start > 2) {
switch (lexer.start[2]) {
case 'i':
return check_keyword(3, 2, "t", TOKEN_KEYWORD_INIT);
case 't':
return check_keyword(3, 0, "", TOKEN_TYPE_INT);
}
}
break;
}
}
break;
case 'n':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'a':
return check_keyword(2, 1, "t", TOKEN_TYPE_NAT);
case 'i':
return check_keyword(2, 1, "l", TOKEN_KEYWORD_NIL);
}
}
break;
case 'o':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'p':
return check_keyword(2, 2, "en", TOKEN_KEYWORD_OPEN);
case 'r':
return check_keyword(2, 0, "", TOKEN_OPERATOR_OR);
}
}
break;
case 'p':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'l':
return check_keyword(2, 2, "ex", TOKEN_KEYWORD_PLEX);
}
}
break;
case 'r':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'e':
if (lexer.current - lexer.start > 2) {
switch (lexer.start[2]) {
case 'f':
return check_keyword(3, 4, "resh", TOKEN_KEYWORD_REFRESH);
case 't':
return check_keyword(3, 3, "urn", TOKEN_KEYWORD_RETURN);
case 'a':
if (lexer.current - lexer.start > 3) {
switch(lexer.start[3]) {
case 'd':
return check_keyword(4, 0, "", TOKEN_KEYWORD_READ);
case 'l':
return check_keyword(4, 0, "", TOKEN_TYPE_REAL);
}
}
}
}
break;
}
}
break;
case 's':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 't':
return check_keyword(2, 1, "r", TOKEN_TYPE_STR);
}
}
break;
case 't':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'h':
return check_keyword(2, 2, "is", TOKEN_KEYWORD_THIS);
case 'r':
return check_keyword(2, 2, "ue", TOKEN_KEYWORD_TRUE);
}
}
break;
case 'u':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 's':
return check_keyword(2, 1, "e", TOKEN_KEYWORD_USE);
case '8':
return check_keyword(2, 0, "", TOKEN_TYPE_U8);
case '1':
return check_keyword(2, 1, "6", TOKEN_TYPE_U16);
case '3':
return check_keyword(2, 1, "2", TOKEN_TYPE_NAT);
}
}
break;
case 'w':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'h':
return check_keyword(2, 3, "ile", TOKEN_KEYWORD_WHILE);
case 'r':
return check_keyword(2, 3, "ite", TOKEN_KEYWORD_WRITE);
}
}
break;
case 'b':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'y':
return check_keyword(2, 2, "te", TOKEN_TYPE_U8);
case 'o':
return check_keyword(2, 2, "ol", TOKEN_TYPE_U8);
}
}
break;
case 'g':
return check_keyword(1, 5, "lobal", TOKEN_KEYWORD_GLOBAL);
case 'l':
return check_keyword(1, 3, "oop", TOKEN_KEYWORD_LOOP);
case 'd':
return check_keyword(1, 1, "o", TOKEN_KEYWORD_DO);
case 'v':
return check_keyword(1, 3, "oid", TOKEN_TYPE_VOID);
}
return TOKEN_IDENTIFIER;
}
static Token identifier() {
while (is_alpha(peek()) || is_digit(peek()))
advance();
return make_token(identifierType());
}
static Token number() {
while (is_digit(peek()))
advance();
/* Look for a fractional part. */
if (peek() == '.' && is_digit(peek_next())) {
/* Consume the ".". */
advance();
while (is_digit(peek()))
advance();
return make_token(TOKEN_LITERAL_REAL);
}
return make_token(TOKEN_LITERAL_INT);
}
static Token string() {
while (peek() != '"' && !is_at_end()) {
if (peek() == '\n')
lexer.line++;
advance();
}
if (is_at_end())
return error_token("Unterminated string.");
/* The closing quote. */
advance();
return make_token(TOKEN_LITERAL_STR);
}
Token next_token() {
skip_whitespace();
lexer.start = lexer.current;
if (is_at_end())
return make_token(TOKEN_EOF);
char c = advance();
if (is_alpha(c))
return identifier();
char next = peek();
if ((c == '-' && is_digit(next)) || is_digit(c))
return number();
switch (c) {
case '(':
return make_token(TOKEN_LPAREN);
case ')':
return make_token(TOKEN_RPAREN);
case '{':
return make_token(TOKEN_LBRACE);
case '}':
return make_token(TOKEN_RBRACE);
case '[':
return make_token(TOKEN_LBRACKET);
case ']':
return make_token(TOKEN_RBRACKET);
case ';':
return make_token(TOKEN_SEMICOLON);
case ',':
return make_token(TOKEN_COMMA);
case '.':
return make_token(TOKEN_DOT);
case '-':
return make_token(match('>') ? TOKEN_ARROW_RIGHT : TOKEN_MINUS);
case '+':
return make_token(TOKEN_PLUS);
case '/':
return make_token(TOKEN_SLASH);
case '&':
return make_token(match('&') ? TOKEN_AND_AND : TOKEN_AND);
case '#':
return make_token(TOKEN_MESH);
case '$':
return make_token(TOKEN_BIG_MONEY);
case '*':
return make_token(TOKEN_STAR);
case '!':
return make_token(match('=') ? TOKEN_BANG_EQ : TOKEN_BANG);
case '=':
return make_token(match('=') ? TOKEN_EQ_EQ : TOKEN_EQ);
case '<':
return make_token(match('=') ? TOKEN_LTE : TOKEN_LT);
case '>':
return make_token(match('=') ? TOKEN_GTE : TOKEN_GT);
case '"':
return string();
}
return error_token("Unexpected character.");
}

655
tools/compiler/compiler.c Normal file
View File

@ -0,0 +1,655 @@
#include "compiler.h"
#include "parser.h"
#include <stdio.h>
#include <stdlib.h>
Token operator_stack[128];
u8 osp;
Token value_stack[256];
u8 vsp;
Parser parser;
Symbol *symbol_table_lookup(ScopeTable *table, const char *name, u32 length,
i32 scope_ref) {
SymbolTable st = table->scopes[scope_ref];
for (u32 i = 0; i < st.count; i++) {
if (st.symbols[i].name_length == length) {
if (sleq(st.symbols[i].name, name, length)) {
return &table->scopes[scope_ref].symbols[i];
}
}
}
if (st.parent < 0)
return nil;
return symbol_table_lookup(table, name, length, st.parent);
}
u8 symbol_table_add(ScopeTable *table, Symbol s) {
Symbol *sym =
symbol_table_lookup(table, s.name, s.name_length, table->scope_ref);
if (sym != nil) {
fprintf(stderr,
"Error: Symbol '%.*s' already defined, in this scope"
" please pick a different variable name or create a new scope.\n",
s.name_length, s.name);
exit(1);
}
if (table->scopes[table->scope_ref].count + 1 > 255) {
fprintf(stderr, "Error: Only 255 symbols are allowed per scope"
" first off: impressive; secondly:"
" just create a new scope and keep going.\n");
exit(1);
}
if (!table_realloc(table)) {
fprintf(stderr,
"Error: Symbol table is out of memory! This is likely because you "
" built the assembler in static mode, increase the static size."
" if you built using malloc, that means your computer is out of"
" memory. Close a few tabs in your web browser and try again."
" Count was %d, while capacity was %d\n",
table->count, table->capacity);
exit(1);
}
table->scopes[table->scope_ref]
.symbols[table->scopes[table->scope_ref].count] = s;
u8 index = table->scopes[table->scope_ref].count;
table->scopes[table->scope_ref].count++;
return index;
}
u32 get_ref(ScopeTable *st, const char *name, u32 length) {
Symbol *sym = symbol_table_lookup(st, name, length, st->scope_ref);
if (!sym) {
fprintf(stderr, "Error: Assembler has no idea what Symbol '%.*s' means.\n",
length, name);
exit(1);
return 0;
}
return sym->ref;
}
u32 get_ptr(Token token, ScopeTable *st) {
if (token.type == TOKEN_IDENTIFIER) {
return get_ref(st, token.start, token.length);
}
if (token.type == TOKEN_LITERAL_INT) {
return atoi(token.start);
}
if (token.type == TOKEN_LITERAL_NAT) {
char *endptr;
u32 out = (u32)strtoul(token.start, &endptr, 10);
if (endptr == token.start || *endptr != '\0') {
fprintf(stderr, "Invalid decimal literal at line %d: %.*s\n", token.line,
token.length, token.start);
exit(1);
}
return out;
}
fprintf(stderr, "Error: Not a pointer or symbol at line %d: %.*s\n",
token.line, token.length, token.start);
exit(1);
}
u32 get_reg(Token token, ScopeTable *st) {
if (token.type == TOKEN_IDENTIFIER) {
return get_ref(st, token.start, token.length);
}
if (token.type == TOKEN_BIG_MONEY) {
token = next_token();
return atoi(token.start);
}
fprintf(stderr, "Error: Not a register or symbol at line %d: %.*s\n",
token.line, token.length, token.start);
exit(1);
}
void advance() {
parser.previous = parser.current;
parser.current = next_token();
}
static void consume(TokenType type, char *err_msg) {
if (parser.current.type == type) {
advance();
return;
}
printf("ERROR at line %d: %.*s %s\n", parser.current.line,
parser.current.length, parser.current.start, err_msg);
exit(1);
}
void next_id_or_reg() {
advance();
if (parser.current.type == TOKEN_IDENTIFIER) {
return;
}
if (parser.current.type == TOKEN_BIG_MONEY) {
advance();
return;
}
printf("Not an ID or register at line %d: %.*s\n", parser.current.line,
parser.current.length, parser.current.start);
exit(1);
}
void next_id_or_ptr() {
advance();
if (parser.current.type != TOKEN_IDENTIFIER &&
parser.current.type != TOKEN_LITERAL_NAT &&
parser.current.type != TOKEN_LITERAL_INT &&
parser.current.type != TOKEN_LITERAL_REAL) {
printf("Not an ID or register at line %d: %.*s\n", parser.current.line,
parser.current.length, parser.current.start);
exit(1);
}
}
static void expression();
static ParseRule *getRule(TokenType type);
static void parsePrecedence(Precedence precedence);
static void number() {
switch (parser.previous.type) {
case TOKEN_LITERAL_INT: {
i32 out = atoi(parser.previous.start);
if (out <= I8_MAX && out >= I8_MIN) {
code[cp++] = OP_PUSH_8;
code[cp++] = (out) & 0xFF;
return;
}
if (out <= I16_MAX && out >= I16_MIN) {
code[cp++] = OP_PUSH_16;
code[cp++] = (out) & 0xFF;
code[cp++] = ((out) >> 8) & 0xFF;
return;
}
code[cp++] = OP_PUSH_32;
code[cp++] = (out) & 0xFF;
code[cp++] = ((out) >> 8) & 0xFF;
code[cp++] = ((out) >> 16) & 0xFF;
code[cp++] = ((out) >> 24) & 0xFF;
return;
}
case TOKEN_LITERAL_NAT: {
char *endptr;
u32 out = (u32)strtoul(parser.previous.start, &endptr, 10);
if (endptr == parser.previous.start || *endptr != '\0') {
fprintf(stderr, "Invalid 'real' number: '%.*s'\n", parser.previous.length,
parser.previous.start);
exit(1);
}
if (out <= U8_MAX) {
code[cp++] = OP_PUSH_8;
code[cp++] = (out) & 0xFF;
return;
}
if (out <= U16_MAX) {
code[cp++] = OP_PUSH_16;
code[cp++] = (out) & 0xFF;
code[cp++] = ((out) >> 8) & 0xFF;
return;
}
code[cp++] = OP_PUSH_32;
code[cp++] = (out) & 0xFF;
code[cp++] = ((out) >> 8) & 0xFF;
code[cp++] = ((out) >> 16) & 0xFF;
code[cp++] = ((out) >> 24) & 0xFF;
return;
}
case TOKEN_LITERAL_REAL: {
i32 out = FLOAT_TO_REAL(atof(parser.previous.start));
code[cp++] = OP_PUSH_32;
code[cp++] = (out) & 0xFF;
code[cp++] = ((out) >> 8) & 0xFF;
code[cp++] = ((out) >> 16) & 0xFF;
code[cp++] = ((out) >> 24) & 0xFF;
return;
}
default: {
fprintf(stderr, "Unknown immediate: '%.*s'\n", parser.previous.length,
parser.previous.start);
exit(1);
}
}
}
static void expression() { parsePrecedence(PREC_ASSIGNMENT); }
static void grouping() {
expression();
consume(TOKEN_RPAREN, "Expected ')'.");
}
static void unary() {
TokenType operatorType = parser.previous.type;
parsePrecedence(PREC_UNARY);
switch (operatorType) {
case TOKEN_MINUS: {
code[cp++] = OP_NEG;
break;
}
case TOKEN_BANG: {
code[cp++] = OP_NOT;
break;
}
default:
return;
}
}
static void cast(TokenType prev) {
switch (prev) {
case TOKEN_TYPE_I8: {
break;
}
case TOKEN_TYPE_I16: {
break;
}
case TOKEN_TYPE_INT: {
break;
}
case TOKEN_TYPE_U8: {
break;
}
case TOKEN_TYPE_U16: {
break;
}
case TOKEN_TYPE_NAT: {
break;
}
case TOKEN_TYPE_REAL: {
break;
}
case TOKEN_TYPE_BOOL: {
break;
}
case TOKEN_TYPE_STR: {
break;
}
default: {
printf("Cannot cast to type (%s)\n", token_type_to_string(parser.previous.type));
}
}
}
static void binary() {
TokenType operatorType = parser.previous.type;
TokenType operand = parser.current.type;
ParseRule *rule = getRule(operatorType);
parsePrecedence((Precedence)(rule->precedence + 1));
printf("before prev: %s, operatorType: %s, operand: %s\n",
token_type_to_string(parser.previous.type),
token_type_to_string(operatorType),
token_type_to_string(operand));
switch (operatorType) {
case TOKEN_KEYWORD_AS: {
cast(parser.previous.type);
break;
}
case TOKEN_PLUS: {
switch (parser.previous.type) {
case TOKEN_LITERAL_INT:
code[cp++] = OP_ADD_INT;
break;
case TOKEN_LITERAL_NAT:
code[cp++] = OP_ADD_NAT;
break;
case TOKEN_LITERAL_REAL:
code[cp++] = OP_ADD_REAL;
break;
case TOKEN_IDENTIFIER:
printf("FIXME: find the identifier's type for add\n");
break;
default:
printf("Unknown Add Arg=%d\n", parser.previous.type);
return;
}
break;
}
case TOKEN_MINUS: {
switch (parser.previous.type) {
case TOKEN_LITERAL_INT:
code[cp++] = OP_SUB_INT;
break;
case TOKEN_LITERAL_NAT:
code[cp++] = OP_SUB_NAT;
break;
case TOKEN_LITERAL_REAL:
code[cp++] = OP_SUB_REAL;
break;
case TOKEN_IDENTIFIER:
printf("FIXME: find the identifier's type for sub\n");
break;
default:
printf("Unknown Sub Arg=%d\n", parser.previous.type);
return; // Unreachable.
}
break;
}
case TOKEN_STAR: {
switch (parser.previous.type) {
case TOKEN_LITERAL_INT:
code[cp++] = OP_MUL_INT;
break;
case TOKEN_LITERAL_NAT:
code[cp++] = OP_MUL_NAT;
break;
case TOKEN_LITERAL_REAL:
code[cp++] = OP_MUL_REAL;
break;
case TOKEN_IDENTIFIER:
printf("FIXME: find the identifier's type for mul\n");
break;
default:
printf("Unknown Mul Arg=%d\n", parser.previous.type);
return; // Unreachable.
}
break;
}
case TOKEN_SLASH: {
switch (parser.previous.type) {
case TOKEN_LITERAL_INT:
code[cp++] = OP_DIV_INT;
break;
case TOKEN_LITERAL_NAT:
code[cp++] = OP_DIV_NAT;
break;
case TOKEN_LITERAL_REAL:
code[cp++] = OP_DIV_REAL;
break;
case TOKEN_IDENTIFIER:
printf("FIXME: find the identifier's type for div\n");
break;
default:
printf("Unknown Div Arg=%d\n", parser.previous.type);
return; // Unreachable.
}
break;
}
case TOKEN_EQ_EQ: {
switch (parser.previous.type) {
case TOKEN_LITERAL_INT:
case TOKEN_LITERAL_REAL:
code[cp++] = OP_EQS;
break;
case TOKEN_LITERAL_NAT:
code[cp++] = OP_EQU;
break;
case TOKEN_IDENTIFIER:
printf("FIXME: find the identifier's type for ==\n");
break;
default:
printf("Unknown == Arg=%d\n", parser.previous.type);
return; // Unreachable.
}
break;
}
case TOKEN_BANG_EQ: {
switch (parser.previous.type) {
case TOKEN_LITERAL_INT:
case TOKEN_LITERAL_REAL:
code[cp++] = OP_NES;
break;
case TOKEN_LITERAL_NAT:
code[cp++] = OP_NEU;
break;
case TOKEN_IDENTIFIER:
printf("FIXME: find the identifier's type for !=\n");
break;
default:
printf("Unknown != Arg=%d\n", parser.previous.type);
return; // Unreachable.
}
break;
}
case TOKEN_GT: {
switch (parser.previous.type) {
case TOKEN_LITERAL_INT:
case TOKEN_LITERAL_REAL:
code[cp++] = OP_GTS;
break;
case TOKEN_LITERAL_NAT:
code[cp++] = OP_GTU;
break;
case TOKEN_IDENTIFIER:
printf("FIXME: find the identifier's type for >\n");
break;
default:
printf("Unknown > Arg=%d\n", parser.previous.type);
return; // Unreachable.
}
break;
}
case TOKEN_GTE: {
switch (parser.previous.type) {
case TOKEN_LITERAL_INT:
case TOKEN_LITERAL_REAL:
code[cp++] = OP_GES;
break;
case TOKEN_LITERAL_NAT:
code[cp++] = OP_GEU;
break;
case TOKEN_IDENTIFIER:
printf("FIXME: find the identifier's type for >=\n");
break;
default:
printf("Unknown >= Arg=%d\n", parser.previous.type);
return; // Unreachable.
}
break;
}
case TOKEN_LT: {
switch (parser.previous.type) {
case TOKEN_LITERAL_INT:
case TOKEN_LITERAL_REAL:
code[cp++] = OP_LTS;
break;
case TOKEN_LITERAL_NAT:
code[cp++] = OP_LTU;
break;
case TOKEN_IDENTIFIER:
printf("FIXME: find the identifier's type for <\n");
break;
default:
printf("Unknown < Arg=%d\n", parser.previous.type);
return; // Unreachable.
}
break;
}
case TOKEN_LTE: {
switch (parser.previous.type) {
case TOKEN_LITERAL_REAL:
case TOKEN_LITERAL_INT:
code[cp++] = OP_LES;
break;
case TOKEN_LITERAL_NAT:
code[cp++] = OP_LEU;
break;
case TOKEN_IDENTIFIER:
printf("FIXME: find the identifier's type for <=\n");
break;
default:
printf("Unknown <= Arg=%d\n", parser.previous.type);
return; // Unreachable.
}
break;
}
default:
return; // Unreachable.
}
}
static void literal() {
switch (parser.previous.type) {
case TOKEN_KEYWORD_NIL: {
code[cp++] = OP_PUSH_8;
code[cp++] = 0;
break;
}
case TOKEN_KEYWORD_TRUE: {
code[cp++] = OP_PUSH_8;
code[cp++] = 1;
break;
}
case TOKEN_KEYWORD_FALSE: {
code[cp++] = OP_PUSH_8;
code[cp++] = 0;
break;
}
default:
return; // Unreachable.
}
}
static void string() {
u32 addr = mp;
const char *src = parser.previous.start + 1;
i32 len = 0;
i32 i = 0;
while (i < parser.previous.length - 2) {
char c = src[i++];
if (c == '\\' && i < parser.previous.length - 2) {
switch (src[i++]) {
case 'n':
c = '\n';
break;
case 't':
c = '\t';
break;
case 'r':
c = '\r';
break;
case '\\':
case '"':
case '\'':
break;
default:
i--; /* Rewind for unknown escapes */
}
}
WRITE_U8(addr + 4 + len, c);
len++;
}
u32 size = len + 5; /* 4 (len) + dst_len + 1 (null) */
mp += size;
WRITE_U32(addr, len);
WRITE_U8(addr + 4 + len, '\0');
/* push address of string on the stack */
code[cp++] = OP_PUSH_32;
code[cp++] = (addr) & 0xFF;
code[cp++] = ((addr) >> 8) & 0xFF;
code[cp++] = ((addr) >> 16) & 0xFF;
code[cp++] = ((addr) >> 24) & 0xFF;
}
ParseRule rules[] = {
[TOKEN_LPAREN] = {grouping, NULL, PREC_NONE},
[TOKEN_RPAREN] = {NULL, NULL, PREC_NONE},
[TOKEN_LBRACE] = {NULL, NULL, PREC_NONE},
[TOKEN_RBRACE] = {NULL, NULL, PREC_NONE},
[TOKEN_COMMA] = {NULL, NULL, PREC_NONE},
[TOKEN_DOT] = {NULL, NULL, PREC_NONE},
[TOKEN_MINUS] = {unary, binary, PREC_TERM},
[TOKEN_PLUS] = {NULL, binary, PREC_TERM},
[TOKEN_SEMICOLON] = {NULL, NULL, PREC_NONE},
[TOKEN_SLASH] = {NULL, binary, PREC_FACTOR},
[TOKEN_STAR] = {NULL, binary, PREC_FACTOR},
[TOKEN_BANG] = {unary, NULL, PREC_NONE},
[TOKEN_BANG_EQ] = {NULL, binary, PREC_EQUALITY},
[TOKEN_EQ] = {NULL, NULL, PREC_NONE},
[TOKEN_EQ_EQ] = {NULL, binary, PREC_EQUALITY},
[TOKEN_GT] = {NULL, binary, PREC_COMPARISON},
[TOKEN_GTE] = {NULL, binary, PREC_COMPARISON},
[TOKEN_LT] = {NULL, binary, PREC_COMPARISON},
[TOKEN_LTE] = {NULL, binary, PREC_COMPARISON},
[TOKEN_IDENTIFIER] = {NULL, NULL, PREC_NONE},
[TOKEN_LITERAL_STR] = {string, NULL, PREC_NONE},
[TOKEN_LITERAL_INT] = {number, NULL, PREC_NONE},
[TOKEN_LITERAL_NAT] = {number, NULL, PREC_NONE},
[TOKEN_LITERAL_REAL] = {number, NULL, PREC_NONE},
[TOKEN_AND] = {NULL, NULL, PREC_NONE},
[TOKEN_KEYWORD_AS] = {NULL, binary, PREC_CAST},
[TOKEN_KEYWORD_PLEX] = {NULL, NULL, PREC_NONE},
[TOKEN_KEYWORD_ELSE] = {NULL, NULL, PREC_NONE},
[TOKEN_KEYWORD_FALSE] = {literal, NULL, PREC_NONE},
[TOKEN_KEYWORD_FOR] = {NULL, NULL, PREC_NONE},
[TOKEN_KEYWORD_FN] = {NULL, NULL, PREC_NONE},
[TOKEN_KEYWORD_IF] = {NULL, NULL, PREC_NONE},
[TOKEN_KEYWORD_NIL] = {literal, NULL, PREC_NONE},
[TOKEN_OPERATOR_OR] = {NULL, NULL, PREC_NONE},
[TOKEN_KEYWORD_RETURN] = {NULL, NULL, PREC_NONE},
[TOKEN_KEYWORD_TRUE] = {literal, NULL, PREC_NONE},
[TOKEN_ERROR] = {NULL, NULL, PREC_NONE},
[TOKEN_EOF] = {NULL, NULL, PREC_NONE},
};
ParseRule *getRule(TokenType type) { return &rules[type]; }
void parsePrecedence(Precedence precedence) {
advance();
ParseFn prefixRule = getRule(parser.previous.type)->prefix;
if (prefixRule == NULL) {
error("Expect expression.");
return;
}
prefixRule();
while (precedence <= getRule(parser.current.type)->precedence) {
advance();
ParseFn infixRule = getRule(parser.previous.type)->infix;
infixRule();
}
}
/**
* Compile.
*/
bool compile(ScopeTable *st, char *source) {
USED(st);
initLexer(source);
advance();
expression();
consume(TOKEN_EOF, "Cannot find end of expression.");
// technically should not need, but just in case
code[cp++] = OP_HALT;
return true;
}

115
tools/compiler/compiler.h Normal file
View File

@ -0,0 +1,115 @@
#ifndef UNDAR_COMPILER_H
#define UNDAR_COMPILER_H
#include "../../vm/libc.h"
#include "../../vm/vm.h"
typedef enum { GLOBAL, LOCAL } ScopeType;
typedef enum {
VOID,
BOOL,
I8,
I16,
I32,
U8,
U16,
U32,
F8,
F16,
F32,
STR,
PLEX,
ARRAY,
FUNCTION
} SymbolType;
typedef struct symbol_s Symbol;
typedef struct symbol_tab_s SymbolTable;
typedef struct value_type_s ValueType;
typedef struct plex_fields_tab_s PlexFieldsTable;
typedef struct plex_def_s PlexDef;
typedef struct plex_tab_s PlexTable;
typedef struct scope_s Scope;
typedef struct scope_tab_s ScopeTable;
struct value_type_s {
SymbolType type;
u32 name;
u32 size;
u32 table_ref; // if it is a heap object
};
struct plex_def_s {
u32 name;
u32 size;
u32 field_ref_start;
u32 field_count;
};
struct plex_fields_tab_s {
u32 *plex_refs;
ValueType *fields;
u32 count;
u32 capacity;
};
struct plex_tab_s {
PlexDef *symbols;
u32 count;
u32 capacity;
};
#define MAX_SYMBOL_NAME_LENGTH 64
struct symbol_s {
char name[MAX_SYMBOL_NAME_LENGTH];
u8 name_length;
SymbolType type;
ScopeType scope;
u32 ref; // vm->mp if global, vm->pc local, register if var
u32 size; // size of symbol
};
#define MAX_SYMBOLS 256
struct symbol_tab_s {
Symbol symbols[MAX_SYMBOLS];
u8 count;
i32 parent;
};
struct scope_tab_s {
SymbolTable *scopes;
u32 count;
u32 capacity;
i32 scope_ref;
};
typedef enum {
PREC_NONE,
PREC_ASSIGNMENT, // =
PREC_OR, // or
PREC_AND, // and
PREC_EQUALITY, // == !=
PREC_COMPARISON, // < > <= >=
PREC_TERM, // + -
PREC_FACTOR, // * /
PREC_CAST, // as
PREC_UNARY, // ! -
PREC_CALL, // . ()
PREC_PRIMARY
} Precedence;
typedef void (*ParseFn)();
typedef struct {
ParseFn prefix;
ParseFn infix;
Precedence precedence;
} ParseRule;
bool compile(ScopeTable *st, char *source);
extern bool table_realloc(ScopeTable *table);/* implement this in arch/ not here */
extern void error(const char* msg);
#endif

510
tools/compiler/parser.c Normal file
View File

@ -0,0 +1,510 @@
#include "parser.h"
Lexer lexer;
void initLexer(const char *source) {
lexer.start = source;
lexer.current = source;
lexer.line = 1;
}
static bool isAlpha(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}
static bool isDigit(char c) { return c >= '0' && c <= '9'; }
static bool isAtEnd() { return *lexer.current == '\0'; }
static char advance() {
lexer.current++;
return lexer.current[-1];
}
static char peek() { return *lexer.current; }
static char peekNext() {
if (isAtEnd())
return '\0';
return lexer.current[1];
}
static bool match(char expected) {
if (isAtEnd())
return false;
if (*lexer.current != expected)
return false;
lexer.current++;
return true;
}
static Token makeToken(TokenType type) {
Token token;
token.type = type;
token.start = lexer.start;
token.length = (int)(lexer.current - lexer.start);
token.line = lexer.line;
return token;
}
static Token errorToken(const char *message) {
Token token;
token.type = TOKEN_ERROR;
token.start = message;
token.length = (int)slen(message);
token.line = lexer.line;
return token;
}
static void skipWhitespace() {
for (;;) {
char c = peek();
switch (c) {
case ' ':
case '\r':
case '\t':
advance();
break;
case '\n':
lexer.line++;
advance();
break;
case '/':
if (peekNext() == '/') {
// Single-line comment: skip until newline or end of file
advance();
while (peek() != '\n' && !isAtEnd())
advance();
} else if (peekNext() == '*') {
// Multi-line comment: skip until '*/' or end of file
advance();
advance();
while (!isAtEnd()) {
if (peek() == '\n')
lexer.line++;
if (peek() == '*' && peekNext() == '/') {
advance();
advance();
break; // Exit loop, comment ended
}
advance();
}
} else {
return; // Not a comment, let tokenization handle it
}
break;
default:
return;
}
}
}
static TokenType checkKeyword(int start, int length, const char *rest,
TokenType type) {
if (lexer.current - lexer.start == start + length &&
sleq(lexer.start + start, rest, length)) {
return type;
}
return TOKEN_IDENTIFIER;
}
static TokenType identifierType() {
switch (lexer.start[0]) {
case 'a':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'n':
return checkKeyword(2, 1, "d", TOKEN_OPERATOR_AND);
case 's':
return checkKeyword(2, 0, "", TOKEN_KEYWORD_AS);
}
}
break;
case 'c':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'l':
return checkKeyword(2, 3, "ose", TOKEN_KEYWORD_CLOSE);
case 'o':
return checkKeyword(2, 3, "nst", TOKEN_KEYWORD_CONST);
}
}
break;
case 'e':
return checkKeyword(1, 3, "lse", TOKEN_KEYWORD_ELSE);
case 'f':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'a':
return checkKeyword(2, 3, "lse", TOKEN_KEYWORD_FALSE);
case 'o':
return checkKeyword(2, 1, "r", TOKEN_KEYWORD_FOR);
case '3':
return checkKeyword(2, 1, "2", TOKEN_TYPE_REAL);
}
return checkKeyword(1, 7, "unction", TOKEN_KEYWORD_FN);
}
break;
case 'i':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'f':
return checkKeyword(2, 0, "", TOKEN_KEYWORD_IF);
case 's':
return checkKeyword(2, 0, "", TOKEN_KEYWORD_IS);
case '8':
return checkKeyword(2, 0, "", TOKEN_TYPE_I8);
case '1':
return checkKeyword(2, 1, "6", TOKEN_TYPE_I16);
case '3':
return checkKeyword(2, 1, "2", TOKEN_TYPE_INT);
case 'n':
if (lexer.current - lexer.start > 2) {
switch (lexer.start[2]) {
case 'i':
return checkKeyword(3, 2, "t", TOKEN_KEYWORD_INIT);
case 't':
return checkKeyword(3, 0, "", TOKEN_TYPE_INT);
}
}
break;
}
}
break;
case 'n':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'a':
return checkKeyword(2, 1, "t", TOKEN_TYPE_NAT);
case 'i':
return checkKeyword(2, 1, "l", TOKEN_KEYWORD_NIL);
}
}
break;
case 'o':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'p':
return checkKeyword(2, 2, "en", TOKEN_KEYWORD_OPEN);
case 'r':
return checkKeyword(2, 0, "", TOKEN_OPERATOR_OR);
}
}
break;
case 'p':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'l':
return checkKeyword(2, 2, "ex", TOKEN_KEYWORD_PLEX);
}
}
break;
case 'r':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'e':
if (lexer.current - lexer.start > 2) {
switch (lexer.start[2]) {
case 'f':
return checkKeyword(3, 4, "resh", TOKEN_KEYWORD_REFRESH);
case 't':
return checkKeyword(3, 3, "urn", TOKEN_KEYWORD_RETURN);
case 'a':
if (lexer.current - lexer.start > 3) {
switch (lexer.start[3]) {
case 'd': {
return checkKeyword(4, 0, "", TOKEN_KEYWORD_READ);
}
case 'l': {
return checkKeyword(4, 0, "", TOKEN_TYPE_REAL);
}
}
}
}
}
break;
}
}
break;
case 's':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 't':
return checkKeyword(2, 1, "r", TOKEN_TYPE_STR);
}
}
break;
case 't':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'h':
return checkKeyword(2, 2, "is", TOKEN_KEYWORD_THIS);
case 'r':
return checkKeyword(2, 2, "ue", TOKEN_KEYWORD_TRUE);
}
}
break;
case 'u':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 's':
return checkKeyword(2, 1, "e", TOKEN_KEYWORD_USE);
case '8':
return checkKeyword(2, 0, "", TOKEN_TYPE_U8);
case '1':
return checkKeyword(2, 1, "6", TOKEN_TYPE_U16);
case '3':
return checkKeyword(2, 1, "2", TOKEN_TYPE_NAT);
}
}
break;
case 'w':
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 'h':
return checkKeyword(2, 3, "ile", TOKEN_KEYWORD_WHILE);
case 'r':
return checkKeyword(2, 3, "ite", TOKEN_KEYWORD_WRITE);
}
}
break;
case 'g':
return checkKeyword(1, 5, "lobal", TOKEN_KEYWORD_GLOBAL);
}
return TOKEN_IDENTIFIER;
}
static Token identifier() {
while (isAlpha(peek()) || isDigit(peek()))
advance();
return makeToken(identifierType());
}
static Token number() {
while (isDigit(peek()))
advance();
/* Look for a fractional part. */
if (peek() == '.' && isDigit(peekNext())) {
/* Consume the ".". */
advance();
while (isDigit(peek()))
advance();
return makeToken(TOKEN_LITERAL_REAL);
}
return makeToken(TOKEN_LITERAL_INT);
}
static Token string() {
while (peek() != '"' && !isAtEnd()) {
if (peek() == '\n')
lexer.line++;
advance();
}
if (isAtEnd())
return errorToken("Unterminated string.");
/* The closing quote. */
advance();
return makeToken(TOKEN_LITERAL_STR);
}
Token next_token() {
skipWhitespace();
lexer.start = lexer.current;
if (isAtEnd())
return makeToken(TOKEN_EOF);
char c = advance();
if (isAlpha(c))
return identifier();
if (isDigit(c))
return number();
switch (c) {
case '(':
return makeToken(TOKEN_LPAREN);
case ')':
return makeToken(TOKEN_RPAREN);
case '{':
return makeToken(TOKEN_LBRACE);
case '}':
return makeToken(TOKEN_RBRACE);
case '[':
return makeToken(TOKEN_LBRACKET);
case ']':
return makeToken(TOKEN_RBRACKET);
case ';':
return makeToken(TOKEN_SEMICOLON);
case ',':
return makeToken(TOKEN_COMMA);
case '.':
return makeToken(TOKEN_DOT);
case '-':
return makeToken(match('>') ? TOKEN_ARROW_RIGHT : TOKEN_MINUS);
case '+':
return makeToken(TOKEN_PLUS);
case '/':
return makeToken(TOKEN_SLASH);
case '&':
return makeToken(match('&') ? TOKEN_AND_AND : TOKEN_AND);
case '#':
return makeToken(TOKEN_MESH);
case '$':
return makeToken(TOKEN_BIG_MONEY);
case '*':
return makeToken(TOKEN_STAR);
case '!':
return makeToken(match('=') ? TOKEN_BANG_EQ : TOKEN_BANG);
case '=':
return makeToken(match('=') ? TOKEN_EQ_EQ : TOKEN_EQ);
case '<':
return makeToken(match('=') ? TOKEN_LTE : TOKEN_LT);
case '>':
return makeToken(match('=') ? TOKEN_GTE : TOKEN_GT);
case '"':
return string();
}
return errorToken("Unexpected character.");
}
const char *token_type_to_string(TokenType type) {
switch (type) {
case TOKEN_EOF:
return "EOF";
case TOKEN_IDENTIFIER:
return "IDENTIFIER";
case TOKEN_LITERAL_INT:
return "LITERAL_INT";
case TOKEN_LITERAL_NAT:
return "LITERAL_NAT";
case TOKEN_LITERAL_REAL:
return "LITERAL_REAL";
case TOKEN_LITERAL_STR:
return "LITERAL_STR";
case TOKEN_TYPE_INT:
return "TYPE_INT";
case TOKEN_TYPE_NAT:
return "TYPE_NAT";
case TOKEN_TYPE_REAL:
return "TYPE_REAL";
case TOKEN_TYPE_STR:
return "TYPE_STR";
case TOKEN_KEYWORD_PLEX:
return "KEYWORD_PLEX";
case TOKEN_KEYWORD_FN:
return "KEYWORD_FN";
case TOKEN_KEYWORD_CONST:
return "KEYWORD_CONST";
case TOKEN_KEYWORD_IF:
return "KEYWORD_IF";
case TOKEN_KEYWORD_IS:
return "IS";
case TOKEN_KEYWORD_AS:
return "AS";
case TOKEN_KEYWORD_ELSE:
return "KEYWORD_ELSE";
case TOKEN_KEYWORD_WHILE:
return "KEYWORD_WHILE";
case TOKEN_KEYWORD_FOR:
return "KEYWORD_FOR";
case TOKEN_KEYWORD_RETURN:
return "KEYWORD_RETURN";
case TOKEN_KEYWORD_USE:
return "KEYWORD_USE";
case TOKEN_KEYWORD_INIT:
return "KEYWORD_INIT";
case TOKEN_KEYWORD_THIS:
return "KEYWORD_THIS";
case TOKEN_KEYWORD_OPEN:
return "TOKEN_KEYWORD_OPEN";
case TOKEN_KEYWORD_READ:
return "TOKEN_KEYWORD_READ";
case TOKEN_KEYWORD_WRITE:
return "TOKEN_KEYWORD_WRITE";
case TOKEN_KEYWORD_REFRESH:
return "TOKEN_KEYWORD_REFRESH";
case TOKEN_KEYWORD_CLOSE:
return "TOKEN_KEYWORD_CLOSE";
case TOKEN_KEYWORD_NIL:
return "KEYWORD_NIL";
case TOKEN_KEYWORD_TRUE:
return "KEYWORD_TRUE";
case TOKEN_KEYWORD_FALSE:
return "KEYWORD_FALSE";
case TOKEN_KEYWORD_GLOBAL:
return "KEYWORD_GLOBAL";
case TOKEN_OPERATOR_NOT:
return "OPERATOR_NOT";
case TOKEN_OPERATOR_AND:
return "OPERATOR_AND";
case TOKEN_OPERATOR_OR:
return "OPERATOR_OR";
case TOKEN_BANG:
return "BANG";
case TOKEN_BANG_EQ:
return "BANG_EQ";
case TOKEN_EQ:
return "EQ";
case TOKEN_EQ_EQ:
return "EQ_EQ";
case TOKEN_GT:
return "GT";
case TOKEN_LT:
return "LT";
case TOKEN_GTE:
return "GTE";
case TOKEN_LTE:
return "LTE";
case TOKEN_DOT:
return "DOT";
case TOKEN_COMMA:
return "COMMA";
case TOKEN_COLON:
return "COLON";
case TOKEN_SEMICOLON:
return "SEMICOLON";
case TOKEN_PLUS:
return "PLUS";
case TOKEN_MINUS:
return "MINUS";
case TOKEN_STAR:
return "STAR";
case TOKEN_SLASH:
return "SLASH";
case TOKEN_LPAREN:
return "LPAREN";
case TOKEN_RPAREN:
return "RPAREN";
case TOKEN_LBRACE:
return "LBRACE";
case TOKEN_RBRACE:
return "RBRACE";
case TOKEN_LBRACKET:
return "LBRACKET";
case TOKEN_RBRACKET:
return "RBRACKET";
case TOKEN_ARROW_RIGHT:
return "ARROW_RIGHT";
case TOKEN_MESH:
return "MESH";
case TOKEN_BIG_MONEY:
return "BIG_MONEY";
case TOKEN_AND:
return "AND";
case TOKEN_AND_AND:
return "AND_AND";
case TOKEN_ERROR:
return "ERROR";
default:
return "UNKNOWN_TOKEN";
}
}

View File

@ -1,6 +1,8 @@
#ifndef UNDAR_LEXER_H
#define UNDAR_LEXER_H
#include "../../vm/libc.h"
typedef enum {
TOKEN_EOF,
TOKEN_IDENTIFIER,
@ -75,14 +77,31 @@ typedef enum {
TOKEN_ERROR
} TokenType;
typedef struct {
typedef struct token_s Token;
typedef struct parser_s Parser;
typedef struct lexer_s Lexer;
struct token_s{
TokenType type;
const char *start;
int length;
int line;
} Token;
};
void init_lexer(const char *source);
struct lexer_s {
const char *start;
const char *current;
int line;
};
struct parser_s {
Token current;
Token previous;
};
void initLexer(const char *source);
Token next_token();
const char* token_type_to_string(TokenType type);
#endif

View File

@ -26,6 +26,18 @@ typedef float f32;
#define FLOAT_TO_REAL(v) (((i32)(v)) * 65536.0f)
#define REAL_TO_FLOAT(v) (((f32)(v)) / 65536.0f)
#define I8_MIN -128
#define I8_MAX 127
#define U8_MAX 255
#define I16_MIN -32768
#define I16_MAX 32767
#define U16_MAX 65535
#define I32_MIN -2147483648
#define I32_MAX 2147483647
#define U32_MAX 4294967295
void mcpy(void *dest, void *src, u32 n);
i32 scpy(char* to, const char *from, u32 length);
bool seq(const char *s1, const char *s2);

686
vm/vm.c
View File

@ -1,19 +1,19 @@
#include "vm.h"
#define FRAME_HEADER_SIZE 12
u32 pc; /* program counter */
u32 cp; /* code pointer */
u32 mp; /* memory pointer */
u32 fp; /* frame pointer */
u8 lc; /* child local count */
u8 status; /* status flag */
u8 interrupt; /* device interrupt */
u32 *code; /* code */
u8 *mem; /* memory */
u32 *stack; /* stack */
u32 sp; /* stack pointer */
u8 *code; /* code */
u32 cp; /* code pointer */
u8 *mem; /* memory */
u32 mp; /* memory pointer */
Frame *frames; /* call frames */
u32 fp; /* frame pointer */
u32 pc; /* program counter */
u8 status; /* status flag */
u8 interrupt; /* device interrupt */
#define MAX_LEN_INT32 11
#define MAX_INT32 2147483647
#define MIN_INT32 -2147483648
const char radix_set[11] = "0123456789";
u32 str_alloc(char *str, u32 length) {
@ -28,366 +28,279 @@ u32 str_alloc(char *str, u32 length) {
}
bool step_vm() {
u32 instruction = code[pc++];
u8 opcode = DECODE_OP(instruction);
u32 *locals = (u32*)(&mem[fp]);
u32 *globals = (u32*)(mem);
u16 opcode = code[pc++];
switch (opcode) {
case OP_HALT: {
/* no need to decode, all are zeros */
return false;
}
case OP_CALL: {
DECODE_A(instruction)
/* function to jump to */
u32 fn_ptr = locals[dest];
/* get mp in 'global indexing mode' */
u32 *header = &globals[mp / 4];
/* reset child locals counter */
lc = 0;
/* push parents frame value to reset the heap to */
(*header++) = fp;
/* push return address to child frame */
(*header++) = pc;
/* push local address to return the value to */
(*header++) = fp + (src2 * 4);
/* increase the mp to new size */
mp += FRAME_HEADER_SIZE;
/* now set the frame pointer, where the locals start */
fp = mp;
/* move mp forward by count many locals */
mp += (src1 * 4);
/* jump to dest_ptr */
u32 fn_ptr = stack[--sp];
frames[fp].return_pc = pc;
frames[fp++].start_mp = mp;
pc = fn_ptr;
return true;
}
case OP_RETURN: {
DECODE_B(instruction)
u32 size = 0;
u32 return_value = locals[dest];
bool is_ptr = (((u32)(1)) << 15) & imm;
bool replaces_value = (((u32)(1)) << 14) & imm;
/* reset mp to saved mp, use header size to get "real" start of frame */
u32 *frame_start = &globals[(fp / 4) - 3];
u32 parent_fp = *frame_start++;
u32 return_address = *frame_start++;
u32 parent_local_return_address = *frame_start++;
USED(replaces_value);
/* reset memory to parents end of memory */
mp = fp - FRAME_HEADER_SIZE;
/* reset the frame pointer */
fp = parent_fp;
if (is_ptr) {
/* copy value to end of mp if it is a pointer */
globals[parent_local_return_address/4] = mp;
size = globals[return_value/4];
globals[mp/4] = size;
mp += 4;
mcpy(&mem[mp], &mem[return_value], size);
mp += size;
} else {
/* otherwise just write the return value to its location */
mcpy(&mem[parent_local_return_address], &return_value, sizeof(u32));
}
/* jump to parent frame */
pc = return_address;
u32 return_pc = frames[--fp].return_pc;
u32 return_mp = frames[fp].start_mp;
mp = return_mp;
pc = return_pc;
return true;
}
case OP_SYSCALL: {
DECODE_A(instruction)
u32 id = dest; /* syscall id */
u32 size = src1; /* size of heap at that pointer */
u32 rd = locals[src2]; /* the pointer */
status = syscall(id, size, rd);
u32 id = stack[--sp]; /* syscall id */
u32 rd = stack[--sp]; /* the pointer */
status = syscall(id, rd);
return true;
}
case OP_PUSH: {
DECODE_B(instruction)
USED(imm);
globals[(mp / 4) + lc + 3] = locals[dest];
lc++;
case OP_PUSH_8: {
u8 value = code[pc++];
stack[sp++] = value;
return true;
}
case OP_PUSH_16: {
u16 *values = (u16*)(code);
u16 value = values[pc/2];
pc+=2;
stack[sp++] = value;
return true;
}
case OP_PUSH_32: {
u32 value = ((u32)code[(pc) + 3] << 24) |
((u32)code[(pc) + 2] << 16) |
((u32)code[(pc) + 1] << 8) | ((u32)mem[(pc)]);
pc+=4;
stack[sp++] = value;
return true;
}
case OP_PUSH_MP: {
stack[sp++] = mp;
return true;
}
case OP_PUSH_START_MP: {
stack[sp++] = frames[fp - 1].start_mp;
return true;
}
case OP_POP: {
DECODE_B(instruction)
USED(dest);
USED(imm);
mp -= 4;
lc--;
--sp;
return true;
}
case OP_LOAD_IMM: {
DECODE_B(instruction)
locals[dest] = imm;
case OP_SET:{
Frame *f = &frames[fp - 1];
u32 *locals = f->locals;
u8 ptr = (u8)stack[--sp];
u32 value = stack[--sp];
locals[ptr] = value;
return true;
}
case OP_LOAD_UPPER_IMM: {
DECODE_B(instruction)
u32 value = locals[dest];
locals[dest] = (value | (((u32)(imm)) << 16));
case OP_SET_IMM:{
Frame *f = &frames[fp - 1];
u32 *locals = f->locals;
u8 ptr = code[pc++];
u32 value = stack[--sp];
locals[ptr] = value;
return true;
}
case OP_LOAD_IND_8: {
DECODE_A(instruction)
USED(src2);
locals[dest] = READ_U8(locals[src1]);
case OP_GET:{
Frame *f = &frames[fp - 1];
u32 *locals = f->locals;
u8 ptr = (u8)stack[--sp];
stack[sp++] = locals[ptr];
return true;
}
case OP_LOAD_IND_16: {
DECODE_A(instruction)
USED(src2);
locals[dest] = READ_U16(locals[src1]);
case OP_GET_IMM:{
Frame *f = &frames[fp - 1];
u32 *locals = f->locals;
u8 ptr = code[pc++];
stack[sp++] = locals[ptr];
return true;
}
case OP_LOAD_IND_32: {
DECODE_A(instruction)
USED(src2);
locals[dest] = READ_U32(locals[src1]);
case OP_LOAD_8: {
u32 ptr = stack[--sp];
u32 value = mem[ptr];
stack[sp++] = value;
return true;
}
case OP_LOAD_ABS_8: {
/* need multibyte for this, ignore for now */
status = 250;
return false;
}
case OP_LOAD_ABS_16: {
/* need multibyte for this, ignore for now */
status = 250;
return false;
}
case OP_LOAD_ABS_32: {
/* need multibyte for this, ignore for now */
status = 250;
return false;
}
case OP_LOAD_OFF_8: {
DECODE_A(instruction)
locals[dest] = READ_U8((locals[src1] + locals[src2]));
case OP_LOAD_16: {
u32 ptr = stack[--sp];
u16 *values = (u16*)(&mem[ptr]);
u32 value = values[0];
stack[sp++] = value;
return true;
}
case OP_LOAD_OFF_16: {
DECODE_A(instruction)
locals[dest] = READ_U16((locals[src1] + locals[src2]));
case OP_LOAD_32: {
u32 ptr = stack[--sp];
u32 *values = (u32*)(&mem[ptr]);
u32 value = values[0];
stack[sp++] = value;
return true;
}
case OP_LOAD_OFF_32: {
DECODE_A(instruction)
locals[dest] = READ_U32((locals[src1] + locals[src2]));
case OP_STORE_8: {
u32 ptr = stack[--sp];
u8 value = (u8)stack[--sp];
mem[ptr] = value;
return true;
}
case OP_STORE_ABS_8: {
/* need multibyte for this, ignore for now */
status = 250;
return false;
}
case OP_STORE_ABS_16: {
/* need multibyte for this, ignore for now */
status = 250;
return false;
}
case OP_STORE_ABS_32: {
/* need multibyte for this, ignore for now */
status = 250;
return false;
}
case OP_STORE_IND_8: {
DECODE_A(instruction)
USED(src2);
WRITE_U8(locals[dest], locals[src1]);
case OP_STORE_16: {
u32 ptr = stack[--sp];
u16 value = (u16)stack[--sp];
u16 *values = (u16*)(&mem[ptr]);
values[0] = value;
return true;
}
case OP_STORE_IND_16: {
DECODE_A(instruction)
USED(src2);
WRITE_U16(locals[dest], locals[src1]);
return true;
}
case OP_STORE_IND_32: {
DECODE_A(instruction)
USED(src2);
WRITE_U32(locals[dest], locals[src1]);
return true;
}
case OP_STORE_OFF_8: {
DECODE_A(instruction)
WRITE_U8((locals[dest] + locals[src2]), locals[src1]);
return true;
}
case OP_STORE_OFF_16: {
DECODE_A(instruction)
WRITE_U16((locals[dest] + locals[src2]), locals[src1]);
return true;
}
case OP_STORE_OFF_32: {
DECODE_A(instruction)
WRITE_U32((locals[dest] + locals[src2]), locals[src1]);
case OP_STORE_32: {
u32 ptr = stack[--sp];
u32 value = stack[--sp];
u32 *values = (u32*)(&mem[ptr]);
values[0] = value;
return true;
}
case OP_MEM_ALLOC: {
DECODE_A(instruction)
u32 size = locals[src1];
locals[dest] = mp;
u32 size = stack[--sp];
stack[sp++] = mp;
WRITE_U32(mp, size);
USED(src2);
mp += (size + 4);
return true;
}
case OP_MEM_CPY_8: {
DECODE_A(instruction)
u32 i = 0;
u32 mdest = locals[dest];
u32 msrc = locals[src1];
u32 count = locals[src2];
u8 *ptr_src;
u8 *ptr_dest;
u32 count = stack[--sp];
u32 src = stack[--sp];
u32 dest = stack[--sp];
if (mdest + count >= mp) {
if (dest + count >= mp) {
status = 1;
return true;
}
for (i = 0; i < count; i++) {
mem[msrc + i] = mem[mdest + i];
}
ptr_dest = &mem[dest];
ptr_src = &mem[src];
if (ptr_dest == ptr_src) { return true; }
mcpy(ptr_dest, ptr_src, count*sizeof(u8));
status = 0;
return true;
}
case OP_MEM_CPY_16: {
DECODE_A(instruction)
u32 i = 0;
u32 mdest = locals[dest];
u32 msrc = locals[src1];
u32 count = locals[src2] * 2;
u8 *ptr_src;
u8 *ptr_dest;
u32 count = stack[--sp];
u32 src = stack[--sp];
u32 dest = stack[--sp];
if (mdest + count >= mp) {
if (dest + count >= mp) {
status = 1;
return true;
}
for (i = 0; i < count; i++) {
u16 value = READ_U16(mdest + i);
WRITE_U16(msrc + i, value);
}
ptr_dest = &mem[dest];
ptr_src = &mem[src];
if (ptr_dest == ptr_src) { return true; }
mcpy(ptr_dest, ptr_src, count*sizeof(u16));
status = 0;
return true;
}
case OP_MEM_CPY_32: {
DECODE_A(instruction)
u32 i = 0;
u32 mdest = locals[dest];
u32 msrc = locals[src1];
u32 count = locals[src2];
u8 *ptr_src;
u8 *ptr_dest;
u32 count = stack[--sp];
u32 src = stack[--sp];
u32 dest = stack[--sp];
if (mdest + count >= mp) {
if (dest + count >= mp) {
status = 1;
return true;
}
for (i = 0; i < count; i++) {
globals[msrc + i] = globals[mdest + i];
}
ptr_dest = &mem[dest];
ptr_src = &mem[src];
if (ptr_dest == ptr_src) { return true; }
mcpy(ptr_dest, ptr_src, count*sizeof(u32));
status = 0;
return true;
}
case OP_MEM_SET_8: {
DECODE_A(instruction)
u32 i, start, end;
u8 *ptr_dest;
u8 value = (u8)stack[--sp];
u32 count = stack[--sp];
u32 dest = stack[--sp];
u32 rd = fp + (dest * 4);
u32 r1 = fp + (src1 * 4);
u32 r2 = fp + (src2 * 4);
u8 value = (u8)READ_U32(r1);
u32 count = READ_U32(r2);
if (r2 == 0) {
if (dest + count >= mp) {
status = 1;
return true;
}
start = READ_U32(rd);
end = start + count;
if (start >= mp || r2 > mp || end > mp) {
status = 1;
return true;
}
for (i = start; i < end; i++) {
mem[i] = value;
}
ptr_dest = &mem[dest];
mcpy(ptr_dest, &value, count*sizeof(u8));
status = 0;
return true;
}
case OP_MEM_SET_16: {
DECODE_A(instruction)
u32 i, start, end;
u8 *ptr_dest;
u16 value = (u16)stack[--sp];
u32 count = stack[--sp];
u32 dest = stack[--sp];
u32 rd = fp + (dest * 4);
u32 r1 = fp + (src1 * 4);
u32 r2 = fp + (src2 * 4);
u16 value = (u16)READ_U32(r1);
u32 count = READ_U32(r2);
if (r2 == 0) {
if (dest + count >= mp) {
status = 1;
return true;
}
start = READ_U32(rd);
end = start + count;
if (start >= mp || r2 > mp || end > mp) {
status = 1;
return true;
}
for (i = start; i < end; i += 2) {
WRITE_U16(i, value);
}
ptr_dest = &mem[dest];
mcpy(ptr_dest, &value, count*sizeof(u16));
status = 0;
return true;
}
case OP_MEM_SET_32: {
DECODE_A(instruction)
u32 i, start, end;
u8 *ptr_dest;
u32 value = stack[--sp];
u32 count = stack[--sp];
u32 dest = stack[--sp];
u32 value = locals[src1];
u32 count = locals[src2];
if (count == 0) {
if (dest + count >= mp) {
status = 1;
return true;
}
start = READ_U32(locals[dest]);
end = start + count;
if (start >= mp || count > mp || end > mp) {
status = 1;
return true;
}
for (i = start; i < end; i += 4) {
WRITE_U32(i, value);
}
ptr_dest = &mem[dest];
mcpy(ptr_dest, &value, count*sizeof(u32));
status = 0;
return true;
}
case OP_MOV: {
DECODE_A(instruction)
USED(src2);
locals[dest] = locals[src1];
case OP_DUP: {
u32 a = stack[--sp];
stack[sp++] = a;
stack[sp++] = a;
return true;
}
case OP_EXCH: {
u32 a = stack[--sp];
u32 b = stack[--sp];
stack[sp++] = b;
stack[sp++] = a;
return true;
}
case OP_OVER: {
u32 a = stack[sp - 1];
stack[sp++] = a;
return true;
}
case OP_PICK: {
u32 n = stack[--sp];
u32 b = stack[sp - n];
stack[sp++] = b;
return true;
}
case OP_DEPTH: {
u32 a = sp;
stack[sp++] = a;
return true;
}
case OP_ADD_INT: {
@ -421,27 +334,27 @@ bool step_vm() {
MATH_OP(i32, -);
}
case OP_MUL_REAL: {
DECODE_A(instruction)
i32 src1 = (i32)stack[--sp];
i32 src2 = (i32)stack[--sp];
i32 src1_whole = (i32)locals[src1] >> 16;
i32 src2_whole = (i32)locals[src2] >> 16;
i32 src1_whole = src1 >> 16;
i32 src2_whole = src2 >> 16;
i32 src1_decimal = (i32)locals[src1] & 16;
i32 src2_decimal = (i32)locals[src2] & 16;
i32 src1_decimal = src1 & 16;
i32 src2_decimal = src2 & 16;
i32 result = 0;
result += (src1_whole * src2_whole) << 16;
result += (src1_whole * src2_decimal);
result += (src1_decimal * src2_whole);
result += ((src1_decimal * src2_decimal) >> 16) & 16;
locals[dest] = result;
stack[sp++] = result;
return true;
}
case OP_DIV_REAL: {
DECODE_A(instruction)
i32 result;
i32 src1_val = (i32)locals[src1];
i32 src2_val = (i32)locals[src2];
i32 src1_val = (i32)stack[--sp];
i32 src2_val = (i32)stack[--sp];
u32 src2_reciprocal = 1;
src2_reciprocal <<= 31;
@ -450,180 +363,128 @@ bool step_vm() {
result = src1_val * src2_reciprocal;
result <<= 1;
locals[dest] = result;
stack[sp++] = result;
return true;
}
case OP_INT_TO_REAL: {
DECODE_A(instruction)
i32 result = (i32)locals[src1] << 16;
USED(src2);
locals[dest] = result;
i32 result = (i32)stack[--sp] << 16;
stack[sp++] = result;
return true;
}
case OP_INT_TO_NAT: {
DECODE_A(instruction)
u32 result = (u32)locals[src1];
USED(src2);
locals[dest] = result;
u32 result = (u32)stack[--sp];
stack[sp++] = result;
return true;
}
case OP_NAT_TO_REAL: {
DECODE_A(instruction)
i32 result = (i32)locals[src1] << 16;
USED(src2);
locals[dest] = result;
i32 result = (i32)stack[--sp] << 16;
stack[sp++] = result;
return true;
}
case OP_NAT_TO_INT: {
DECODE_A(instruction)
i32 result = (i32)locals[src1];
USED(src2);
locals[dest] = result;
i32 result = (i32)stack[--sp];
stack[sp++] = result;
return true;
}
case OP_REAL_TO_INT: {
DECODE_A(instruction)
i32 result = (i32)locals[src1] >> 16;
USED(src2);
locals[dest] = result;
i32 result = (i32)stack[--sp] >> 16;
stack[sp++] = result;
return true;
}
case OP_REAL_TO_NAT: {
DECODE_A(instruction)
u32 result = (u32)locals[src1] >> 16;
USED(src2);
locals[dest] = result;
u32 result = (u32)stack[--sp] >> 16;
stack[sp++] = result;
return true;
}
case OP_NEG: {
i32 a = (i32)stack[--sp];
stack[sp++] = -a;
return true;
}
case OP_NOT: {
u32 a = !stack[--sp];
stack[sp++] = a;
return true;
}
case OP_BIT_SHIFT_LEFT: {
MATH_OP_NO_CAST(<<);
MATH_OP(u32, <<);
}
case OP_BIT_SHIFT_RIGHT: {
MATH_OP_NO_CAST(>>);
MATH_OP(u32, >>);
}
case OP_BIT_SHIFT_R_EXT: {
MATH_OP(i32, >>);
}
case OP_BIT_AND: {
MATH_OP_NO_CAST(&);
MATH_OP(u32, &);
}
case OP_BIT_OR: {
MATH_OP_NO_CAST(|);
MATH_OP(u32, |);
}
case OP_BIT_XOR: {
MATH_OP_NO_CAST(^);
MATH_OP(u32, ^);
}
case OP_JMP_IMM: {
u32 imm = (((u32)code[(pc) + 3] << 24) |
((u32)code[(pc) + 2] << 16) |
((u32)code[(pc) + 1] << 8) |
((u32)code[(pc)]));
pc = imm;
return true;
case OP_EQS: {
MATH_OP(i32, ==);
}
case OP_JMP_ABS: {
DECODE_A(instruction)
u32 jmp_dest = locals[dest];
if (jmp_dest > cp) {
status = 1;
return true;
}
USED(src1);
USED(src2);
pc = jmp_dest;
return true;
case OP_NES: {
MATH_OP(i32, !=);
}
case OP_JMP_OFF: {
DECODE_A(instruction)
u32 jmp_dest = locals[dest] + locals[src1];
if (jmp_dest > cp) {
status = 1;
return true;
}
USED(src2);
pc = jmp_dest;
case OP_GTS: {
MATH_OP(i32, >);
}
case OP_LTS: {
MATH_OP(i32, <);
}
case OP_LES: {
MATH_OP(i32, <=);
}
case OP_GES: {
MATH_OP(i32, >=);
}
case OP_EQU: {
MATH_OP(u32, ==);
}
case OP_NEU: {
MATH_OP(u32, !=);
}
case OP_GTU: {
MATH_OP(u32, >);
}
case OP_LTU: {
MATH_OP(u32, <);
}
case OP_LEU: {
MATH_OP(u32, <=);
}
case OP_GEU: {
MATH_OP(u32, >=);
}
case OP_JMP: {
pc = stack[--sp];
return true;
}
case OP_JMP_FLAG: {
DECODE_A(instruction)
u32 mask;
u32 jmp_dest = locals[dest];
if (jmp_dest > cp) {
status = 1;
return true;
}
USED(src1);
USED(src2);
u32 jmp_dest = stack[--sp];
mask = -(u32)(status == 0);
pc = (jmp_dest & mask) | (pc & ~mask);
return true;
}
case OP_JEQ_INT: {
COMPARE_AND_JUMP(i32, ==);
case OP_JNZ: {
u32 mask;
u32 target = stack[--sp];
i32 cond = stack[--sp];
mask = -(u32)cond;
pc = (target & mask) | (pc & ~mask);
return true;
}
case OP_JNE_INT: {
COMPARE_AND_JUMP(i32, !=);
}
case OP_JGT_INT: {
COMPARE_AND_JUMP(i32, >);
}
case OP_JLT_INT: {
COMPARE_AND_JUMP(i32, <);
}
case OP_JLE_INT: {
COMPARE_AND_JUMP(i32, <=);
}
case OP_JGE_INT: {
COMPARE_AND_JUMP(i32, >=);
}
case OP_JEQ_NAT: {
COMPARE_AND_JUMP(u32, ==);
}
case OP_JNE_NAT: {
COMPARE_AND_JUMP(u32, !=);
}
case OP_JGT_NAT: {
COMPARE_AND_JUMP(u32, >);
}
case OP_JLT_NAT: {
COMPARE_AND_JUMP(u32, <);
}
case OP_JLE_NAT: {
COMPARE_AND_JUMP(u32, <=);
}
case OP_JGE_NAT: {
COMPARE_AND_JUMP(u32, >=);
}
case OP_JEQ_REAL: {
COMPARE_AND_JUMP(i32, ==);
}
case OP_JNE_REAL: {
COMPARE_AND_JUMP(i32, !=);
}
case OP_JGE_REAL: {
COMPARE_AND_JUMP(i32, >=);
}
case OP_JGT_REAL: {
COMPARE_AND_JUMP(i32, >);
}
case OP_JLT_REAL: {
COMPARE_AND_JUMP(i32, <);
}
case OP_JLE_REAL: {
COMPARE_AND_JUMP(i32, <=);
}
case OP_INT_TO_STR: {
DECODE_A(instruction)
case OP_INT_TO_STR: {
u32 i = MAX_LEN_INT32;
i32 v = (i32)locals[src1];
i32 v = (i32)stack[--sp];
char buffer[MAX_LEN_INT32];
i32 n = v;
bool neg = n < 0;
USED(src2);
if (neg)
n = -n;
@ -639,18 +500,16 @@ bool step_vm() {
buffer[--i] = '0';
/* Copy from buffer[i] to buffer + MAX_LEN_INT32 */
locals[dest] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
stack[sp++] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
return pc;
return true;
}
case OP_NAT_TO_STR: {
DECODE_A(instruction)
u32 v = (i32)locals[src1];
u32 v = (i32)stack[--sp];
char buffer[MAX_LEN_INT32];
u32 n = v;
u32 i = MAX_LEN_INT32;
USED(src2);
do {
buffer[--i] = radix_set[n % 10];
n /= 10;
@ -659,15 +518,13 @@ bool step_vm() {
if (v == 0)
buffer[--i] = '0';
/* Copy from buffer[i] to buffer + MAX_LEN_INT32 */
locals[dest] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
stack[sp++] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
return pc;
return true;
}
case OP_REAL_TO_STR: {
DECODE_A(instruction)
u32 i = 0, j = 0;
i32 q = (i32)locals[src1];
i32 q = (i32)stack[--sp];
char buffer[MAX_LEN_INT32];
u32 int_part, frac_part;
@ -678,7 +535,6 @@ bool step_vm() {
int_part = q >> 16;
frac_part = q & 0xFFFF;
USED(src2);
if (int_part == 0) {
buffer[i++] = radix_set[0];
@ -701,9 +557,9 @@ bool step_vm() {
frac_part &= 0xFFFF;
}
locals[dest] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
stack[sp++] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
return pc;
return true;
}
}

257
vm/vm.h
View File

@ -3,122 +3,88 @@
#include "libc.h"
/**
* Instruction Types
*
* A : [8:opcode][8:dest][8:src1][8:src2]
* B : [8:opcode][8:dest][16:immediate]
* C : [8:opcode][24:immediate]
*/
#define DECODE_OP(instruction) ((((u32)(instruction)) >> 24) & 0xFF)
#define ENCODE_A(opcode, dest, src1, src2) ((((u32)(opcode) & 0xFF) << 24) | \
(((u32)(dest) & 0xFF) << 16) | \
(((u32)(src1) & 0xFF) << 8) | \
(((u32)(src2) & 0xFF)))
#define DECODE_A(instruction) \
u8 dest = (((u32)(instruction)) >> 16) & 0xFF; \
u8 src1 = (((u32)(instruction)) >> 8) & 0xFF; \
u8 src2 = ((u32)(instruction)) & 0xFF;
#define ENCODE_B(opcode, dest, imm) ((((u32)(opcode) & 0xFF) << 24) | \
(((u32)(dest) & 0xFF) << 16) | \
(((u32)(imm)) & 0xFFFF))
#define DECODE_B(instruction) \
u8 dest = (((u32)(instruction)) >> 16) & 0xFF; \
u16 imm = ((u32)(instruction)) & 0xFFFF;
#define ENCODE_C(opcode, imm) ((((u32)(opcode) & 0xFF) << 24) | \
(((u32)(imm)) & 0xFFFFFF))
#define DECODE_C(instruction) \
u32 imm = ((u32)(instruction)) & 0xFFFFFF;
typedef enum {
OP_HALT, /* halt : A : all zeros : halt execution */
OP_CALL, /* call : A : dest args return : creates a new frame */
OP_RETURN, /* return : B : dest return_flags: returns from a frame to the parent frame */
OP_SYSCALL, /* syscall : A : id args mem_ptr : does a system call based on id with args */
OP_LOAD_IMM, /* load_immediate : B : locals[dest] = const as u16 */
OP_LOAD_UPPER_IMM, /* load_upper_immediate : B : locals[dest] = const as u32 << 16 | u16 */
OP_LOAD_IND_8, /* load_indirect_8 : A : locals[dest] = memory[locals[src1]] as u8 */
OP_LOAD_IND_16, /* load_indirect_16 : A : locals[dest] = memory[locals[src1]] as u16 */
OP_LOAD_IND_32, /* load_indirect_32 : A : locals[dest] = memory[locals[src1]] as u32 */
OP_LOAD_ABS_8, /* load_absolute_8 : E : locals[dest] = memory[src1:u32] as u8 */
OP_LOAD_ABS_16, /* load_absolute_16 : E : locals[dest] = memory[src1:u32] as u16 */
OP_LOAD_ABS_32, /* load_absolute_32 : E : locals[dest] = memory[src1:u32] as u32 */
OP_LOAD_OFF_8, /* load_offset_8 : A : locals[dest] = memory[locals[src1] + locals[src2]] as u8 */
OP_LOAD_OFF_16, /* load_offset_16 : A : locals[dest] = memory[locals[src1] + locals[src2]] as u16 */
OP_LOAD_OFF_32, /* load_offset_32 : A : locals[dest] = memory[locals[src1] + locals[src2]] as u32 */
OP_STORE_ABS_8, /* store_absolute_8 : E : memory[dest] = src1 && 0xFF */
OP_STORE_ABS_16, /* store_absolute_16 : E : memory[dest] = src1 && 0xFFFF */
OP_STORE_ABS_32, /* store_absolute_32 : E : memory[dest] = src1 */
OP_STORE_IND_8, /* store_indirect_8 : A : memory[locals[dest]] = locals[src1] && 0xFF */
OP_STORE_IND_16, /* store_indirect_16 : A : memory[locals[dest]] = locals[src1] && 0xFFFF*/
OP_STORE_IND_32, /* store_indirect_32 : A : memory[locals[dest]] = locals[src1] */
OP_STORE_OFF_8, /* store_offset_8 : A : memory[locals[dest] + locals[src2]] = locals[src1] && 0xFF */
OP_STORE_OFF_16, /* store_offset_16 : A : memory[locals[dest] + locals[src2]] = locals[src1] && 0xFFFF */
OP_STORE_OFF_32, /* store_offset_32 : A : memory[locals[dest] + locals[src2]] = locals[src1] */
OP_MEM_ALLOC, /* alloc : A : memory[dest] = [locals[src1] as size + 4] */
OP_MEM_CPY_8, /* memcpy_8 : A : memory[src1..src1+src2] = memory[dest..dest+src2] */
OP_MEM_CPY_16, /* memcpy_16 : A : memory[src1..src1+src2] = memory[dest..dest+src2] */
OP_MEM_CPY_32, /* memcpy_32 : A : memory[src1..src1+src2] = memory[dest..dest+src2] */
OP_MEM_SET_8, /* memset_8 : A : memory[dest..dest+src2] = local[src1] as u8 */
OP_MEM_SET_16, /* memset_16 : A : memory[dest..dest+src2] = local[src1] as u16 */
OP_MEM_SET_32, /* memset_32 : A : memory[dest..dest+src2] = local[src1] as u32 */
OP_MOV, /* mov : A : locals[dest] = locals[src1] */
OP_PUSH, /* push : B : push u32 value onto the childs locals */
OP_POP, /* pop : C : pop u32 value off the stack (move MP back) */
OP_ADD_INT, /* add_int : A : locals[dest] = locals[src1] + locals[src2] */
OP_SUB_INT, /* sub_int : A : locals[dest] = locals[src1] - locals[src2] */
OP_MUL_INT, /* mul_int : A : locals[dest] = locals[src1] * locals[src2] */
OP_DIV_INT, /* div_int : A : locals[dest] = locals[src1] / locals[src2] */
OP_ADD_NAT, /* add_nat : A : locals[dest] = locals[src1] + locals[src2] */
OP_SUB_NAT, /* sub_nat : A : locals[dest] = locals[src1] - locals[src2] */
OP_MUL_NAT, /* mul_nat : A : locals[dest] = locals[src1] * locals[src2] */
OP_DIV_NAT, /* div_nat : A : locals[dest] = locals[src1] / locals[src2] */
OP_ADD_REAL, /* add_real : A : locals[dest] = locals[src1] + locals[src2] */
OP_SUB_REAL, /* sub_real : A : locals[dest] = locals[src1] - locals[src2] */
OP_MUL_REAL, /* mul_real : A : locals[dest] = locals[src1] * locals[src2] */
OP_DIV_REAL, /* div_real : A : locals[dest] = locals[src1] / locals[src2] */
OP_INT_TO_REAL, /* int_to_real : A : locals[dest] = locals[src1] as real */
OP_INT_TO_NAT, /* int_to_nat : A : locals[dest] = locals[src1] as nat */
OP_NAT_TO_REAL, /* nat_to_real : A : locals[dest] = locals[src1] as real */
OP_NAT_TO_INT, /* nat_to_int : A : locals[dest] = locals[src1] as int */
OP_REAL_TO_INT, /* real_to_int : A : locals[dest] = locals[src1] as int */
OP_REAL_TO_NAT, /* real_to_nat : A : locals[dest] = locals[src1] as nat */
OP_BIT_SHIFT_LEFT, /* bit_shift_left : A : locals[dest] = locals[src1] << locals[src2] */
OP_BIT_SHIFT_RIGHT,/* bit_shift_right : A : locals[dest] = locals[src1] >> locals[src2] */
OP_BIT_SHIFT_R_EXT,/* bit_shift_r_ext : A : locals[dest] as i32 = locals[src1] >> locals[src2] */
OP_BIT_AND, /* bit_and : A : locals[dest] = locals[src1] & locals[src2] */
OP_BIT_OR, /* bit_or : A : locals[dest] = locals[src1] | locals[src2] */
OP_BIT_XOR, /* bit_xor : A : locals[dest] = locals[src1] ^ locals[src2] */
OP_JMP_IMM, /* jump_immediate : E : jump to imm unconditionally */
OP_JMP_ABS, /* jump_absolute : A : jump to locals[dest] unconditionally */
OP_JMP_OFF, /* jump_offset : A : jump to locals[dest] + locals[src1] unconditionally */
OP_JMP_FLAG, /* jump_if_flag : A : jump to locals[dest] if flag > 0 */
OP_JEQ_INT, /* jump_eq_int : A : jump to locals[dest] if locals[src1] as int == locals[src2] as int */
OP_JNE_INT, /* jump_neq_int : A : jump to locals[dest] if locals[src1] as int != locals[src2] as int */
OP_JGT_INT, /* jump_gt_int : A : jump to locals[dest] if locals[src1] as int > locals[src2] as int */
OP_JLT_INT, /* jump_lt_int : A : jump to locals[dest] if locals[src1] as int < locals[src2] as int */
OP_JLE_INT, /* jump_le_int : A : jump to locals[dest] if locals[src1] as int <= locals[src2] as int */
OP_JGE_INT, /* jump_ge_int : A : jump to locals[dest] if locals[src1] as int >= locals[src2] as int */
OP_JEQ_NAT, /* jump_eq_nat : A : jump to locals[dest] if locals[src1] as nat == locals[src2] as nat */
OP_JNE_NAT, /* jump_neq_nat : A : jump to locals[dest] if locals[src1] as nat != locals[src2] as nat */
OP_JGT_NAT, /* jump_gt_nat : A : jump to locals[dest] if locals[src1] as nat > locals[src2] as nat */
OP_JLT_NAT, /* jump_lt_nat : A : jump to locals[dest] if locals[src1] as nat < locals[src2] as nat */
OP_JLE_NAT, /* jump_le_nat : A : jump to locals[dest] if locals[src1] as nat <= locals[src2] as nat */
OP_JGE_NAT, /* jump_ge_nat : A : jump to locals[dest] if locals[src1] as nat >= locals[src2] as nat */
OP_JEQ_REAL, /* jump_eq_real : A : jump to locals[dest] if locals[src1] as real == locals[src2] as real */
OP_JNE_REAL, /* jump_neq_real : A : jump to locals[dest] if locals[src1] as real != locals[src2] as real */
OP_JGE_REAL, /* jump_ge_real : A : jump to locals[dest] if locals[src1] as real >= locals[src2] as real */
OP_JGT_REAL, /* jump_gt_real : A : jump to locals[dest] if locals[src1] as real > locals[src2] as real */
OP_JLT_REAL, /* jump_lt_real : A : jump to locals[dest] if locals[src1] as real < locals[src2] as real */
OP_JLE_REAL, /* jump_le_real : A : jump to locals[dest] if locals[src1] as real <= locals[src2] as real */
OP_INT_TO_STR, /* int_to_str : A : locals[dest] = &mem[mp..] locals[src1] as str */
OP_NAT_TO_STR, /* nat_to_str : A : locals[dest] = &mem[mp..] locals[src1] as str */
OP_REAL_TO_STR, /* real_to_str : A : locals[dest] = &mem[mp..] locals[src1] as str */
OP_MAX_OPCODE /* not an opcode count of instructions */
OP_HALT, /* - `halt` | halt execution */
OP_CALL, /* ptr `call` - | creates a new frame */
OP_RETURN, /* - `return` - | returns from a frame to the parent frame */
OP_SYSCALL, /* id mem_ptr `syscall` - | does a system call based on id with args */
OP_LOAD_8, /* dest `ld8` u8 | push memory[obj1] onto stack as u8 */
OP_LOAD_16, /* dest `ld16` u16 | push memory[obj1] onto stack as u16 */
OP_LOAD_32, /* dest `ld32` u32 | push memory[obj1] onto stack as u32 */
OP_STORE_8, /* dest obj1 `st8` - | memory[dest] = obj1 << 8 */
OP_STORE_16, /* dest obj1 `st16` - | memory[dest] = obj1 << 16 */
OP_STORE_32, /* dest obj1 `st32` - | memory[dest] = obj1 */
OP_MALLOC, /* size `alloc` ptr | allocate 'size + 4' of memory and push ptr to memory on stack */
OP_PUSH_8, /* const `push8` obj1 | push a 8 bit const onto the stack */
OP_PUSH_16, /* const `push16` obj1 | push a 16 bit const onto the stack */
OP_PUSH_32, /* const `push32` obj1 | push a 32 bit const onto the stack */
OP_PUSH_MP, /* - `pmp` mp | push current mp to stack */
OP_PUSH_START_MP, /* - `psmp` mp | push the frames start mp to stack (parent frames end mp); used for returning heap values to parent */
OP_SET, /* obj dest `set` - | sets a local to the next value on top of the stack (max 255) */
OP_GET, /* dest `get` obj | pushes a local from the value on top of the stack (max 255) */
OP_SET_IMM, /* obj #dest `seti` - | sets a local to the next immediate location (max 255) */
OP_GET_IMM, /* #dest `geti` obj | pushes a local from the immediate location (max 255) */
OP_POP, /* - `pop` - | removes top item from the stack */
OP_DUP, /* obj1 `dup` obj1 obj1 | duplicates the top of the stack */
OP_EXCH, /* obj2 obj1 `exch` obj1 obj2 | swaps the top two values on the stack */
OP_OVER, /* obj2 obj1 `over` obj2 | copys the 2nd to the top element and pushes to the stack */
OP_PICK, /* N `pick` objN | gets the nth element on the stack and pushes it on top */
OP_DEPTH, /* - `depth` stack_count | pushes the number of elements on the stack to the stack */
OP_MEM_ALLOC, /* size `alloc` ptr | allocate 'size + 4' of memory and push ptr to memory on stack */
OP_MEM_CPY_8, /* size src dest `mcpy8` - | memory[src..src+size] = memory[dest..dest+size] */
OP_MEM_CPY_16, /* size src dest `mcpy16` - | memory[src..src+size] = memory[dest..dest+size] */
OP_MEM_CPY_32, /* size src dest `mcpy32` - | memory[src..src+size] = memory[dest..dest+size] */
OP_MEM_SET_8, /* size src dest `mset8` - | memory[dest..dest+size] = local[src] as u8 */
OP_MEM_SET_16, /* size src dest `mset16` - | memory[dest..dest+size] = local[src] as u16 */
OP_MEM_SET_32, /* size src dest `mset32` - | memory[dest..dest+size] = local[src] as u32 */
OP_ADD_INT, /* obj2 obj1 `addi` obj | obj1 + obj2 then push result on stack */
OP_SUB_INT, /* obj2 obj1 `subi` obj | obj1 - obj2 then push result on stack */
OP_MUL_INT, /* obj2 obj1 `muli` obj | obj1 * obj2 then push result on stack */
OP_DIV_INT, /* obj2 obj1 `divi` obj | obj1 / obj2 then push result on stack */
OP_ADD_NAT, /* obj2 obj1 `addn` obj | obj1 + obj2 then push result on stack */
OP_SUB_NAT, /* obj2 obj1 `subn` obj | obj1 - obj2 then push result on stack */
OP_MUL_NAT, /* obj2 obj1 `muln` obj | obj1 * obj2 then push result on stack */
OP_DIV_NAT, /* obj2 obj1 `divn` obj | obj1 / obj2 then push result on stack */
OP_ADD_REAL, /* obj2 obj1 `addr` obj | obj1 + obj2 then push result on stack */
OP_SUB_REAL, /* obj2 obj1 `subr` obj | obj1 - obj2 then push result on stack */
OP_MUL_REAL, /* obj2 obj1 `mulr` obj | obj1 * obj2 then push result on stack */
OP_DIV_REAL, /* obj2 obj1 `divr` obj | obj1 / obj2 then push result on stack */
OP_INT_TO_REAL, /* obj1 `itor` real | casts an int to a fixed number */
OP_INT_TO_NAT, /* obj1 `iton` nat | casts an int to a unsigned int */
OP_NAT_TO_REAL, /* obj1 `ntor` real | casts a unsigned int to a fixed number */
OP_NAT_TO_INT, /* obj1 `ntoi` int | casts a unsigned int to an int */
OP_REAL_TO_INT, /* obj1 `rtoi` int | casts a fixed number to an int */
OP_REAL_TO_NAT, /* obj1 `rton` nat | casts a fixed number to an unsigned int */
OP_BIT_SHIFT_LEFT, /* obj2 obj1 `sll` obj | src1] << locals[src2] */
OP_BIT_SHIFT_RIGHT, /* obj2 obj1 `srl` obj | src1] >> locals[src2] */
OP_BIT_SHIFT_R_EXT, /* obj2 obj1 `sre` obj | src1 >> src2 then cast result as i32 */
OP_BIT_AND, /* obj2 obj1 `band` obj | obj1 & obj2 */
OP_BIT_OR, /* obj2 obj1 `bor` obj | obj1 | obj2 */
OP_BIT_XOR, /* obj2 obj1 `bxor` obj | obj1 ^ obj2 */
OP_NEG, /* obj1 `neg` obj | -obj1 */
OP_NOT, /* obj1 `not` obj | not obj1 */
OP_JMP, /* pc `jump` | jump unconditionally */
OP_JMP_FLAG, /* pc `jmpf` | jump to pc if flag > 0 */
OP_JNZ, /* obj1 pc `jnz` | jump to pc if obj1 != 0 */
OP_EQU, /* obj2 obj1 `equ` bool | unsigned obj1 == obj2 */
OP_NEU, /* obj2 obj1 `neu` bool | unsigned obj1 != obj2 */
OP_GTU, /* obj2 obj1 `gtu` bool | unsigned obj1 > obj2 */
OP_LTU, /* obj2 obj1 `ltu` bool | unsigned obj1 < obj2 */
OP_LEU, /* obj2 obj1 `leu` bool | unsigned obj1 <= obj2 */
OP_GEU, /* obj2 obj1 `geu` bool | unsigned obj1 >= obj2 */
OP_EQS, /* obj2 obj1 `eqs` bool | signed obj1 == obj2 */
OP_NES, /* obj2 obj1 `nes` bool | signed obj1 != obj2 */
OP_GTS, /* obj2 obj1 `gts` bool | signed obj1 > obj2 */
OP_LTS, /* obj2 obj1 `lts` bool | signed obj1 < obj2 */
OP_LES, /* obj2 obj1 `les` bool | signed obj1 <= obj2 */
OP_GES, /* obj2 obj1 `ges` bool | signed obj1 >= obj2 */
OP_INT_TO_STR, /* obj1 `itos` str_ptr | convert obj1 to str */
OP_NAT_TO_STR, /* obj1 `ntos` str_ptr | convert obj1 to str */
OP_REAL_TO_STR, /* obj1 `rtos` str_ptr | convert obj1 to str */
OP_STR_TO_INT, /* str_ptr `stoi` obj | convert obj1 to int */
OP_STR_TO_NAT, /* str_ptr `ntoi` obj | convert obj1 to nat */
OP_STR_TO_REAL, /* str_ptr `stor` obj | convert obj1 to real */
OP_MAX_OPCODE /* not an opcode count of instructions */
} Opcode;
typedef enum {
@ -127,15 +93,24 @@ typedef enum {
SYSCALL_MAX
} Syscall;
extern u32 pc; /* program counter */
extern u32 cp; /* code pointer */
extern u32 mp; /* memory pointer */
extern u32 fp; /* frame pointer */
extern u8 lc; /* child local count */
extern u8 status; /* status flag */
extern u8 interrupt; /* device interrupt */
extern u32 *code; /* code */
extern u8 *mem; /* memory */
typedef struct frame_s Frame;
struct frame_s {
u32 locals[256];
u32 return_pc;
u32 start_mp;
};
extern u8 *code; /* code */
extern u32 cp; /* code pointer */
extern u8 *mem; /* memory */
extern u32 mp; /* memory pointer */
extern u32 *stack; /* stack */
extern u32 sp; /* stack pointer */
extern Frame *frames; /* call frames */
extern u32 fp; /* frame pointer */
extern u32 pc; /* program counter */
extern u8 status; /* status flag */
extern u8 interrupt; /* device interrupt */
#define READ_U8(addr) (mem[addr])
@ -166,36 +141,16 @@ extern u8 *mem; /* memory */
mem[addr + 3] = ((value) >> 24) & 0xFF; \
} while (0)
#define MATH_OP(type, op) \
do { \
DECODE_A(instruction) \
locals[dest] = ((type)locals[src1] op (type)locals[src2]); \
return true; \
} while (0)
#define MATH_OP_NO_CAST(op) \
do { \
DECODE_A(instruction) \
locals[dest] = (locals[src1] op locals[src2]); \
return true; \
} while (0)
#define COMPARE_AND_JUMP(type, op) \
do { \
DECODE_A(instruction) \
i32 cond; \
u32 mask; \
u32 target = locals[dest]; \
type value = (type)locals[src1]; \
type value2 = (type)locals[src2]; \
cond = !!(value op value2); \
mask = -(u32)cond; \
pc = (target & mask) | (pc & ~mask); \
return true; \
#define MATH_OP(type, op) \
do { \
type b = (type)stack[--sp]; \
type a = (type)stack[--sp]; \
stack[sp++] = (type)(a op b); \
return true; \
} while (0)
extern bool init_vm();
extern u32 syscall(u32 id, u32 args, u32 mem_ptr);
extern u32 syscall(u32 id, u32 mem_ptr);
bool step_vm();
u32 str_alloc(char *str, u32 length);