Compare commits

..

6 Commits

Author SHA1 Message Date
zongor 7fdd4b66b0 small bugfixes, 2026-02-11 22:46:24 -08:00
zongor 3ee4442b3d general cleanup 2026-02-11 16:57:19 -08:00
zongor f4c5577153 Add compiler todo note 2026-02-10 00:43:27 -08:00
zongor f90349c09a wip compiler 2026-02-08 11:00:47 -08:00
zongor 8bde10d5b8 refinement of vm, idea for new locals 2026-02-07 11:35:13 -08:00
zongor f7a4fb5f7f Copy updates, add tests, implement compiler directly, no more assemblers 2026-01-20 23:10:47 -08:00
20 changed files with 1624 additions and 1289 deletions

233
LICENSE
View File

@ -1,7 +1,232 @@
Copyright (c) 2026 Zongor
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
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:
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
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.
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>.

View File

@ -71,7 +71,7 @@ cd undar-lang && ./build
* License
[[./LICENSE][MIT]]
[[./LICENSE][GPLv3]]
* 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, 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://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://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,76 +1,26 @@
#include "../../../vm/vm.h"
#include "../../../tools/compiler/compiler.h"
#include <SDL2/SDL.h>
#include <stdio.h>
#include <string.h>
#define MEMORY_SIZE 65536
#define CODE_SIZE 8192
#define STACK_SIZE 1024
#define MEMORY_SIZE 65536
u8 lmem[MEMORY_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;
}
u32 lcode[CODE_SIZE] = {0};
bool init_vm() {
mem = lmem;
memset(mem, 0, MEMORY_SIZE*sizeof(u8));
code = lcode;
stack = lstack;
frames = lframes;
reset();
mp = 0;
cp = 0;
pc = 0;
interrupt = 0;
return true;
}
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
u32 syscall(u32 id, u32 args, u32 mem_ptr) {
return 0; // success
}
i32 main() {

View File

@ -1,47 +1,25 @@
#include "../../../vm/vm.h"
#include "../../../tools/compiler/compiler.h"
#include <stdio.h>
#define MEMORY_SIZE 65536
#define CODE_SIZE 8192
#define STACK_SIZE 1024
#define MEMORY_SIZE 65536
u8 lmem[MEMORY_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;
}
u32 lcode[CODE_SIZE] = {0};
bool init_vm() {
mem = lmem;
code = lcode;
stack = lstack;
frames = lframes;
reset();
lc = 0;
mp = 0;
cp = 0;
pc = 0;
interrupt = 0;
status = 0;
return true;
}
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;
u32 syscall(u32 id, u32 device, u32 mem_ptr) {
USED(device);
switch(id) {
case SYSCALL_CONSOLE_WRITE: {
u32 size = *(u32*)&mem[mem_ptr];
@ -52,6 +30,7 @@ u32 syscall(u32 id, u32 mem_ptr) {
return 0;
}
case SYSCALL_CONSOLE_READ: {
u32 size;
u8 *ptr = &mem[mp];
mcpy(ptr, &size, sizeof(u32));
ptr += 4;
@ -71,86 +50,80 @@ u32 syscall(u32 id, u32 mem_ptr) {
return 1; // generic error
}
//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]);
// }
//}
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_PARG, 0, 0);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 1, 1);
code[cp++] = ENCODE_B(OP_PARG, 1, 0);
i32 add = cp + 5;
code[cp++] = ENCODE_B(OP_LOAD_IMM, 2, add);
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;
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);
while(step_vm()) {}
/* 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_PARG, 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_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_JLTS, 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_PARG, 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_PARG, 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, 0, 0);
code[cp++] = ENCODE_B(OP_LOAD_IMM, 0, new_line);
code[cp++] = ENCODE_A(OP_SYSCALL, SYSCALL_CONSOLE_WRITE, 0, 0);
code[cp++] = ENCODE_A(OP_HALT, 0, 0, 0);
}
i32 main() {
init_vm();
fib();
//repl();
test_fibonacci();
while(step_vm()) {
// do stuff
}
return 0;
}

12
build
View File

@ -69,7 +69,7 @@ case $MODE in
BUILD_FLAGS="-g -Wall -Wextra -Werror -pedantic"
;;
"release")
BUILD_FLAGS="-O2 -Wall -Wextra -Werror -pedantic"
BUILD_FLAGS="-Ofast -Wall -Wextra -Werror -pedantic"
;;
esac
@ -102,18 +102,10 @@ 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_DIR/parser.o $BUILD_DIR/compiler.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_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"

View File

@ -1,8 +1,6 @@
/**
* Constants
* Plexes
*/
const str nl = "\n";
plex Terminal {
nat handle;
}
@ -11,7 +9,7 @@ plex Terminal {
* Main function
*/
function main() {
pln(add(1, 1).str);
pln(add(1, 1) as str);
}
/**
@ -25,7 +23,7 @@ function add(int a, int b) int {
* Print with a newline
*/
function pln(str message) {
Terminal term = open("term::/0", 0);
write(term, message, message.length);
write(term, nl, nl.length);
Terminal term = open("term:///0", 0);
term.write(message);
term.write("\n");
}

View File

@ -1,8 +1,6 @@
/**
* Constants
* Plexes
*/
const str nl = "\n";
plex Terminal {
nat handle;
}
@ -11,7 +9,7 @@ plex Terminal {
* Main function
*/
function main() {
pln(fib(35).str);
pln(fib(35) as str);
}
/**
@ -26,7 +24,7 @@ function fib(int n) int {
* Print with a newline
*/
function pln(str message) {
Terminal term = open("term::/0", 0);
write(term, message, message.length);
write(term, nl, nl.length);
Terminal term = open("term:///0", 0);
term.write(message);
term.write("\n");
}

View File

@ -16,8 +16,7 @@ function main() {
* 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);
Terminal term = open("term:///0", 0);
term.write(message);
term.write("\n");
}

View File

@ -1,26 +1,26 @@
/**
* Constants
* Plexes
*/
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));
Terminal term = open("term:///0", 0);
pln("Enter a string: ");
pln(term.read(32) as str);
return 0;
}
/**
* Print with a newline
*/
function pln(Terminal term, str message) {
write(term, message, message.length);
write(term, nl, nl.length);
function pln(str message) {
Terminal term = open("term:///0", 0);
term.write(message);
term.write("\n");
}

View File

@ -20,7 +20,7 @@ plex Screen implements Device {
byte[] buffer;
draw() {
write(this, this.buffer, this.buffer.length);
this.write(this.buffer);
}
}
@ -38,15 +38,14 @@ plex Mouse implements Device {
* Main function
*/
function main() {
Screen screen = open("screen::/0", 0);
Mouse mouse = open("mouse::/0", 0);
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;

View File

@ -19,7 +19,7 @@ function main() {
* Print with a newline
*/
function pln(str message) {
Terminal term = open("term::/0", 0);
Terminal term = open("term:///0", 0);
write(term, message, message.length);
write(term, nl, nl.length);
}

View File

@ -1,9 +1,9 @@
/**
* Constants
*/
const str screen_namespace = "screen::/0"
const str mouse_namespace = "mouse::/0"
const str terminal_namespace = "term::/0"
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

751
tools/compiler.c Normal file
View File

@ -0,0 +1,751 @@
#include "compiler.h"
#include "parser.h"
#include <stdio.h>
#include <stdlib.h>
#define DEBUG_COMPILER
void emit_byte(u8 byte) {
#ifdef DEBUG_COMPILER
printf("code[%d] = %d\n", cp, byte);
#endif
code[cp] = byte;
}
void emit_u32(u32 value) {
#ifdef DEBUG_COMPILER
printf("code[%d..%d] = %d\n", cp, cp + 3, value);
#endif
u32 *c = (u32 *)(&code[cp / 4]);
c[0] = value;
}
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);
}
u8 current_index = table->scopes[table->scope_ref].count;
if (current_index + 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);
}
/* set ref to current count for local */
s.ref = current_index;
#ifdef DEBUG_COMPILER
if (s.scope == VAR) {
printf("$%d = %s\n", s.ref, s.name);
} else if (s.scope == GLOBAL) {
printf("memory[%d] = %s\n", s.ref, s.name);
} else {
printf("code[%d] = %s\n", s.ref, s.name);
}
#endif
table->scopes[table->scope_ref].symbols[current_index] = s;
table->scopes[table->scope_ref].count++;
return current_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);
}
Token next_id_or_reg() {
Token token = next_token();
if (token.type == TOKEN_IDENTIFIER) {
return token;
}
if (token.type == TOKEN_BIG_MONEY) {
token = next_token();
return token;
}
printf("Not an ID or register at line %d: %.*s\n", token.line, token.length,
token.start);
exit(1);
return token;
}
Token next_id_or_ptr() {
Token token = next_token();
if (token.type != TOKEN_IDENTIFIER && token.type != TOKEN_LITERAL_NAT &&
token.type != TOKEN_LITERAL_INT && token.type != TOKEN_LITERAL_REAL) {
printf("Not an ID or register at line %d: %.*s\n", token.line, token.length,
token.start);
exit(1);
}
return token;
}
Token next_token_is(TokenType type) {
Token token = next_token();
if (token.type != type) {
printf("ERROR at line %d: %.*s\n", token.line, token.length, token.start);
exit(1);
}
return token;
}
/**
* Global .
*/
bool define_global(ScopeTable *st, Token regType) {
u32 *globals = (u32 *)(mem);
Symbol s;
switch (regType.type) {
case TOKEN_TYPE_BOOL:
s.type = BOOL;
s.size = 1;
break;
case TOKEN_TYPE_I8:
s.type = I8;
s.size = 1;
break;
case TOKEN_TYPE_U8:
s.type = U8;
s.size = 1;
break;
case TOKEN_TYPE_I16:
s.type = I16;
s.size = 2;
break;
case TOKEN_TYPE_U16:
s.type = U16;
s.size = 2;
break;
case TOKEN_TYPE_INT:
s.type = I32;
s.size = 4;
break;
case TOKEN_TYPE_NAT:
s.type = U32;
s.size = 4;
break;
case TOKEN_TYPE_REAL:
s.type = F32;
s.size = 4;
break;
case TOKEN_TYPE_STR:
s.type = STR;
break;
default:
return false;
}
Token name = next_token_is(TOKEN_IDENTIFIER);
if (name.length > MAX_SYMBOL_NAME_LENGTH) {
return false;
}
mcpy(s.name, (char *)name.start, name.length);
s.name_length = name.length;
s.name[name.length] = '\0';
u32 addr = mp;
s.ref = addr;
s.scope = GLOBAL;
next_token_is(TOKEN_EQ);
Token value = next_token();
switch (value.type) {
case TOKEN_KEYWORD_TRUE: {
u32 addr = mp;
WRITE_U8(addr, 1);
mp += s.size;
break;
}
case TOKEN_KEYWORD_FALSE: {
u32 addr = mp;
WRITE_U8(addr, 0);
mp += s.size;
break;
}
case TOKEN_LITERAL_INT: {
i32 out = atoi(value.start);
u32 addr = mp;
WRITE_U32(addr, out);
mp += s.size;
break;
}
case TOKEN_LITERAL_NAT: {
char *endptr;
u32 out = (u32)strtoul(value.start, &endptr, 10);
if (endptr == value.start || *endptr != '\0') {
fprintf(stderr, "Invalid decimal literal: %s\n", value.start);
exit(1);
}
u32 addr = mp;
WRITE_U32(addr, out);
mp += s.size;
break;
}
case TOKEN_LITERAL_REAL: {
i32 out = FLOAT_TO_REAL(atof(value.start));
u32 addr = mp;
WRITE_U32(addr, out);
mp += s.size;
break;
}
case TOKEN_LITERAL_STR: {
const char *src = value.start;
i32 len = 0;
i32 i = 0;
while (i < value.length) {
char c = src[i++];
if (c == '"') {
continue;
}
if (c == '\\' && i < value.length) {
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) */
s.size = size;
mp += size;
WRITE_U32(addr, len);
WRITE_U8(addr + 4 + len, '\0');
break;
}
default:
return false;
}
next_token_is(TOKEN_SEMICOLON);
symbol_table_add(st, s);
return true;
}
/**
* Var .
*/
void define_var(ScopeTable *st, Token regType) {
Symbol s;
s.scope = VAR;
switch (regType.type) {
case TOKEN_TYPE_I8: {
s.type = I8;
s.size = 1;
break;
}
case TOKEN_TYPE_I16: {
s.type = I16;
s.size = 2;
break;
}
case TOKEN_TYPE_INT: {
s.type = I32;
s.size = 4;
break;
}
case TOKEN_TYPE_U8: {
s.type = U8;
s.size = 1;
break;
}
case TOKEN_TYPE_U16: {
s.type = U16;
s.size = 2;
break;
}
case TOKEN_TYPE_NAT: {
s.type = U32;
s.size = 4;
break;
}
case TOKEN_TYPE_REAL: {
s.type = F32;
s.size = 4;
break;
}
case TOKEN_TYPE_BOOL: {
s.type = BOOL;
s.size = 1;
break;
}
case TOKEN_TYPE_STR: {
s.type = STR;
s.size = 4; /* not really this type, pointer alias which is 4 */
break;
}
default:
printf("ERROR at line %d: %.*s\n", regType.line, regType.length,
regType.start);
exit(1);
}
Token name = next_token_is(TOKEN_IDENTIFIER);
if (name.length > MAX_SYMBOL_NAME_LENGTH) {
printf("VARIABLE NAME TOO LONG at line %d: %.*s\n", regType.line,
regType.length, regType.start);
exit(1);
}
mcpy(s.name, (void *)name.start, name.length);
s.name[name.length] = '\0';
s.name_length = name.length;
symbol_table_add(st, s);
}
/**
* Function.
*/
void define_function(ScopeTable *st) {
Symbol s;
s.scope = LOCAL;
s.type = FUNCTION;
Token name = next_token_is(TOKEN_IDENTIFIER);
if (name.length > MAX_SYMBOL_NAME_LENGTH) {
printf("FUNCITON NAME TOO LONG at line %d: %.*s\n", name.line, name.length,
name.start);
exit(1);
}
mcpy(s.name, (void *)name.start, name.length);
s.name[name.length] = '\0';
s.name_length = name.length;
next_token_is(TOKEN_LPAREN);
i32 temp = st->scope_ref;
st->count++;
st->scopes[st->count].parent = st->scope_ref;
st->scope_ref = (i32)st->count;
Token next = next_token();
while (next.type != TOKEN_RPAREN) {
define_var(st, next);
next = next_token();
if (next.type == TOKEN_COMMA) {
next = next_token();
continue;
} else if (next.type == TOKEN_RPAREN) {
break;
} else {
printf("ERROR at line %d: %.*s\n", next.line, next.length, next.start);
exit(1);
}
}
s.ref = cp;
next = next_token_is(TOKEN_LBRACE);
st->scope_ref = temp; // need to add to the parents scope
symbol_table_add(st, s);
st->scope_ref = (i32)st->count;
}
/**
* Plex.
*/
void define_plex(ScopeTable *st) {
Symbol s;
s.scope = GLOBAL;
s.type = PLEX;
Token name = next_token_is(TOKEN_IDENTIFIER);
if (name.length > MAX_SYMBOL_NAME_LENGTH) {
printf("PLEX NAME TOO LONG at line %d: %.*s\n", name.line, name.length,
name.start);
exit(1);
}
mcpy(s.name, (void *)name.start, name.length);
s.name[name.length] = '\0';
s.name_length = name.length;
next_token_is(TOKEN_LPAREN);
}
/**
* Branch.
*/
void define_branch(ScopeTable *st) {
Symbol s;
s.scope = LOCAL;
s.type = VOID;
Token name = next_token_is(TOKEN_IDENTIFIER);
if (name.length > MAX_SYMBOL_NAME_LENGTH) {
printf("BRANCH NAME TOO LONG at line %d: %.*s\n", name.line, name.length,
name.start);
exit(1);
}
mcpy(s.name, (void *)name.start, name.length);
s.name_length = name.length;
s.name[name.length] = '\0';
s.ref = cp;
symbol_table_add(st, s);
}
/**
* Define a loop
*/
void define_loop(ScopeTable *st) {
}
/**
* Parses an expression using the shunting yard algorithem.
* This will be useful because it will make it trivial to track types.
* If the type is a literal, we just read it, if it is a variable we read the variable type from the info.
*
* During the first pass we count the number of variables. We assign a local to each variable.
*
* When parsing a expression, we assign any function call or literal to a temp variable slot,
* (2 maybe?) First one goes in 0, then 2nd in 1, then do operation. Store the operation in 0.
* If it is a function call, use 1 to load and push the args, then use 1 for the return variable.
* Then do the operation on 1 and 0 and store in 0.
*/
Symbol value_stack[MAX_SYMBOLS];
u8 vsp;
Symbol operator_stack[MAX_SYMBOLS];
u8 osp;
void parse_expression(ScopeTable *st) {
}
/**
* Build the symbol table and calculate the types/size/offsets of all values.
*/
void build_symbol_table(char *source, ScopeTable *st) {
Token token;
init_lexer(source);
do {
token = next_token();
if (token.type == TOKEN_ERROR) {
printf("ERROR at line %d: %.*s\n", token.line, token.length, token.start);
exit(1);
}
if (token.type != TOKEN_EOF) {
if (token.type == TOKEN_LBRACE) {
st->count++;
st->scopes[st->count].parent = st->scope_ref;
st->scope_ref = (i32)st->count;
st->depth++;
continue;
}
if (token.type == TOKEN_RBRACE) {
i32 current_scope = st->scope_ref;
i32 parent = st->scopes[current_scope].parent;
if (parent < 0)
parent = 0;
st->scope_ref = parent;
st->depth--;
continue;
}
if (token.type == TOKEN_KEYWORD_PLEX) {
if (st->depth != 0) {
printf("I'm letting it slide, but generally plexes are declared "
"outside of a scope %d: %.*s\n",
token.line, token.length, token.start);
}
define_plex(st);
continue;
}
if (token.type == TOKEN_KEYWORD_FN) {
if (st->depth != 0) {
printf("Functions can only be declared outside of a scope %d: %.*s\n",
token.line, token.length, token.start);
exit(1);
}
define_function(st);
continue;
}
if (token.type == TOKEN_KEYWORD_CONST) {
// FIXME: add consts, for now just make everything
next_token();
continue;
}
if (token.type == TOKEN_TYPE_I8 || token.type == TOKEN_TYPE_I16 ||
token.type == TOKEN_TYPE_INT || token.type == TOKEN_TYPE_U8 ||
token.type == TOKEN_TYPE_U16 || token.type == TOKEN_TYPE_NAT ||
token.type == TOKEN_TYPE_REAL || token.type == TOKEN_TYPE_STR ||
token.type == TOKEN_TYPE_BOOL) {
if (st->depth == 0) {
define_global(st, token);
continue;
}
define_var(st, token);
next_token_is(TOKEN_SEMICOLON);
continue;
}
if (token.type == TOKEN_KEYWORD_IF) {
define_loop(st);
continue;
}
if (token.type == TOKEN_KEYWORD_LOOP || token.type == TOKEN_KEYWORD_DO ||
token.type == TOKEN_KEYWORD_FOR) {
define_branch(st);
continue;
}
if (token.type == TOKEN_KEYWORD_RETURN) {
Token next = next_token();
if (next.type == TOKEN_SEMICOLON) {
/* put 0xFF as return register */
cp++;
continue;
}
get_reg(next, st);
cp++;
next_token_is(TOKEN_SEMICOLON);
continue;
}
#ifdef DEBUG_COMPILER
printf("-- %.*s --\n", token.length, token.start);
#endif
}
} while (token.type != TOKEN_EOF);
}
/**
* 2nd pass, emit the bytecode
*/
void emit_bytecode(char *source, ScopeTable *st) {
Token token;
init_lexer(source);
do {
token = next_token();
if (token.type == TOKEN_ERROR) {
printf("ERROR at line %d: %.*s\n", token.line, token.length, token.start);
break;
}
if (token.type != TOKEN_EOF) {
if (token.type == TOKEN_LBRACE) {
st->count++;
st->scopes[st->count].parent = st->scope_ref;
st->scope_ref = (i32)st->count;
st->depth++;
continue;
}
if (token.type == TOKEN_RBRACE) {
i32 current_scope = st->scope_ref;
i32 parent = st->scopes[current_scope].parent;
if (parent < 0)
parent = 0;
st->scope_ref = parent;
st->depth--;
continue;
}
if (token.type == TOKEN_KEYWORD_FN) {
/* ignore, already processed */
Token next = next_token();
while (next.type != TOKEN_RPAREN) {
next = next_token();
}
continue;
}
if (token.type == TOKEN_KEYWORD_PLEX) {
/* ignore, already processed */
Token next = next_token();
while (next.type != TOKEN_RPAREN) {
next = next_token();
}
continue;
}
if (token.type == TOKEN_KEYWORD_CONST) {
/* ignore, already processed */
next_token(); /* type */
next_token(); /* var */
next_token(); /* reg */
next_token(); /* ; */
continue;
}
if (token.type == TOKEN_TYPE_I8 || token.type == TOKEN_TYPE_I16 ||
token.type == TOKEN_TYPE_INT || token.type == TOKEN_TYPE_U8 ||
token.type == TOKEN_TYPE_U16 || token.type == TOKEN_TYPE_NAT ||
token.type == TOKEN_TYPE_REAL || token.type == TOKEN_TYPE_STR) {
/* ignore, already processed */
next_token(); /* var */
next_token(); /* reg */
next_token(); /* ; */
continue;
}
if (token.type == TOKEN_KEYWORD_LOOP || token.type == TOKEN_KEYWORD_IF ||
token.type == TOKEN_KEYWORD_ELSE || token.type == TOKEN_KEYWORD_DO ||
token.type == TOKEN_KEYWORD_FOR) {
/* ignore, already processed */
next_token(); /* id */
}
if (token.type == TOKEN_KEYWORD_RETURN) {
Token next = next_token();
if (next.type == TOKEN_SEMICOLON) {
/* put 0xFF as return register */
code[cp++] = ENCODE_B(OP_RETURN, 255, 0);
continue;
}
u32 reg = get_reg(next, st);
code[cp++] = ENCODE_B(OP_RETURN, reg, 0);
next_token_is(TOKEN_SEMICOLON);
continue;
}
#ifdef DEBUG_COMPILER
printf("-- %.*s --\n", token.length, token.start);
#endif
if (token.type == TOKEN_IDENTIFIER) {
/*} else {
some other identifier
printf("Unknown id at line %d: %.*s\n", token.line, token.length,
token.start);
exit(1);
}
*/
}
}
} while (token.type != TOKEN_EOF);
}
/**
* Compile.
*/
bool compile(ScopeTable *st, char *source) {
build_symbol_table(source, st);
cp = 0; /* actually start emitting code */
st->count = 0;
emit_bytecode(source, st);
return true;
}

View File

@ -1,10 +1,10 @@
#ifndef UNDAR_COMPILER_H
#define UNDAR_COMPILER_H
#include "../../vm/libc.h"
#include "../../vm/vm.h"
#include "../vm/libc.h"
#include "../vm/vm.h"
typedef enum { GLOBAL, LOCAL } ScopeType;
typedef enum { GLOBAL, LOCAL, VAR } ScopeType;
typedef enum {
VOID,
BOOL,
@ -81,35 +81,29 @@ struct scope_tab_s {
u32 count;
u32 capacity;
i32 scope_ref;
u32 depth;
};
#define EMIT_U8(value) \
do { \
code[cp++] = (value) & 0xFF; \
} while (0)
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;
#define EMIT_U16(value) \
do { \
code[cp++] = (value) & 0xFF; \
code[cp++] = ((value) >> 8) & 0xFF; \
} while (0)
#define EMIT_U32(value) \
do { \
code[cp++] = (value) & 0xFF; \
code[cp++] = ((value) >> 8) & 0xFF; \
code[cp++] = ((value) >> 16) & 0xFF; \
code[cp++] = ((value) >> 24) & 0xFF; \
} while (0)
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

View File

@ -1,655 +0,0 @@
#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;
}

View File

@ -1,5 +1,11 @@
#include "parser.h"
typedef struct {
const char *start;
const char *current;
int line;
} Lexer;
Lexer lexer;
void initLexer(const char *source) {
@ -206,21 +212,10 @@ static TokenType identifierType() {
case 'e':
if (lexer.current - lexer.start > 2) {
switch (lexer.start[2]) {
case 'f':
return checkKeyword(3, 4, "resh", TOKEN_KEYWORD_REFRESH);
case 'a':
return checkKeyword(3, 1, "d", TOKEN_KEYWORD_READ);
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;
@ -231,7 +226,14 @@ static TokenType identifierType() {
if (lexer.current - lexer.start > 1) {
switch (lexer.start[1]) {
case 't':
return checkKeyword(2, 1, "r", TOKEN_TYPE_STR);
if (lexer.current - lexer.start > 2) {
switch (lexer.start[2]) {
case 'r':
return checkKeyword(2, 0, "", TOKEN_TYPE_STR);
case 'a':
return checkKeyword(2, 1, "t", TOKEN_KEYWORD_STAT);
}
}
}
}
break;
@ -430,8 +432,8 @@ const char *token_type_to_string(TokenType type) {
return "TOKEN_KEYWORD_READ";
case TOKEN_KEYWORD_WRITE:
return "TOKEN_KEYWORD_WRITE";
case TOKEN_KEYWORD_REFRESH:
return "TOKEN_KEYWORD_REFRESH";
case TOKEN_KEYWORD_STAT:
return "TOKEN_KEYWORD_STAT";
case TOKEN_KEYWORD_CLOSE:
return "TOKEN_KEYWORD_CLOSE";
case TOKEN_KEYWORD_NIL:

View File

@ -1,7 +1,7 @@
#ifndef UNDAR_LEXER_H
#define UNDAR_LEXER_H
#include "../../vm/libc.h"
#include "../vm/libc.h"
typedef enum {
TOKEN_EOF,
@ -37,7 +37,7 @@ typedef enum {
TOKEN_KEYWORD_OPEN,
TOKEN_KEYWORD_READ,
TOKEN_KEYWORD_WRITE,
TOKEN_KEYWORD_REFRESH,
TOKEN_KEYWORD_STAT,
TOKEN_KEYWORD_CLOSE,
TOKEN_KEYWORD_LOOP,
TOKEN_KEYWORD_DO,
@ -77,30 +77,14 @@ typedef enum {
TOKEN_ERROR
} TokenType;
typedef struct token_s Token;
typedef struct parser_s Parser;
typedef struct lexer_s Lexer;
struct token_s{
typedef struct {
TokenType type;
const char *start;
int length;
int line;
};
} Token;
struct lexer_s {
const char *start;
const char *current;
int line;
};
struct parser_s {
Token current;
Token previous;
};
void initLexer(const char *source);
void init_lexer(const char *source);
Token next_token();
const char* token_type_to_string(TokenType type);

View File

@ -18,14 +18,6 @@ typedef float f32;
#define nil NULL
#define USED(x) ((void)(x))
#define AS_INT(v) ((i32)(v))
#define AS_NAT(v) ((u32)(v))
#define AS_REAL(v) ((i32)(v))
#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
@ -38,6 +30,16 @@ typedef float f32;
#define I32_MAX 2147483647
#define U32_MAX 4294967295
#define FIXED_CONST 65536.0f
#define AS_INT(v) ((i32)(v))
#define AS_NAT(v) ((u32)(v))
#define AS_REAL(v) ((i32)(v))
#define FLOAT_TO_REAL(v) (((i32)(v)) * FIXED_CONST)
#define REAL_TO_FLOAT(v) (((f32)(v)) / FIXED_CONST)
#define USED(x) ((void)(x))
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);

536
vm/vm.c
View File

@ -1,17 +1,15 @@
#include "vm.h"
#define FRAME_HEADER_SIZE 12
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 */
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 */
#define MAX_LEN_INT32 11
const char radix_set[11] = "0123456789";
@ -28,279 +26,301 @@ u32 str_alloc(char *str, u32 length) {
}
bool step_vm() {
u16 opcode = code[pc++];
u32 instruction = code[pc++];
u8 opcode = DECODE_OP(instruction);
u32 *locals = (u32*)(&mem[fp]);
u32 *globals = (u32*)(mem);
switch (opcode) {
case OP_HALT: {
/* no need to decode, all are zeros */
return false;
}
case OP_CALL: {
u32 fn_ptr = stack[--sp];
frames[fp].return_pc = pc;
frames[fp++].start_mp = mp;
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 */
pc = fn_ptr;
return true;
}
case OP_RETURN: {
u32 return_pc = frames[--fp].return_pc;
u32 return_mp = frames[fp].start_mp;
mp = return_mp;
pc = return_pc;
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 (parent_local_return_address != 255) {
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 */
globals[(parent_local_return_address / 4)] = return_value;
}
}
/* jump to parent frame */
pc = return_address;
return true;
}
case OP_SYSCALL: {
u32 id = stack[--sp]; /* syscall id */
u32 rd = stack[--sp]; /* the pointer */
status = syscall(id, rd);
DECODE_A(instruction)
u32 rd = locals[src2]; /* the pointer */
status = syscall(dest, src1, rd);
return true;
}
case OP_PUSH_8: {
u8 value = code[pc++];
stack[sp++] = value;
case OP_PARG: {
DECODE_B(instruction)
USED(imm);
globals[(mp / 4) + lc + 3] = locals[dest];
lc++;
return true;
}
case OP_PUSH_16: {
u16 *values = (u16*)(code);
u16 value = values[pc/2];
pc+=2;
stack[sp++] = value;
case OP_LOAD_IMM: {
DECODE_B(instruction)
locals[dest] = ((u32)(imm));
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;
case OP_LOAD_UPPER_IMM: {
DECODE_B(instruction)
u32 value = locals[dest];
locals[dest] = (value | (((u32)(imm)) << 16));
return true;
}
case OP_PUSH_MP: {
stack[sp++] = mp;
case OP_LOAD_IND_8: {
DECODE_A(instruction)
USED(src2);
locals[dest] = READ_U8(locals[src1]);
return true;
}
case OP_PUSH_START_MP: {
stack[sp++] = frames[fp - 1].start_mp;
case OP_LOAD_IND_16: {
DECODE_A(instruction)
USED(src2);
locals[dest] = READ_U16(locals[src1]);
return true;
}
case OP_POP: {
--sp;
case OP_LOAD_IND_32: {
DECODE_A(instruction)
USED(src2);
locals[dest] = READ_U32(locals[src1]);
return true;
}
case OP_SET:{
Frame *f = &frames[fp - 1];
u32 *locals = f->locals;
u8 ptr = (u8)stack[--sp];
u32 value = stack[--sp];
locals[ptr] = value;
case OP_LOAD_OFF_8: {
DECODE_A(instruction)
locals[dest] = READ_U8((locals[src1] + locals[src2]));
return true;
}
case OP_SET_IMM:{
Frame *f = &frames[fp - 1];
u32 *locals = f->locals;
u8 ptr = code[pc++];
u32 value = stack[--sp];
locals[ptr] = value;
case OP_LOAD_OFF_16: {
DECODE_A(instruction)
locals[dest] = READ_U16((locals[src1] + locals[src2]));
return true;
}
case OP_GET:{
Frame *f = &frames[fp - 1];
u32 *locals = f->locals;
u8 ptr = (u8)stack[--sp];
stack[sp++] = locals[ptr];
case OP_LOAD_OFF_32: {
DECODE_A(instruction)
locals[dest] = READ_U32((locals[src1] + locals[src2]));
return true;
}
case OP_GET_IMM:{
Frame *f = &frames[fp - 1];
u32 *locals = f->locals;
u8 ptr = code[pc++];
stack[sp++] = locals[ptr];
case OP_STORE_IND_8: {
DECODE_A(instruction)
USED(src2);
WRITE_U8(locals[dest], locals[src1]);
return true;
}
case OP_LOAD_8: {
u32 ptr = stack[--sp];
u32 value = mem[ptr];
stack[sp++] = value;
case OP_STORE_IND_16: {
DECODE_A(instruction)
USED(src2);
WRITE_U16(locals[dest], locals[src1]);
return true;
}
case OP_LOAD_16: {
u32 ptr = stack[--sp];
u16 *values = (u16*)(&mem[ptr]);
u32 value = values[0];
stack[sp++] = value;
case OP_STORE_IND_32: {
DECODE_A(instruction)
USED(src2);
WRITE_U32(locals[dest], locals[src1]);
return true;
}
case OP_LOAD_32: {
u32 ptr = stack[--sp];
u32 *values = (u32*)(&mem[ptr]);
u32 value = values[0];
stack[sp++] = value;
case OP_STORE_OFF_8: {
DECODE_A(instruction)
WRITE_U8((locals[dest] + locals[src2]), locals[src1]);
return true;
}
case OP_STORE_8: {
u32 ptr = stack[--sp];
u8 value = (u8)stack[--sp];
mem[ptr] = value;
case OP_STORE_OFF_16: {
DECODE_A(instruction)
WRITE_U16((locals[dest] + locals[src2]), locals[src1]);
return true;
}
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_32: {
u32 ptr = stack[--sp];
u32 value = stack[--sp];
u32 *values = (u32*)(&mem[ptr]);
values[0] = value;
case OP_STORE_OFF_32: {
DECODE_A(instruction)
WRITE_U32((locals[dest] + locals[src2]), locals[src1]);
return true;
}
case OP_MEM_ALLOC: {
u32 size = stack[--sp];
stack[sp++] = mp;
DECODE_A(instruction)
u32 size = locals[src1];
locals[dest] = mp;
WRITE_U32(mp, size);
USED(src2);
mp += (size + 4);
return true;
}
case OP_MEM_CPY_8: {
DECODE_A(instruction)
u8 *ptr_src;
u8 *ptr_dest;
u32 count = stack[--sp];
u32 src = stack[--sp];
u32 dest = stack[--sp];
u32 mdest = locals[dest];
u32 msrc = locals[src1];
u32 count = locals[src2];
if (dest + count >= mp) {
if (mdest + count >= mp) {
status = 1;
return true;
}
ptr_dest = &mem[dest];
ptr_src = &mem[src];
if (ptr_dest == ptr_src) { return true; }
ptr_dest = &mem[mdest];
ptr_src = &mem[msrc];
mcpy(ptr_dest, ptr_src, count*sizeof(u8));
status = 0;
return true;
}
case OP_MEM_CPY_16: {
DECODE_A(instruction)
u8 *ptr_src;
u8 *ptr_dest;
u32 count = stack[--sp];
u32 src = stack[--sp];
u32 dest = stack[--sp];
u32 mdest = locals[dest];
u32 msrc = locals[src1];
u32 count = locals[src2];
if (dest + count >= mp) {
if (mdest + count >= mp) {
status = 1;
return true;
}
ptr_dest = &mem[dest];
ptr_src = &mem[src];
if (ptr_dest == ptr_src) { return true; }
ptr_dest = &mem[mdest];
ptr_src = &mem[msrc];
mcpy(ptr_dest, ptr_src, count*sizeof(u16));
status = 0;
return true;
}
case OP_MEM_CPY_32: {
DECODE_A(instruction)
u8 *ptr_src;
u8 *ptr_dest;
u32 count = stack[--sp];
u32 src = stack[--sp];
u32 dest = stack[--sp];
u32 mdest = locals[dest];
u32 msrc = locals[src1];
u32 count = locals[src2];
if (dest + count >= mp) {
if (mdest + count >= mp) {
status = 1;
return true;
}
ptr_dest = &mem[dest];
ptr_src = &mem[src];
if (ptr_dest == ptr_src) { return true; }
ptr_dest = &mem[mdest];
ptr_src = &mem[msrc];
mcpy(ptr_dest, ptr_src, count*sizeof(u32));
status = 0;
return true;
}
case OP_MEM_SET_8: {
u8 *ptr_dest;
u8 value = (u8)stack[--sp];
u32 count = stack[--sp];
u32 dest = stack[--sp];
DECODE_A(instruction)
if (dest + count >= mp) {
u8 *ptr_dest;
u8 value = (u8)locals[src1];
u32 count = locals[src2];
u32 mdest = locals[dest];
if (mdest + count >= mp) {
status = 1;
return true;
}
ptr_dest = &mem[dest];
ptr_dest = &mem[mdest];
mcpy(ptr_dest, &value, count*sizeof(u8));
status = 0;
return true;
}
case OP_MEM_SET_16: {
u8 *ptr_dest;
u16 value = (u16)stack[--sp];
u32 count = stack[--sp];
u32 dest = stack[--sp];
DECODE_A(instruction)
if (dest + count >= mp) {
u8 *ptr_dest;
u16 value = (u16)locals[src1];
u32 count = locals[src2];
u32 mdest = locals[dest];
if (mdest + count >= mp) {
status = 1;
return true;
}
ptr_dest = &mem[dest];
ptr_dest = &mem[mdest];
mcpy(ptr_dest, &value, count*sizeof(u16));
status = 0;
return true;
}
case OP_MEM_SET_32: {
u8 *ptr_dest;
u32 value = stack[--sp];
u32 count = stack[--sp];
u32 dest = stack[--sp];
DECODE_A(instruction)
if (dest + count >= mp) {
u8 *ptr_dest;
u32 value = locals[src1];
u32 count = locals[src2];
u32 mdest = locals[dest];
if (mdest + count >= mp) {
status = 1;
return true;
}
ptr_dest = &mem[dest];
ptr_dest = &mem[mdest];
mcpy(ptr_dest, &value, count*sizeof(u32));
status = 0;
return true;
}
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;
case OP_MOV: {
DECODE_A(instruction)
USED(src2);
locals[dest] = locals[src1];
return true;
}
case OP_ADD_INT: {
@ -334,27 +354,27 @@ bool step_vm() {
MATH_OP(i32, -);
}
case OP_MUL_REAL: {
i32 src1 = (i32)stack[--sp];
i32 src2 = (i32)stack[--sp];
DECODE_A(instruction)
i32 src1_whole = src1 >> 16;
i32 src2_whole = src2 >> 16;
i32 src1_whole = (i32)locals[src1] >> 16;
i32 src2_whole = (i32)locals[src2] >> 16;
i32 src1_decimal = src1 & 16;
i32 src2_decimal = src2 & 16;
i32 src1_decimal = (i32)locals[src1] & 16;
i32 src2_decimal = (i32)locals[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;
stack[sp++] = result;
locals[dest] = result;
return true;
}
case OP_DIV_REAL: {
DECODE_A(instruction)
i32 result;
i32 src1_val = (i32)stack[--sp];
i32 src2_val = (i32)stack[--sp];
i32 src1_val = (i32)locals[src1];
i32 src2_val = (i32)locals[src2];
u32 src2_reciprocal = 1;
src2_reciprocal <<= 31;
@ -363,66 +383,141 @@ bool step_vm() {
result = src1_val * src2_reciprocal;
result <<= 1;
stack[sp++] = result;
locals[dest] = result;
return true;
}
case OP_INT_TO_REAL: {
i32 result = (i32)stack[--sp] << 16;
stack[sp++] = result;
DECODE_A(instruction)
i32 result = (i32)locals[src1] << 16;
USED(src2);
locals[dest] = result;
return true;
}
case OP_INT_TO_NAT: {
u32 result = (u32)stack[--sp];
stack[sp++] = result;
DECODE_A(instruction)
u32 result = (u32)locals[src1];
USED(src2);
locals[dest] = result;
return true;
}
case OP_NAT_TO_REAL: {
i32 result = (i32)stack[--sp] << 16;
stack[sp++] = result;
DECODE_A(instruction)
i32 result = (i32)locals[src1] << 16;
USED(src2);
locals[dest] = result;
return true;
}
case OP_NAT_TO_INT: {
i32 result = (i32)stack[--sp];
stack[sp++] = result;
DECODE_A(instruction)
i32 result = (i32)locals[src1];
USED(src2);
locals[dest] = result;
return true;
}
case OP_REAL_TO_INT: {
i32 result = (i32)stack[--sp] >> 16;
stack[sp++] = result;
DECODE_A(instruction)
i32 result = (i32)locals[src1] >> 16;
USED(src2);
locals[dest] = result;
return true;
}
case OP_REAL_TO_NAT: {
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;
DECODE_A(instruction)
u32 result = (u32)locals[src1] >> 16;
USED(src2);
locals[dest] = result;
return true;
}
case OP_BIT_SHIFT_LEFT: {
MATH_OP(u32, <<);
MATH_OP_NO_CAST(<<);
}
case OP_BIT_SHIFT_RIGHT: {
MATH_OP(u32, >>);
MATH_OP_NO_CAST(>>);
}
case OP_BIT_SHIFT_R_EXT: {
MATH_OP(i32, >>);
}
case OP_BIT_AND: {
MATH_OP(u32, &);
MATH_OP_NO_CAST(&);
}
case OP_BIT_OR: {
MATH_OP(u32, |);
MATH_OP_NO_CAST(|);
}
case OP_BIT_XOR: {
MATH_OP(u32, ^);
MATH_OP_NO_CAST(^);
}
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_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;
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);
mask = -(u32)(status == 0);
pc = (jmp_dest & mask) | (pc & ~mask);
return true;
}
case OP_JEQS: {
COMPARE_AND_JUMP(i32, ==);
}
case OP_JNES: {
COMPARE_AND_JUMP(i32, !=);
}
case OP_JGTS: {
COMPARE_AND_JUMP(i32, >);
}
case OP_JLTS: {
COMPARE_AND_JUMP(i32, <);
}
case OP_JLES: {
COMPARE_AND_JUMP(i32, <=);
}
case OP_JGES: {
COMPARE_AND_JUMP(i32, >=);
}
case OP_JEQU: {
COMPARE_AND_JUMP(u32, ==);
}
case OP_JNEU: {
COMPARE_AND_JUMP(u32, !=);
}
case OP_JGTU: {
COMPARE_AND_JUMP(u32, >);
}
case OP_JLTU: {
COMPARE_AND_JUMP(u32, <);
}
case OP_JLEU: {
COMPARE_AND_JUMP(u32, <=);
}
case OP_EQS: {
MATH_OP(i32, ==);
@ -460,31 +555,15 @@ bool step_vm() {
case OP_GEU: {
MATH_OP(u32, >=);
}
case OP_JMP: {
pc = stack[--sp];
return true;
}
case OP_JMP_FLAG: {
u32 mask;
u32 jmp_dest = stack[--sp];
mask = -(u32)(status == 0);
pc = (jmp_dest & mask) | (pc & ~mask);
return true;
}
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_INT_TO_STR: {
DECODE_A(instruction)
u32 i = MAX_LEN_INT32;
i32 v = (i32)stack[--sp];
i32 v = (i32)locals[src1];
char buffer[MAX_LEN_INT32];
i32 n = v;
bool neg = n < 0;
USED(src2);
if (neg)
n = -n;
@ -500,16 +579,18 @@ bool step_vm() {
buffer[--i] = '0';
/* Copy from buffer[i] to buffer + MAX_LEN_INT32 */
stack[sp++] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
locals[dest] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
return true;
return pc;
}
case OP_NAT_TO_STR: {
u32 v = (i32)stack[--sp];
DECODE_A(instruction)
u32 v = (i32)locals[src1];
char buffer[MAX_LEN_INT32];
u32 n = v;
u32 i = MAX_LEN_INT32;
USED(src2);
do {
buffer[--i] = radix_set[n % 10];
n /= 10;
@ -518,14 +599,16 @@ bool step_vm() {
if (v == 0)
buffer[--i] = '0';
/* Copy from buffer[i] to buffer + MAX_LEN_INT32 */
stack[sp++] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
locals[dest] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
return true;
return pc;
}
case OP_REAL_TO_STR: {
DECODE_A(instruction)
u32 i = 0, j = 0;
i32 q = (i32)stack[--sp];
char buffer[MAX_LEN_INT32];
i32 q = (i32)locals[src1];
char buffer[12];
u32 int_part, frac_part;
if (q < 0) {
@ -535,6 +618,7 @@ bool step_vm() {
int_part = q >> 16;
frac_part = q & 0xFFFF;
USED(src2);
if (int_part == 0) {
buffer[i++] = radix_set[0];
@ -557,9 +641,9 @@ bool step_vm() {
frac_part &= 0xFFFF;
}
stack[sp++] = str_alloc(buffer + i, MAX_LEN_INT32 - i);
locals[dest] = str_alloc(buffer + i, 12 - i);
return true;
return pc;
}
}

251
vm/vm.h
View File

@ -3,88 +3,117 @@
#include "libc.h"
/**
* Instruction Types
*
* A : [8:opcode][8:dest][8:src1][8:src2]
* B : [8:opcode][8:dest][16: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;
typedef enum {
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 */
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 device 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_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_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_PARG, /* push_arg : A : dest : push u32 value onto the childs locals */
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_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_EQS, /* eq_signed : A : locals[dest] = locals[src1] == locals[src2] */
OP_NES, /* ne_signed : A : locals[dest] = locals[src1] != locals[src2] */
OP_GTS, /* gt_signed : A : locals[dest] = locals[src1] > locals[src2] */
OP_LTS, /* lt_signed : A : locals[dest] = locals[src1] < locals[src2] */
OP_LES, /* le_signed : A : locals[dest] = locals[src1] <= locals[src2] */
OP_GES, /* ge_signed : A : locals[dest] = locals[src1] >= locals[src2] */
OP_EQU, /* eq_unsigned : A : locals[dest] = locals[src1] == locals[src2] */
OP_NEU, /* ne_unsigned : A : locals[dest] = locals[src1] != locals[src2] */
OP_GTU, /* gt_unsigned : A : locals[dest] = locals[src1] > locals[src2] */
OP_LTU, /* lt_unsigned : A : locals[dest] = locals[src1] < locals[src2] */
OP_LEU, /* le_unsigned : A : locals[dest] = locals[src1] <= locals[src2] */
OP_GEU, /* ge_unsigned : A : locals[dest] = locals[src1] >= locals[src2] */
OP_JMP_FLAG, /* jump_if_flag : A : jump to locals[dest] if flag > 0 */
OP_JMP_ABS, /* jump_absolute : A : jump to locals[dest] if locals[src1] != 0 */
OP_JMP_OFF, /* jump_offset : A : jump to locals[dest] + locals[src2] if locals[src1] != 0 */
OP_JEQS, /* jump_eq_signed : A : jump to locals[dest] if locals[src1] as i32 == locals[src2] as i32 */
OP_JNES, /* jump_neq_signed : A : jump to locals[dest] if locals[src1] as i32 != locals[src2] as i32 */
OP_JGTS, /* jump_gt_signed : A : jump to locals[dest] if locals[src1] as i32 > locals[src2] as i32 */
OP_JLTS, /* jump_lt_signed : A : jump to locals[dest] if locals[src1] as i32 < locals[src2] as i32 */
OP_JLES, /* jump_le_signed : A : jump to locals[dest] if locals[src1] as i32 <= locals[src2] as i32 */
OP_JGES, /* jump_ge_signed : A : jump to locals[dest] if locals[src1] as i32 >= locals[src2] as i32 */
OP_JEQU, /* jump_eq_unsigned : A : jump to locals[dest] if locals[src1] as u32 == locals[src2] as u32 */
OP_JNEU, /* jump_neq_unsigned : A : jump to locals[dest] if locals[src1] as u32 != locals[src2] as u32 */
OP_JGTU, /* jump_gt_unsigned : A : jump to locals[dest] if locals[src1] as u32 > locals[src2] as u32 */
OP_JLTU, /* jump_lt_unsigned : A : jump to locals[dest] if locals[src1] as u32 < locals[src2] as u32 */
OP_JLEU, /* jump_le_unsigned : A : jump to locals[dest] if locals[src1] as u32 <= locals[src2] as u32 */
OP_JGEU, /* jump_ge_unsigned : A : jump to locals[dest] if locals[src1] as u32 >= locals[src2] as u32 */
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_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_STR_TO_INT, /* str_to_int : A : locals[dest] = mem[locals[src1]..] ~> int */
OP_STR_TO_NAT, /* str_to_nat : A : locals[dest] = mem[locals[src1]..] ~> nat */
OP_STR_TO_REAL, /* str_to_real : A : locals[dest] = mem[locals[src1]..] ~> real */
OP_MAX_OPCODE /* not an opcode just a count of instructions */
} Opcode;
typedef enum {
@ -93,32 +122,22 @@ typedef enum {
SYSCALL_MAX
} Syscall;
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 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 */
#define READ_U8(addr) (mem[addr])
#define READ_U16(addr) \
(((u16)mem[(addr) + 1] << 8) | ((u16)mem[(addr)]))
#define READ_U32(addr) \
(((u32)mem[(addr) + 3] << 24) | \
#define READ_U32(addr) (((u32)mem[(addr) + 3] << 24) | \
((u32)mem[(addr) + 2] << 16) | \
((u32)mem[(addr) + 1] << 8) | ((u32)mem[(addr)]))
@ -135,22 +154,42 @@ extern u8 interrupt; /* device interrupt */
#define WRITE_U32(addr, value) \
do { \
mem[addr] = (value) & 0xFF; \
mem[addr + 1] = ((value) >> 8) & 0xFF; \
mem[addr + 2] = ((value) >> 16) & 0xFF; \
mem[addr + 3] = ((value) >> 24) & 0xFF; \
mem[(addr)] = (value) & 0xFF; \
mem[(addr) + 1] = ((value) >> 8) & 0xFF; \
mem[(addr) + 2] = ((value) >> 16) & 0xFF; \
mem[(addr) + 3] = ((value) >> 24) & 0xFF; \
} while (0)
#define MATH_OP(type, op) \
do { \
type b = (type)stack[--sp]; \
type a = (type)stack[--sp]; \
stack[sp++] = (type)(a op b); \
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; \
} while (0)
extern bool init_vm();
extern u32 syscall(u32 id, u32 mem_ptr);
extern u32 syscall(u32 id, u32 args, u32 mem_ptr);
bool step_vm();
u32 str_alloc(char *str, u32 length);