Repository: stefano/wasm-forth Branch: master Commit: a83428b2e4a9 Files: 37 Total size: 185.6 KB Directory structure: gitextract_w71cah5a/ ├── .gitignore ├── LICENSE ├── README.md ├── examples/ │ ├── script/ │ │ ├── README │ │ ├── index.html │ │ ├── index.js │ │ └── package.json │ ├── todomvc/ │ │ ├── README │ │ ├── index.f │ │ ├── index.html │ │ ├── index.js │ │ ├── package.json │ │ └── vendor/ │ │ └── index.css │ └── webpack/ │ ├── README │ ├── index.html │ ├── index.js │ ├── package.json │ └── webpack.config.js ├── kernel/ │ ├── __init__.py │ ├── __main__.py │ ├── asm_ops.py │ ├── assembler.py │ ├── binaryen_module.py │ ├── build_binaryen_ext.py │ ├── code_words.py │ ├── forth/ │ │ ├── core.f │ │ └── vdom.f │ ├── forth_interpreter.py │ ├── memory_layout.py │ └── vendor/ │ └── binaryen-c.h ├── package.json ├── repl/ │ ├── index.html │ ├── repl.css │ └── repl.js ├── setup.py ├── src/ │ └── index.js └── webpack.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ dist node_modules /wasm_forth.egg-info /_binaryen_c.abi3.so /.eggs /.vscode /build /env __pycache__ ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ WASM Forth ========== A Forth implementation compiling to WebAssembly. It includes an ANS Forth standard environment containing all the CORE words. The system has a fixed amount of memory available, currently 128 MB. Interaction with Javascript at the moment is limited to textual input (using `WasmForth.source`) and output (through the `write` configuration parameter passed to `WasmForth.boot`). Using the included (optional) virtual DOM library it's possible to write interactive web apps. See the code in `examples/todomvc/` for an example TODO list web app fully implemented in Forth. Installation ============ $ npm install wasm-forth Usage ===== The following code instantiates the interpreter and runs a program that prints "Hello, World!" to the console: import * as WasmForth from 'wasm-forth'; import wasmURL from 'wasm-forth/dist/kernel.wasm'; import coreURL from 'wasm-forth/dist/core.f'; import vdomURL from 'wasm-forth/dist/vdom.f'; WasmForth.boot({ wasmURL, sources: [coreURL, vdomURL], write: (text) => { console.log(text); } }).then(() => { WasmForth.source(': HELLO S" Hello, World!" TYPE ; HELLO\n'); }); `WasmForth.boot({ ... })` initializes the system and returns a Promise. Once resolved, it's possible to interpret forth code by passing it to `WasmForth.source(string)`. Note that the string passed must end with a newline. `WasmForth.boot` accepts a configuration object with 3 required parameters: - `wasmURL`: URL where to fetch the "kernel.wasm" included in the NPM package. - `sources`: a list of URLs where to fetch the forth "core.f" included in the NPM package. - `write`: a function that will be called when the forth code needs to output text. If you're using webpack, you can use the file-loader (https://github.com/webpack-contrib/file-loader) plugin to distribute `kernel.wasm`, `core.f` and `vdom.f`. You can also use this library without a module bundler by loading it in a ================================================ FILE: examples/script/index.js ================================================ WasmForth.boot({ wasmURL: 'node_modules/wasm-forth/dist/kernel.wasm', sources: ['node_modules/wasm-forth/dist/core.f', 'node_modules/wasm-forth/dist/vdom.f'], write: (text) => { document.getElementById('content').textContent += text; } }).then(() => { WasmForth.source(': HELLO S" Hello, World!" TYPE ; HELLO\n'); }); ================================================ FILE: examples/script/package.json ================================================ { "name": "example", "version": "1.0.0", "description": "", "main": "index.js", "author": "", "license": "GPL-3.0", "dependencies": { "wasm-forth": "^2.0.0" } } ================================================ FILE: examples/todomvc/README ================================================ To run this example: $ npm install $ python3 -m http.server 8080 then open the browser at http://localhost:8080 ================================================ FILE: examples/todomvc/index.f ================================================ 1 QUIET ! VARIABLE first-render TRUE first-render ! ( each todo has: 4 byte length [excluding flags], 1 byte completed flag, 1 byte editing flag, 1 byte show remove button 1 byte focus editing, string content ) 1 MB buffer todos 1025 buffer todo-temp 0 todo-temp ! 1025 buffer item-temp 0 item-temp ! : completed ( addr -- flag ) CELL+ C@ ; : set-completed ( flag addr -- ) CELL+ C! ; : editing ( addr -- flag ) CELL+ 1+ C@ ; : set-editing ( flag addr -- ) CELL+ 1+ C! ; : show-remove ( addr -- flag ) CELL+ 2 + C@ ; : set-show-remove ( flag addr -- ) CELL+ 2 + C! ; : focus ( addr -- flag ) CELL+ 3 + C@ ; : set-focus ( flag addr -- ) CELL+ 3 + C! ; : text-addr ( addr -- addr1 ) 2 CELLS + ; : todo-text ( addr -- addr1 u ) text-addr & @ ; : todo-text-len @ ; : bytes-to-end ( addr -- n ) todos buf-next @ SWAP - ; : eof-todo ( addr -- addr1 ) todo-text + ; : no-space-to-replace? ( u addr -- flag ) DUP eof-todo bytes-to-end + + 2 CELLS + todos buf-end > ; : set-todo-text ( c-addr u addr -- ) 2DUP no-space-to-replace? IF abort-task" no space left to set todo text" THEN 2DUP + 2 CELLS + >R DUP eof-todo DUP bytes-to-end R> 2DUP + >R SWAP MOVE ( make space ) R> todos buf-next ! 2DUP ! ( set text length ) 2 CELLS + SWAP MOVE ; ( copy text ) : add-empty-todo ( -- addr ) todos buf-next @ 0 todos ,buf 0 todos ,buf ; : remove-todo ( addr -- ) DUP eof-todo SWAP OVER bytes-to-end 2DUP + >R MOVE R> todos buf-next ! ; : next-todo-offset ( addr1 -- u ) @ 2 CELLS + ; : next-todo ( addr -- addr1 ) DUP next-todo-offset + ; : remove-completed ( -- ) todos BEGIN DUP todos buf-next @ < WHILE DUP completed IF DUP remove-todo ELSE next-todo THEN REPEAT DROP ; : each-todo ( xt -- ) todos buf-next @ todos = IF DROP EXIT THEN todos buf-next @ todos DO I SWAP DUP >R EXECUTE R> I next-todo-offset +LOOP DROP ; : inc-count ( n addr -- n2 ) DROP 1+ ; : count-todos ( -- u ) 0 ['] inc-count each-todo ; : inc-completed ( n addr -- n2 ) completed IF 1+ THEN ; : count-completed ( -- u ) 0 ['] inc-completed each-todo ; : inc-not-completed ( n addr -- n2 ) completed 0= IF 1+ THEN ; : count-left ( -- u ) 0 ['] inc-not-completed each-todo ; : .todo ( addr -- ) todo-text TYPE ; : .todos ( -- ) ['] .todo each-todo ; : is-checked ( flag1 addr -- flag2 ) completed AND ; : toggle-all-state ( -- flag ) TRUE ['] is-checked each-todo ; : checked ( -- flag ) S" target.checked" 0 0 EVT-ATTR ; : key-code ( -- x ) S" keyCode" 0 0 EVT-ATTR ; : clear-completed ( -- ) remove-completed repaint ; : temp-str ( addr -- c-addr u ) CELL+ & @ ; : save-todo-temp ( -- ) S" target.value" todo-temp CELL+ 1024 EVT-ATTR todo-temp ! ; : reset-todo-temp ( -- ) 0 todo-temp ! ; : todo-tmp-str ( -- c-addr u ) todo-temp temp-str ; : set-item-temp ( addr -- ) todo-text TUCK item-temp CELL+ SWAP CMOVE item-temp ! ; : item-tmp-str ( -- c-addr u ) item-temp temp-str ; : on-todo-input ( -- ) save-todo-temp ; : on-todo-action ( -- ) key-code 13 = IF todo-tmp-str trim DUP 0= IF 2DROP EXIT THEN add-empty-todo set-todo-text reset-todo-temp THEN repaint ; : set-completed' ( flag addr -- flag ) OVER /top set-completed ; : on-toggle-all ( -- ) checked ['] set-completed' each-todo DROP repaint ; : on-item-checked ( data -- ) checked SWAP set-completed repaint ; : on-todo-item-enter ( addr -- ) TRUE SWAP set-show-remove repaint ; : on-todo-item-leave ( addr -- ) 0 SWAP set-show-remove repaint ; : on-item-start-editing ( addr -- ) DUP set-item-temp TRUE OVER set-editing TRUE OVER set-focus repaint 0 SWAP set-focus repaint ; : on-remove-todo ( addr -- ) remove-todo repaint ; : trim-item ( addr -- ) DUP todo-text trim ROT set-todo-text ; : on-item-blur ( addr -- ) DUP trim-item DUP todo-text-len 0= IF remove-todo ELSE 0 SWAP set-editing THEN repaint ; : on-item-input ( addr -- ) HERE S" target.value" HERE 1024 EVT-ATTR ROT set-todo-text repaint ; : on-item-action ( addr -- ) key-code 13 = IF on-item-blur EXIT THEN key-code 27 = IF item-tmp-str ROT set-todo-text repaint EXIT THEN ( reset from temp ) DROP ; : todo-header ( -- )
S" header" =class

S" todos" text

S" new-todo" =class S" What needs to be done?" =placeholder first-render @ IF empty-attr =focus THEN ['] on-todo-input =oninput ['] on-todo-action =onkeydown todo-tmp-str to-rbuf =input-value
; : todo-item ( addr -- ) >R
  • R@ bind on-todo-item-enter =onmouseenter R@ bind on-todo-item-leave =onmouseleave R@ editing IF R@ completed IF S" completed editing" ELSE S" editing" THEN ELSE R@ completed IF S" completed" ELSE S" " THEN THEN =class
    S" view" =class S" toggle" =class S" checkbox" =type R@ completed IF empty-attr =checked THEN R@ bind on-item-checked =onchange R@ show-remove IF THEN
    S" edit" =class R@ todo-text to-rbuf =input-value R@ focus IF empty-attr =focus THEN R@ bind on-item-blur =onblur R@ bind on-item-start-editing =onfocus R@ bind on-item-input =oninput R@ bind on-item-action =onkeydown
  • R> DROP ; : render-todos ( -- ) count-todos 0= IF EXIT THEN
    S" main" =class S" toggle-all" =id S" toggle-all" =class S" checkbox" =type toggle-all-state IF S" checked" =checked THEN ['] on-toggle-all =onchange
      S" todo-list" =class ['] todo-item each-todo
    ; : items-left ( n-left -- ) >R R@ fmt-int text S" " text R> 1 = IF S" item left" ELSE S" items left" THEN text ; : clear-completed-btn ( -- ) ; : todo-footer ( n-completed n-left -- ) count-todos 0= IF 2DROP EXIT THEN 2>R
    S" footer" =class R> items-left R> 0 > IF clear-completed-btn THEN
    ; : todo-app ( -- )
    S" todoapp" =class todo-header render-todos count-completed count-left todo-footer
    ; : footer-info ( -- ) ; : app
    todo-app footer-info
    0 first-render ! ; repaint-with app repaint 0 QUIET ! ================================================ FILE: examples/todomvc/index.html ================================================ TodoMVC ================================================ FILE: examples/todomvc/index.js ================================================ WasmForth.boot({ wasmURL: 'node_modules/wasm-forth/dist/kernel.wasm', sources: ['node_modules/wasm-forth/dist/core.f', 'node_modules/wasm-forth/dist/vdom.f', 'index.f'], write: msg => console.log(msg) }); ================================================ FILE: examples/todomvc/package.json ================================================ { "name": "example", "version": "1.0.0", "description": "", "main": "index.js", "author": "", "license": "GPL-3.0", "dependencies": { "wasm-forth": "^2.0.0" } } ================================================ FILE: examples/todomvc/vendor/index.css ================================================ /* * Copied from https://github.com/tastejs/todomvc/ */ html, body { margin: 0; padding: 0; } button { margin: 0; padding: 0; border: 0; background: none; font-size: 100%; vertical-align: baseline; font-family: inherit; font-weight: inherit; color: inherit; -webkit-appearance: none; appearance: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } body { font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif; line-height: 1.4em; background: #f5f5f5; color: #4d4d4d; min-width: 230px; max-width: 550px; margin: 0 auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-weight: 300; } :focus { outline: 0; } .hidden { display: none; } .todoapp { background: #fff; margin: 130px 0 40px 0; position: relative; box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1); } .todoapp input::-webkit-input-placeholder { font-style: italic; font-weight: 300; color: #e6e6e6; } .todoapp input::-moz-placeholder { font-style: italic; font-weight: 300; color: #e6e6e6; } .todoapp input::input-placeholder { font-style: italic; font-weight: 300; color: #e6e6e6; } .todoapp h1 { position: absolute; top: -155px; width: 100%; font-size: 100px; font-weight: 100; text-align: center; color: rgba(175, 47, 47, 0.15); -webkit-text-rendering: optimizeLegibility; -moz-text-rendering: optimizeLegibility; text-rendering: optimizeLegibility; } .new-todo, .edit { position: relative; margin: 0; width: 100%; font-size: 24px; font-family: inherit; font-weight: inherit; line-height: 1.4em; border: 0; color: inherit; padding: 6px; border: 1px solid #999; box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2); box-sizing: border-box; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .new-todo { padding: 16px 16px 16px 60px; border: none; background: rgba(0, 0, 0, 0.003); box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03); } .main { position: relative; z-index: 2; border-top: 1px solid #e6e6e6; } .toggle-all { width: 1px; height: 1px; border: none; /* Mobile Safari */ opacity: 0; position: absolute; right: 100%; bottom: 100%; } .toggle-all + label { width: 60px; height: 34px; font-size: 0; position: absolute; top: -52px; left: -13px; -webkit-transform: rotate(90deg); transform: rotate(90deg); } .toggle-all + label:before { content: '❯'; font-size: 22px; color: #e6e6e6; padding: 10px 27px 10px 27px; } .toggle-all:checked + label:before { color: #737373; } .todo-list { margin: 0; padding: 0; list-style: none; } .todo-list li { position: relative; font-size: 24px; border-bottom: 1px solid #ededed; } .todo-list li:last-child { border-bottom: none; } .todo-list li.editing { border-bottom: none; padding: 0; } .todo-list li.editing .edit { display: block; width: calc(100% - 43px); padding: 12px 16px; margin: 0 0 0 43px; } .todo-list li.editing .view { display: none; } .todo-list li .toggle { text-align: center; width: 40px; /* auto, since non-WebKit browsers doesn't support input styling */ height: auto; position: absolute; top: 0; bottom: 0; margin: auto 0; border: none; /* Mobile Safari */ -webkit-appearance: none; appearance: none; } .todo-list li .toggle { opacity: 0; } .todo-list li .toggle + label { /* Firefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433 IE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/ */ background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23ededed%22%20stroke-width%3D%223%22/%3E%3C/svg%3E'); background-repeat: no-repeat; background-position: center left; } .todo-list li .toggle:checked + label { background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23bddad5%22%20stroke-width%3D%223%22/%3E%3Cpath%20fill%3D%22%235dc2af%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22/%3E%3C/svg%3E'); } .todo-list li label { word-break: break-all; padding: 15px 15px 15px 60px; display: block; line-height: 1.2; transition: color 0.4s; } .todo-list li.completed label { color: #d9d9d9; text-decoration: line-through; } .todo-list li .destroy { display: none; position: absolute; top: 0; right: 10px; bottom: 0; width: 40px; height: 40px; margin: auto 0; font-size: 30px; color: #cc9a9a; margin-bottom: 11px; transition: color 0.2s ease-out; } .todo-list li .destroy:hover { color: #af5b5e; } .todo-list li .destroy:after { content: '×'; } .todo-list li:hover .destroy { display: block; } .todo-list li .edit { display: none; } .todo-list li.editing:last-child { margin-bottom: -1px; } .footer { color: #777; padding: 10px 15px; height: 20px; text-align: center; border-top: 1px solid #e6e6e6; } .footer:before { content: ''; position: absolute; right: 0; bottom: 0; left: 0; height: 50px; overflow: hidden; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), 0 8px 0 -3px #f6f6f6, 0 9px 1px -3px rgba(0, 0, 0, 0.2), 0 16px 0 -6px #f6f6f6, 0 17px 2px -6px rgba(0, 0, 0, 0.2); } .todo-count { float: left; text-align: left; } .todo-count strong { font-weight: 300; } .filters { margin: 0; padding: 0; list-style: none; position: absolute; right: 0; left: 0; } .filters li { display: inline; } .filters li a { color: inherit; margin: 3px; padding: 3px 7px; text-decoration: none; border: 1px solid transparent; border-radius: 3px; } .filters li a:hover { border-color: rgba(175, 47, 47, 0.1); } .filters li a.selected { border-color: rgba(175, 47, 47, 0.2); } .clear-completed, html .clear-completed:active { float: right; position: relative; line-height: 20px; text-decoration: none; cursor: pointer; } .clear-completed:hover { text-decoration: underline; } .info { margin: 65px auto 0; color: #bfbfbf; font-size: 10px; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); text-align: center; } .info p { line-height: 1; } .info a { color: inherit; text-decoration: none; font-weight: 400; } .info a:hover { text-decoration: underline; } /* Hack to remove background from Mobile Safari. Can't use it globally since it destroys checkboxes in Firefox */ @media screen and (-webkit-min-device-pixel-ratio:0) { .toggle-all, .todo-list li .toggle { background: none; } .todo-list li .toggle { height: 40px; } } @media (max-width: 430px) { .footer { height: 50px; } .filters { bottom: 10px; } } ================================================ FILE: examples/webpack/README ================================================ To run this example: $ npm install $ npm run build $ python3 -m http.server 8080 then open the browser at http://localhost:8080 ================================================ FILE: examples/webpack/index.html ================================================ Example
    ================================================ FILE: examples/webpack/index.js ================================================ import * as WasmForth from 'wasm-forth'; import wasmURL from 'wasm-forth/dist/kernel.wasm'; import coreURL from 'wasm-forth/dist/core.f'; import vdomURL from 'wasm-forth/dist/vdom.f'; WasmForth.boot({ wasmURL, sources: [coreURL, vdomURL], write: (text) => { document.getElementById('content').textContent += text; } }).then(() => { WasmForth.source(': HELLO S" Hello, World!" TYPE ; HELLO\n'); }); ================================================ FILE: examples/webpack/package.json ================================================ { "name": "example", "version": "1.0.0", "description": "", "main": "index.js", "author": "", "license": "GPL-3.0", "scripts": { "build": "webpack" }, "dependencies": { "wasm-forth": "^2.0.0" }, "devDependencies": { "file-loader": "^1.1.6", "webpack": "^3.10.0" } } ================================================ FILE: examples/webpack/webpack.config.js ================================================ let path = require('path'); module.exports = { entry: { main: './index.js' }, output: { path: path.resolve(__dirname, 'dist'), filename: 'index.js', publicPath: 'dist/' }, module: { rules: [ { test : /\.(f|wasm)$/, loader : 'file-loader' } ] } }; ================================================ FILE: kernel/__init__.py ================================================ ================================================ FILE: kernel/__main__.py ================================================ import shutil import sys import os import assembler BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DIST_PATH = os.path.join(BASE_PATH, '../dist') if not os.path.exists(DIST_PATH): os.makedirs(DIST_PATH) assembler.build_kernel(os.path.join(DIST_PATH, 'kernel.wasm')) for file_name in ('core.f', 'vdom.f'): shutil.copy( os.path.join(BASE_PATH, os.path.join('forth', file_name)), os.path.join(DIST_PATH, file_name), ) if len(sys.argv) > 1 and sys.argv[1] == '--demo-repl': import http.server import socketserver REPL_DIST_PATH = os.path.join(BASE_PATH, '../repl/dist/') if not os.path.exists(REPL_DIST_PATH): os.makedirs(REPL_DIST_PATH) for file_name in ('core.f', 'vdom.f'): shutil.copy( os.path.join(BASE_PATH, 'forth', file_name), os.path.join(REPL_DIST_PATH, file_name), ) shutil.copy( os.path.join(DIST_PATH, 'kernel.wasm'), os.path.join(REPL_DIST_PATH, 'kernel.wasm'), ) os.chdir(os.path.join(BASE_PATH, '..', 'repl')) socketserver.TCPServer.allow_reuse_address = True with socketserver.TCPServer(('', 8080), http.server.SimpleHTTPRequestHandler) as httpd: print('Open your browser at http://localhost:8080/') httpd.serve_forever() ================================================ FILE: kernel/asm_ops.py ================================================ """ Utilities to make it easier to write webassembly opcodes. """ from _binaryen_c import ffi, lib from binaryen_module import module, retain_gc from memory_layout import * # Control flow def block(*instrs, label=None): if label is None: label = ffi.NULL else: label = label.encode('ascii') instrs_array = ffi.new('BinaryenExpressionRef[]', _flatten(instrs)) return lib.BinaryenBlock( module, label, instrs_array, len(instrs_array), lib.BinaryenNone(), ) retain_gc.append(instrs_array) def _flatten(lst, res=None): if res is None: res = [] for item in lst: if isinstance(item, (list, tuple)): _flatten(item, res) else: res.append(item) return res def loop(label, expr): return lib.BinaryenLoop( module, label.encode('ascii'), expr, ) def switch(labels, default_label, cond_expr): labels_array_elems = [ffi.new('char[]', label.encode('ascii')) for label in labels] labels_array = ffi.new('char*[]', labels_array_elems) retain_gc(labels_array_elems, labels_array) return lib.BinaryenSwitch(module, labels_array, len(labels_array), default_label.encode('ascii'), cond_expr, ffi.NULL) def jmp(label, cond_expr=ffi.NULL): return lib.BinaryenBreak(module, label.encode('ascii'), cond_expr, ffi.NULL) # Function calls def call_iiin(label, expr1, expr2, expr3): params = ffi.new('BinaryenExpressionRef[3]', [expr1, expr2, expr3]) retain_gc(params) return lib.BinaryenCall(module, label.encode('ascii'), params, 3, lib.BinaryenNone()) def call_iin(label, expr1, expr2): params = ffi.new('BinaryenExpressionRef[2]', [expr1, expr2]) retain_gc(params) return lib.BinaryenCall(module, label.encode('ascii'), params, 2, lib.BinaryenNone()) def call_iiii_i(label, expr1, expr2, expr3, expr4): params = ffi.new('BinaryenExpressionRef[4]', [expr1, expr2, expr3, expr4]) retain_gc(params) return lib.BinaryenCall(module, label.encode('ascii'), params, 4, lib.BinaryenInt32()) # Memory access def get_reg(reg): return lib.BinaryenGetLocal(module, reg, CELL_TYPE) def get_double_reg(reg): return lib.BinaryenGetLocal(module, reg, DOUBLE_CELL_TYPE) def set_reg(reg, expr): return lib.BinaryenSetLocal(module, reg, expr) def load_cell(addr_expr, cells_offset=0): return lib.BinaryenLoad( module, CELL_SIZE, 0, cells_offset * CELL_SIZE, 0, CELL_TYPE, addr_expr, ) def load_double_cell(addr_expr, cells_offset=0): return lib.BinaryenLoad( module, CELL_SIZE * 2, 0, cells_offset * CELL_SIZE, 0, DOUBLE_CELL_TYPE, addr_expr, ) def store_cell(addr_expr, value_expr, cells_offset=0): return lib.BinaryenStore( module, CELL_SIZE, cells_offset * CELL_SIZE, 0, addr_expr, value_expr, CELL_TYPE, ) def store_double_cell(addr_expr, value_expr, cells_offset=0): return lib.BinaryenStore( module, CELL_SIZE * 2, cells_offset * CELL_SIZE, 0, addr_expr, value_expr, DOUBLE_CELL_TYPE, ) def load_byte(addr_expr): return lib.BinaryenLoad( module, 1, 0, 0, 0, CELL_TYPE, addr_expr, ) def store_byte(addr_expr, value_expr): return lib.BinaryenStore( module, 1, 0, 0, addr_expr, value_expr, CELL_TYPE, # NOTE: there is no 'byte' type in webassembly ) # Stack helpers def invert_double_cell(expr): """forth wants low | hi, but wasm is little endian (i.e. the reverse). Cells are already stored in little-endian, so we can get a proper 64 bit number by rotating by 32 bits. """ return lib.BinaryenBinary(module, lib.BinaryenRotRInt64(), expr, lib.BinaryenConst(module, lib.BinaryenLiteralInt64(32))) def peek(stack_reg, cells_offset): return load_cell(get_reg(stack_reg), cells_offset) def peek_double(stack_reg, cells_offset): return invert_double_cell(load_double_cell(get_reg(stack_reg), cells_offset)) def put(stack_reg, cells_offset, expr): return store_cell(get_reg(stack_reg), expr, cells_offset) def put_double(stack_reg, cells_offset, expr): return store_double_cell(get_reg(stack_reg), invert_double_cell(expr), cells_offset) def inc(reg, n_cells): return set_reg(reg, add_cell_size(reg, n_cells)) def drop(reg, n_cells): return inc(reg, n_cells) def push(stack_reg, expr): """ NOTE: the stack size is already incremented by 1 cell when expr is evaluated. """ return [ inc(stack_reg, -1), put(stack_reg, 0, expr), ] def add_cell_size(reg, n_cells): if n_cells == 0: return get_reg(reg) return add( get_reg(reg), const_cell(n_cells * CELL_SIZE), ) def cmp_neg(cmp_op): # NOT: cmp_op MUST be the reverse of the desired one! return [ put( SP, 1, sub( cmp_op( peek(SP, 1), peek(SP, 0), ), const_cell(1), ), ), drop(SP, 1), ] def cmp_neg_zero(cmp_op): # NOT: cmp_op MUST be the reverse of the desired one! return [ put( SP, 0, sub( cmp_op( peek(SP, 0), const_cell(0), ), const_cell(1), ), ), ] def op_on_tos(op, rhs_expr, stack_reg=SP): """ Applies X = op(X, rhs_expr), where X is the top of the stack. """ return put(stack_reg, 0, op(peek(stack_reg, 0), rhs_expr)) def bin_op(op): return [ put(SP, 1, op(peek(SP, 1), peek(SP, 0))), drop(SP, 1), ] def bin_op_32_32_64(op): return put_double(SP, 0, op(peek(SP, 1), peek(SP, 0))) def bin_op_64_32_64(op): return [ put_double(SP, 1, op(peek_double(SP, 1), peek(SP, 0))), drop(SP, 1), ] # Constants def const_cell(value): return lib.BinaryenConst(module, lib.BinaryenLiteralInt32(value)) def const_double_cell(value): return lib.BinaryenConst(module, lib.BinaryenLiteralInt64(value)) # Type conversions def u_32_to_64(expr): return lib.BinaryenUnary(module, lib.BinaryenExtendUInt32(), expr) def u_64_to_32(expr): return lib.BinaryenUnary(module, lib.BinaryenWrapInt64(), expr) def s_32_to_64(expr): return lib.BinaryenUnary(module, lib.BinaryenExtendSInt32(), expr) def s_64_to_32(expr): return lib.BinaryenUnary(module, lib.BinaryenWrapInt64(), expr) # Comparisons def eqz(expr): return lib.BinaryenUnary(module, lib.BinaryenEqZInt32(), expr) def eq(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenEqInt32(), expr1, expr2) def ne(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenNeInt32(), expr1, expr2) def ge_s(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenGeSInt32(), expr1, expr2) def ge_u(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenGeUInt32(), expr1, expr2) def le_s(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenLeSInt32(), expr1, expr2) def le_u(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenLeUInt32(), expr1, expr2) def l_s(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenLtSInt32(), expr1, expr2) # Math/bit-ops def add(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenAddInt32(), expr1, expr2) def add_64_32(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenAddInt64(), expr1, u_32_to_64(expr2)) def add_64(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenAddInt64(), expr1, expr2) def sub(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenSubInt32(), expr1, expr2) def mul(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenMulInt32(), expr1, expr2) def mul_32_32_64(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenMulInt64(), s_32_to_64(expr1), s_32_to_64(expr2)) def mul_64(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenMulInt64(), expr1, expr2) def umul_32_32_64(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenMulInt64(), u_32_to_64(expr1), u_32_to_64(expr2)) def div(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenDivSInt32(), expr1, expr2) def rem(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenRemSInt32(), expr1, expr2) def div_64_32_32(expr1, expr2): return s_64_to_32(lib.BinaryenBinary(module, lib.BinaryenDivSInt64(), expr1, s_32_to_64(expr2))) def udiv_64_32_32(expr1, expr2): return u_64_to_32(lib.BinaryenBinary(module, lib.BinaryenDivUInt64(), expr1, u_32_to_64(expr2))) def udiv_64_32_64(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenDivUInt64(), expr1, u_32_to_64(expr2)) def rem_64_32_32(expr1, expr2): return s_64_to_32(lib.BinaryenBinary(module, lib.BinaryenRemSInt64(), expr1, s_32_to_64(expr2))) def urem_64_32_32(expr1, expr2): return u_64_to_32(lib.BinaryenBinary(module, lib.BinaryenRemUInt64(), expr1, u_32_to_64(expr2))) def ls(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenShlInt32(), expr1, expr2) def a_rs(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenShrSInt32(), expr1, expr2) def l_rs(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenShrUInt32(), expr1, expr2) def bit_and(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenAndInt32(), expr1, expr2) def bit_or(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenOrInt32(), expr1, expr2) def bit_xor(expr1, expr2): return lib.BinaryenBinary(module, lib.BinaryenXorInt32(), expr1, expr2) ================================================ FILE: kernel/assembler.py ================================================ from _binaryen_c import ffi, lib from asm_ops import * from binaryen_module import module, retain_gc, release_gc from code_words import load_registers, CODE_WORDS from forth_interpreter import FORTH_CONSTANTS, FORTH_VARIABLES, FORTH_COL_DEFS from memory_layout import * def build_kernel(output_file): """ Builds the basic forth kernel, with just enough primitives to run an interpreter, and saves it to a WASM file. """ assemble() save_kernel(output_file) destroy() def assemble(): """ Assembles the forth kernel into the global binaryen module. """ add_imports() add_exports() add_initial_memory() add_interpreter() def add_imports(): """ Add FFI imports to the module (io.read and io.write). """ iii_params = ffi.new('BinaryenType[3]', [CELL_TYPE] * 3) iiin = lib.BinaryenAddFunctionType(module, b'iiin', lib.BinaryenNone(), iii_params, 3) ii_params = ffi.new('BinaryenType[2]', [CELL_TYPE] * 2) iin = lib.BinaryenAddFunctionType(module, b'iin', lib.BinaryenNone(), ii_params, 2) iiii_params = ffi.new('BinaryenType[4]', [CELL_TYPE] * 4) iiii_i = lib.BinaryenAddFunctionType(module, b'iiiii', lib.BinaryenInt32(), iiii_params, 4) lib.BinaryenAddFunctionImport(module, b'read', b'io', b'read', iiin) lib.BinaryenAddFunctionImport(module, b'write', b'io', b'write', iin) lib.BinaryenAddFunctionImport(module, b'patchBody', b'io', b'patchBody', iin) lib.BinaryenAddFunctionImport(module, b'evtAttr', b'io', b'evtAttr', iiii_i) retain_gc(iiii_params) retain_gc(iii_params) retain_gc(ii_params) def add_exports(): """ Exports the interpreter entry point. """ lib.BinaryenAddExport(module, b'exec', b'exec') def add_initial_memory(): """ Initializes the memory with compiled forth constants, variables and column definition. """ forth_words_addrs = {} dictionary_bytes = [] last_name_addr = 0 last_name_addr = add_code_primitives_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr) last_name_addr = add_forth_constants_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr) last_name_addr = add_forth_variables_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr) last_name_addr = add_forth_col_defs_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr) # set LATEST to last_name_addr replace_forth_variable_value(dictionary_bytes, forth_words_addrs, 'LATEST', last_name_addr) # set HERE to HERE_INITIAL + len(dictionary_bytes) replace_forth_variable_value(dictionary_bytes, forth_words_addrs, '\'HERE', HERE_INITIAL + len(dictionary_bytes)) # main task saved registers initial values, will be loaded into registers when the interpreter first boots reg_initial_bytes = [] append_cell(reg_initial_bytes, MAIN_TASK_BASE_VALUE + IP_INITIAL_OFFSET) append_cell(reg_initial_bytes, MAIN_TASK_BASE_VALUE + SP_INITIAL_OFFSET) append_cell(reg_initial_bytes, MAIN_TASK_BASE_VALUE + RS_INITIAL_OFFSET) # address of first forth word to run ip_initial_bytes = [] append_cell(ip_initial_bytes, forth_words_addrs['ABORT']) dictionary_data = ffi.new('char[]', bytes(dictionary_bytes)) reg_initial_data = ffi.new('char[]', bytes(reg_initial_bytes)) ip_initial_data = ffi.new('char[]', bytes(ip_initial_bytes)) segment_contents = ffi.new('char*[]', [reg_initial_data, ip_initial_data, dictionary_data]) segment_offsets = ffi.new('BinaryenExpressionRef[]', [const_cell(MAIN_TASK_BASE_VALUE), const_cell(MAIN_TASK_BASE_VALUE + IP_INITIAL_OFFSET), const_cell(HERE_INITIAL)]) segment_sizes = ffi.new('BinaryenIndex[]', [len(reg_initial_bytes), len(ip_initial_bytes), len(dictionary_bytes)]) segments_passive = ffi.new('char[]', bytes([0, 0, 0])) # memory size is given in number of 64 KB pages, # in this case we use a fixed 128 MB size lib.BinaryenSetMemory(module, 2048, 2048, b'mem', segment_contents, segments_passive, segment_offsets, segment_sizes, 3, 0) retain_gc(dictionary_data, reg_initial_data, segment_contents, segment_offsets, segment_sizes, segments_passive) def add_interpreter(): """ Adds the interpreter function to the global module. """ ii_params = ffi.new('BinaryenType[2]', [CELL_TYPE, CELL_TYPE]) iin = lib.BinaryenAddFunctionType(module, b't_iin', lib.BinaryenNone(), ii_params, len(ii_params)) registers = ffi.new('BinaryenType[]', 8) registers[IP - 2] = CELL_TYPE registers[W - 2] = CELL_TYPE registers[SP - 2] = CELL_TYPE registers[RS - 2] = CELL_TYPE registers[SCRATCH_1 - 2] = CELL_TYPE registers[SCRATCH_2 - 2] = CELL_TYPE registers[SCRATCH_3 - 2] = CELL_TYPE registers[SCRATCH_DOUBLE_1 - 2] = DOUBLE_CELL_TYPE exec_body = block( load_registers(), assemble_interpreter(), label='entry', ) lib.BinaryenAddFunction(module, b'exec', iin, registers, len(registers), exec_body) retain_gc(ii_params, registers) def assemble_interpreter(): # main interpreter switch to execute code words interpreter_body = switch( [label for label, _ in CODE_WORDS], # memory addresses in the dictionary are always greater than # primitive indexes (because of how far into the memory the # dictionary starts). If a code index is not found, we assume # it's a custom initiation code defined using DOES>, so we # execute (dodoes) to run it. '(dodoes)', load_cell(get_reg(W)), ) for label, instrs in CODE_WORDS: interpreter_body = block(block(interpreter_body, label=label), instrs) interpreter_body = block( set_reg(W, load_cell(get_reg(IP))), inc(IP, 1), loop('interpreter_switch', interpreter_body), ) return loop('next', interpreter_body) def add_code_primitives_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr): for code_addr, (label, _) in enumerate(CODE_WORDS): last_name_addr = append_dict_header(dictionary_bytes, forth_words_addrs, last_name_addr, label) append_cell(dictionary_bytes, code_addr) return last_name_addr def add_forth_constants_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr): doconst_addr = find_code_primitive_addr('(doconst)') for label, initial_value in FORTH_CONSTANTS: last_name_addr = append_dict_header(dictionary_bytes, forth_words_addrs, last_name_addr, label) append_cell(dictionary_bytes, doconst_addr) append_cell(dictionary_bytes, initial_value) return last_name_addr def add_forth_variables_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr): dovar_addr = find_code_primitive_addr('(dovar)') for label, initial_value in FORTH_VARIABLES: last_name_addr = append_dict_header(dictionary_bytes, forth_words_addrs, last_name_addr, label) append_cell(dictionary_bytes, dovar_addr) # variable values can be a byte-string or a single-cell integer if isinstance(initial_value, bytes): append_aligned_bytes(dictionary_bytes, initial_value) else: append_cell(dictionary_bytes, initial_value) return last_name_addr def replace_forth_variable_value(dictionary_bytes, forth_words_addrs, label, new_value): replace_cell(dictionary_bytes, forth_words_addrs[label] + CELL_SIZE - HERE_INITIAL, new_value) def add_forth_col_defs_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr): docol_addr = find_code_primitive_addr('(docol)') for label, words, immediate in FORTH_COL_DEFS: last_name_addr = append_dict_header(dictionary_bytes, forth_words_addrs, last_name_addr, label, immediate) append_cell(dictionary_bytes, docol_addr) # compile the body for word in words: if isinstance(word, int): append_cell(dictionary_bytes, word) else: assert word in forth_words_addrs, 'word {} not defined'.format(word) append_cell(dictionary_bytes, forth_words_addrs[word]) append_cell(dictionary_bytes, forth_words_addrs['EXIT']) return last_name_addr def find_code_primitive_addr(primitive_label): for code_addr, (label, _) in enumerate(CODE_WORDS): if label == primitive_label: return code_addr else: raise Exception('The {} code primitive must be defined'.format(primitive_label)) def append_dict_header(dictionary_bytes, forth_words_addrs, last_name_addr, label, immediate=False): """ Appends the header for a definition entry in the forth dictionary. Adds the address of the code word to forth_words_addrs, and returns the address where the (length, name) pair starts. Header structure: - 4 bytes pointer to previous entry - 1 byte of flags (1 = immediate word, 0 = non-immediate word) - 1 byte of label length - 4-byte aligned label bytes (max 30) """ assert len(label) < 31 append_cell(dictionary_bytes, last_name_addr) # pointer to previous entry dictionary_bytes.append(int(immediate)) # 1 byte of flags: 1 = IMMEDIATE, 0 = normal last_name_addr = HERE_INITIAL + len(dictionary_bytes) dictionary_bytes.append(len(label)) # 1 byte of label length (high-bit can be set to 1 to hide the word) append_aligned_bytes(dictionary_bytes, label.encode('ascii')) forth_words_addrs[label] = HERE_INITIAL + len(dictionary_bytes) return last_name_addr def append_aligned_bytes(dictionary_bytes, value): dictionary_bytes.extend(value) append_padding(dictionary_bytes) def append_padding(dictionary_bytes): """pad to CELL_SIZE boundary""" size = len(dictionary_bytes) padded_size = ((CELL_SIZE - (size & (CELL_SIZE - 1))) & (CELL_SIZE - 1)) + size dictionary_bytes.extend([0] * (padded_size - size)) def append_cell(dictionary_bytes, value): # webassembly uses little endian dictionary_bytes.append(value & 0xFF) dictionary_bytes.append((value >> 8) & 0xFF) dictionary_bytes.append((value >> 16) & 0xFF) dictionary_bytes.append((value >> 24) & 0xFF) def replace_cell(dictionary_bytes, offset, value): # webassembly uses little endian dictionary_bytes[offset] = value & 0xFF dictionary_bytes[offset + 1] = (value >> 8) & 0xFF dictionary_bytes[offset + 2] = (value >> 16) & 0xFF dictionary_bytes[offset + 3] = (value >> 24) & 0xFF def print_debug(): lib.BinaryenModulePrint(module) def save_kernel(output_file): """ Saves the global module to a file. """ assert lib.BinaryenModuleValidate(module) == 1 size = 1024 while True: buf = ffi.new('char[]', size) written_size = lib.BinaryenModuleWrite(module, buf, size) if written_size < size: with open(output_file, 'w+b') as out: out.write(ffi.buffer(buf, written_size)) break size *= 2 def destroy(): """ Frees memory allocated to build to the global module. """ lib.BinaryenModuleDispose(module) release_gc() ================================================ FILE: kernel/binaryen_module.py ================================================ from _binaryen_c import lib _no_gc = [] module = lib.BinaryenModuleCreate() def retain_gc(*items): _no_gc.extend(items) def release_gc(): global _no_gc _no_gc = [] ================================================ FILE: kernel/build_binaryen_ext.py ================================================ from os import path from cffi import FFI ffibuilder = FFI() base_path = path.abspath(path.dirname(__file__)) header_path = path.join(base_path, 'vendor/binaryen-c.h') with open(header_path, 'r') as header_file: source = header_file.read() ffibuilder.set_source( '_binaryen_c', r""" #include #include {}""".format(source), libraries=['binaryen'], library_dirs=['vendor'], ) ffibuilder.cdef(source) if __name__ == '__main__': ffibuilder.compile(verbose=True) ================================================ FILE: kernel/code_words.py ================================================ """ Basic Forth words defined directly in WebAssembly. """ from asm_ops import * def store_registers(): """ Store registers into the memory, so the interpeter can be restarted, similar to a context switch. """ # NOTE: it's not necessary to store/reload register W, its value # will be refreshed from the IP return [ store_cell(_register_mem_addr(IP_MEM_OFFSET), get_reg(IP)), store_cell(_register_mem_addr(SP_MEM_OFFSET), get_reg(SP)), store_cell(_register_mem_addr(RS_MEM_OFFSET), get_reg(RS)), ] def load_registers(): """ Load registers from the memory, to restart the interpeter, similar to a context switch. """ return [ set_reg(IP, load_cell(_register_mem_addr(IP_MEM_OFFSET))), set_reg(SP, load_cell(_register_mem_addr(SP_MEM_OFFSET))), set_reg(RS, load_cell(_register_mem_addr(RS_MEM_OFFSET))), ] def _register_mem_addr(offset): return add(get_reg(TASK_BASE_PARAM), const_cell(offset)) def _branch(): """ Branch to the instruction indicated by the byte offset stored in the next cell pointed by IP """ return [ # relative jump to offset, bytes offset calculated and stored # after the current codeword set_reg( IP, add( get_reg(IP), # note: offset in bytes, user must manually skip the address load_cell(get_reg(IP)), ), ), jmp('next'), ] def _call_iin_sync(name): return [ call_iin(name, peek(SP, 1), peek(SP, 0)), drop(SP, 2), ] def _call_iiii_i_sync(name): return [ put(SP, 3, call_iiii_i(name, peek(SP, 3), peek(SP, 2), peek(SP, 1), peek(SP, 0))), drop(SP, 3), ] def _call_iiin_async(name): return [ # store in temporary registers, so we can drop # from the stack before executing the FFI call set_reg(SCRATCH_1, peek(SP, 1)), set_reg(SCRATCH_2, peek(SP, 0)), drop(SP, 2), # store before the FFI call, so it can re-enter the interpeter asynchronously store_registers(), call_iiin(name, get_reg(TASK_BASE_PARAM), get_reg(SCRATCH_1), get_reg(SCRATCH_2)), # quit, it's responsibility of the FFI call to restart the # interpreter in a future next event loop cycle jmp('entry'), ] CODE_WORDS = [ # Initiation codes (non-standard words) ('(docol)', [ # ( R: -- c-addr ) push(RS, get_reg(IP)), set_reg(IP, add_cell_size(W, 1)), jmp('next'), ]), ('(doconst)', [ # ( -- x ) push(SP, load_cell(get_reg(W), 1)), jmp('next'), ]), ('(dovar)', [ # ( -- a-addr ) push(SP, add_cell_size(W, 1)), jmp('next'), ]), ('(dodoes)', [ # ( -- a-addr ) push(RS, get_reg(IP)), push(SP, add_cell_size(W, 1)), # see the switch in assemble_interpreter, the cell pointed by # W contains the address to execute compiled in by (DOES>) set_reg(IP, load_cell(get_reg(W))), jmp('next'), ]), # FFI (non-standard words, async) # these quit the interpreter. The called foreign function must then re-enter it. Return value is obtained using 'task-param'. ('READ', [ # ( c-addr u1 -- ) _call_iiin_async('read'), ]), # FFI (sync) ('WRITE', [ # ( c-addr u1 -- ) _call_iin_sync('write'), jmp('next'), ]), ('PATCH-BODY', [ # ( addr u1 -- ) _call_iin_sync('patchBody'), jmp('next'), ]), ('EVT-ATTR', [ # ( addr1 u1 addr2 u2 -- u3 ) _call_iiii_i_sync('evtAttr'), jmp('next'), ]), # Non-standard extensions, useful to implement the interpreter ('task-base', [ # ( -- addr ) push(SP, get_reg(TASK_BASE_PARAM)), jmp('next'), ]), ('task-base!', [ # ( addr -- ) set_reg(TASK_BASE_PARAM, peek(SP, 0)), drop(SP, 1), jmp('next'), ]), ('task-param', [ # ( -- x ) push(SP, get_reg(TASK_PARAM)), jmp('next'), ]), ('lit', [ # ( -- x ) # load literal value kept in next cell, which is now pointed by IP push(SP, load_cell(get_reg(IP))), inc(IP, 1), jmp('next'), ]), ('RP!', [ # ( a-addr -- ) set_reg(RS, peek(SP, 0)), drop(SP, 1), jmp('next'), ]), ('RP@', [ # ( -- a-addr ) inc(SP, -1), put(SP, 0, get_reg(RS)), jmp('next'), ]), ('SP!', [ # ( a-addr -- ) set_reg(SP, peek(SP, 0)), jmp('next'), ]), ('SP@', [ # ( -- a-addr ) # returns address of stack top on top of the stack, # counting the newly added address inc(SP, -1), put(SP, 0, get_reg(SP)), jmp('next'), ]), ('SKIP', [ # ( c-addr1 u1 c -- c-addr2 u2 ) set_reg(SCRATCH_1, peek(SP, 0)), # c set_reg(SCRATCH_2, peek(SP, 1)), # u1 set_reg(SCRATCH_3, peek(SP, 2)), # c-addr1 drop(SP, 1), loop( 'SKIP-loop', block( jmp( 'SKIP-loop-done', cond_expr=le_s(get_reg(SCRATCH_2), const_cell(0)), ), jmp( 'SKIP-loop-done', cond_expr=ne(load_byte(get_reg(SCRATCH_3)), get_reg(SCRATCH_1)), ), set_reg(SCRATCH_2, sub(get_reg(SCRATCH_2), const_cell(1))), set_reg(SCRATCH_3, add(get_reg(SCRATCH_3), const_cell(1))), jmp('SKIP-loop'), label='SKIP-loop-done', ), ), put(SP, 0, get_reg(SCRATCH_2)), put(SP, 1, get_reg(SCRATCH_3)), jmp('next'), ]), ('SCAN', [ # ( c-addr1 u1 c -- c-addr2 u2 ) set_reg(SCRATCH_1, peek(SP, 0)), # c set_reg(SCRATCH_2, peek(SP, 1)), # u1 set_reg(SCRATCH_3, peek(SP, 2)), # c-addr1 drop(SP, 1), loop( 'SCAN-loop', block( jmp( 'SCAN-loop-done', cond_expr=le_s(get_reg(SCRATCH_2), const_cell(0)), ), jmp( 'SCAN-loop-done', cond_expr=eq(load_byte(get_reg(SCRATCH_3)), get_reg(SCRATCH_1)), ), set_reg(SCRATCH_2, sub(get_reg(SCRATCH_2), const_cell(1))), set_reg(SCRATCH_3, add(get_reg(SCRATCH_3), const_cell(1))), jmp('SCAN-loop'), label='SCAN-loop-done', ), ), put(SP, 0, get_reg(SCRATCH_2)), put(SP, 1, get_reg(SCRATCH_3)), jmp('next'), ]), ('EQ-COUNTED', [ # ( c-addr1 c-addr2 -- flag ) set_reg(SCRATCH_1, load_byte(peek(SP, 0))), # n1 set_reg(SCRATCH_2, load_byte(peek(SP, 1))), # n2 block( jmp('eq-counted-if', cond_expr=eq(get_reg(SCRATCH_1), get_reg(SCRATCH_2))), put(SP, 1, const_cell(0)), drop(SP, 1), jmp('next'), label='eq-counted-if', ), loop( 'eq-counted-loop', block( block( jmp( 'eq-counted-ok', cond_expr=le_s(get_reg(SCRATCH_1), const_cell(0)), ), jmp( 'eq-counted-loop-fail', cond_expr=ne( load_byte(add(peek(SP, 0), get_reg(SCRATCH_1))), load_byte(add(peek(SP, 1), get_reg(SCRATCH_1))), ), ), set_reg(SCRATCH_1, sub(get_reg(SCRATCH_1), const_cell(1))), jmp('eq-counted-loop'), label='eq-counted-loop-fail', ), put(SP, 1, const_cell(0)), drop(SP, 1), jmp('next'), label='eq-counted-ok', ), ), put(SP, 1, const_cell(-1)), drop(SP, 1), jmp('next'), ]), # Branching/looping (non-standard words) ('branch', [ # ( -- ) _branch(), ]), ('?branch', [ # ( x -- ) block( jmp('?branch-if', cond_expr=ne(peek(SP, 0), const_cell(0))), drop(SP, 1), _branch(), label='?branch-if', ), drop(SP, 1), inc(IP, 1), # if false, skip the address jmp('next'), ]), ('(do)', [ # ( limit index -- R: -- loop-end-addr limit index ) inc(RS, -3), # copy limit and index in one go store_double_cell(get_reg(RS), load_double_cell(get_reg(SP))), put(RS, 2, load_cell(get_reg(IP))), # the loop end address, stored in the next cell inc(IP, 1), # skip the loop-end-addr drop(SP, 2), jmp('next'), ]), ('(loop)', [ # ( R: loop-end-addr limit index1 -- | loop-end-addr limit index2 ) op_on_tos(add, const_cell(1), stack_reg=RS), block( jmp('(loop)-if', l_s(peek(RS, 0), peek(RS, 1))), drop(RS, 3), inc(IP, 1), # skip the address jmp('next'), label='(loop)-if', ), _branch(), ]), ('(+loop)', [ # ( n -- R: loop-end-addr limit index1 -- | loop-end-addr limit index2 ) op_on_tos(add, peek(SP, 0), stack_reg=RS), drop(SP, 1), block( jmp('(+loop)-if', l_s(peek(RS, 0), peek(RS, 1))), drop(RS, 3), inc(IP, 1), # skip the address jmp('next'), label='(+loop)-if', ), _branch(), ]), # Core words # Stack manipulation ('>R', [ # ( x -- R: -- x ) push(RS, peek(SP, 0)), drop(SP, 1), jmp('next'), ]), ('R>', [ # ( -- x R: x -- ) push(SP, peek(RS, 0)), drop(RS, 1), jmp('next'), ]), ('R@', [ # ( -- x R: x -- x ) push(SP, peek(RS, 0)), jmp('next'), ]), ('DROP', [ # ( x -- ) drop(SP, 1), jmp('next'), ]), ('DUP', [ # ( x -- x x ) push(SP, peek(SP, 1)), jmp('next'), ]), ('2DUP', [ # ( x1 x2 -- x1 x2 x1 x2 ) inc(SP, -2), store_double_cell(get_reg(SP), load_double_cell(get_reg(SP), 2)), jmp('next'), ]), ('SWAP', [ # ( x1 x2 -- x2 x1 ) set_reg(SCRATCH_1, peek(SP, 0)), put(SP, 0, peek(SP, 1)), put(SP, 1, get_reg(SCRATCH_1)), jmp('next'), ]), ('OVER', [ # ( x1 x2 -- x1 x2 x1 ) push(SP, peek(SP, 2)), jmp('next'), ]), ('ROT', [ # ( x1 x2 x3 -- x2 x3 x1 ) set_reg(SCRATCH_1, peek(SP, 2)), put(SP, 2, peek(SP, 1)), put(SP, 1, peek(SP, 0)), put(SP, 0, get_reg(SCRATCH_1)), jmp('next'), ]), ('NIP', [ # ( x1 x2 -- x2 ) put(SP, 1, peek(SP, 0)), drop(SP, 1), jmp('next'), ]), ('TUCK', [ # ( x1 x2 -- x2 x1 x2 ) inc(SP, -1), put(SP, 0, peek(SP, 1)), put(SP, 1, peek(SP, 2)), put(SP, 2, peek(SP, 0)), jmp('next'), ]), ('2DROP', [ # ( x x -- ) drop(SP, 2), jmp('next'), ]), ('2OVER', [ # ( x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2 ) inc(SP, -2), store_double_cell(get_reg(SP), load_double_cell(get_reg(SP), 4)), jmp('next'), ]), ('2SWAP', [ # ( x1 x2 x3 x4 -- x3 x4 x1 x2 ) set_reg(SCRATCH_DOUBLE_1, load_double_cell(get_reg(SP))), store_double_cell(get_reg(SP), load_double_cell(get_reg(SP), 2)), store_double_cell(get_reg(SP), get_double_reg(SCRATCH_DOUBLE_1), 2), jmp('next'), ]), # Memory access ('@', [ # ( a-addr -- x ) put(SP, 0, load_cell(peek(SP, 0))), jmp('next'), ]), ('!', [ # ( x a-addr -- ) store_cell(peek(SP, 0), peek(SP, 1)), drop(SP, 2), jmp('next'), ]), ('+!', [ # ( n1|u1 a-addr -- ) store_cell( peek(SP, 0), add( load_cell(peek(SP, 0)), peek(SP, 1), ), ), drop(SP, 2), jmp('next'), ]), ('C@', [ # ( a-addr -- x ) put(SP, 0, load_byte(peek(SP, 0))), jmp('next'), ]), ('C!', [ # ( c c-addr -- ) store_byte(peek(SP, 0), peek(SP, 1)), drop(SP, 2), jmp('next'), ]), ('CMOVE', [ # ( c-addr1 c-addr2 u -- ) set_reg(SCRATCH_1, peek(SP, 2)), # c-addr-1 set_reg(SCRATCH_2, add(get_reg(SCRATCH_1), peek(SP, 0))), # c-addr-1 + u set_reg(SCRATCH_3, peek(SP, 1)), # c-addr-2 loop( 'cmove-loop', block( jmp( 'cmove-loop-done', cond_expr=le_s(get_reg(SCRATCH_2), get_reg(SCRATCH_1)), ), store_byte(get_reg(SCRATCH_3), load_byte(get_reg(SCRATCH_1))), set_reg(SCRATCH_1, add(get_reg(SCRATCH_1), const_cell(1))), set_reg(SCRATCH_3, add(get_reg(SCRATCH_3), const_cell(1))), jmp('cmove-loop'), label='cmove-loop-done', ), ), drop(SP, 3), jmp('next'), ]), ('CMOVE>', [ # ( c-addr1 c-addr2 u -- ) set_reg(SCRATCH_2, peek(SP, 0)), # u set_reg(SCRATCH_1, peek(SP, 2)), # c-addr-1 set_reg(SCRATCH_3, sub(add(get_reg(SCRATCH_2), peek(SP, 1)), const_cell(1))), # c-addr-2 + u - 1 set_reg(SCRATCH_2, sub(add(get_reg(SCRATCH_2), get_reg(SCRATCH_1)), const_cell(1))), # c-addr-1 + u - 1 loop( 'cmove>-loop', block( jmp( 'cmove>-loop-done', cond_expr=l_s(get_reg(SCRATCH_2), get_reg(SCRATCH_1)), ), store_byte(get_reg(SCRATCH_3), load_byte(get_reg(SCRATCH_2))), set_reg(SCRATCH_2, sub(get_reg(SCRATCH_2), const_cell(1))), set_reg(SCRATCH_3, sub(get_reg(SCRATCH_3), const_cell(1))), jmp('cmove>-loop'), label='cmove>-loop-done', ), ), drop(SP, 3), jmp('next'), ]), # Loops ('I', [ # ( -- n|u R: loop-sys1 -- loop-sys1 ) push(SP, peek(RS, 0)), jmp('next'), ]), ('J', [ # ( -- n|u R: loop-sys1 loop-sys2 -- loop-sys1 loop-sys2 ) push(SP, peek(RS, 3)), # a do-loop has 3 control parameters jmp('next'), ]), ('UNLOOP', [ # ( R: loop-end-addr sys1 sys2 -- ) drop(RS, 3), jmp('next'), ]), ('LEAVE', [ # ( loop-end-addr limit index -- ) set_reg(IP, peek(RS, 2)), drop(RS, 3), jmp('next'), ]), # Control ('EXECUTE', [ # ( i*x xt -- j*x ) set_reg(W, peek(SP, 0)), drop(SP, 1), jmp('interpreter_switch'), ]), ('EXIT', [ set_reg(IP, load_cell(get_reg(RS))), drop(RS, 1), jmp('next'), ]), ('BYE', [ jmp('entry'), ]), # Type conversions ('S>D', [ # ( n -- d ) inc(SP, -1), put_double(SP, 0, s_32_to_64(peek(SP, 1))), jmp('next'), ]), ('D>S', [ # ( d -- n ) put(SP, 1, s_64_to_32(peek_double(SP, 0))), drop(SP, 1), jmp('next'), ]), # Comparisons ('=', [ # ( x1 x2 -- flag ) cmp_neg(ne), jmp('next'), ]), ('<>', [ # ( x1 x2 -- x3 ) cmp_neg(eq), jmp('next'), ]), ('<', [ # ( n1 n2 -- flag ) cmp_neg(ge_s), jmp('next'), ]), ('>', [ # ( n1 n2 -- flag ) cmp_neg(le_s), jmp('next'), ]), ('U<', [ # ( u1 u2 -- flag ) cmp_neg(ge_u), jmp('next'), ]), ('U>', [ # ( u1 u2 -- flag ) cmp_neg(le_u), jmp('next'), ]), ('0<', [ # ( n -- flag ) cmp_neg_zero(ge_s), jmp('next'), ]), ('0=', [ # ( n -- flag ) cmp_neg_zero(ne), jmp('next'), ]), # Bitwise operations ('INVERT', [ # ( x1 -- x2 ) op_on_tos(bit_xor, const_cell(-1)), jmp('next'), ]), ('AND', [ # ( x1 x2 -- x3 ) bin_op(bit_and), jmp('next'), ]), ('OR', [ # ( x1 x2 -- x3 ) bin_op(bit_or), jmp('next'), ]), ('XOR', [ # ( x1 x2 -- x3 ) bin_op(bit_xor), jmp('next'), ]), ('LSHIFT', [ # ( x1 u -- x2 ) bin_op(ls), jmp('next'), ]), ('RSHIFT', [ # ( x1 u -- x2 ) bin_op(l_rs), jmp('next'), ]), # Single-cell math ('NEGATE', [ # ( x1 -- x2 ) op_on_tos(mul, const_cell(-1)), jmp('next'), ]), ('+', [ # ( n1|u1 n2|u2 -- n3|u3 ) bin_op(add), jmp('next'), ]), ('-', [ # ( n1|u1 n2|u2 -- n3|u3 ) bin_op(sub), jmp('next'), ]), ('*', [ # ( n1 n2 -- n3 ) bin_op(mul), jmp('next'), ]), ('/MOD', [ # ( n1 n2 -- n_rem n_quot ) set_reg(SCRATCH_1, div(peek(SP, 1), peek(SP, 0))), put(SP, 1, rem(peek(SP, 1), peek(SP, 0))), put(SP, 0, get_reg(SCRATCH_1)), jmp('next'), ]), ('1+', [ # ( n1|u1 -- n2|u2 ) op_on_tos(add, const_cell(1)), jmp('next'), ]), ('1-', [ # ( n1|u1 -- n2|u2 ) op_on_tos(add, const_cell(-1)), jmp('next'), ]), ('2*', [ # ( x1 -- x2 ) op_on_tos(ls, const_cell(1)), jmp('next'), ]), ('2/', [ # ( x1 -- x2 ) op_on_tos(a_rs, const_cell(1)), jmp('next'), ]), # Mixed math ('M*', [ # ( n1 n2 -- d ) bin_op_32_32_64(mul_32_32_64), jmp('next'), ]), ('UM*', [ # ( u1 u2 -- ud ) bin_op_32_32_64(umul_32_32_64), jmp('next'), ]), ('SM/REM', [ # ( d1 n1 -- n_rem n_quot ) set_reg(SCRATCH_1, div_64_32_32(peek_double(SP, 1), peek(SP, 0))), put(SP, 2, rem_64_32_32(peek_double(SP, 1), peek(SP, 0))), put(SP, 1, get_reg(SCRATCH_1)), drop(SP, 1), jmp('next'), ]), ('UM/MOD', [ # ( ud u1 -- u_rem u_quot ) set_reg(SCRATCH_1, udiv_64_32_32(peek_double(SP, 1), peek(SP, 0))), put(SP, 1, urem_64_32_32(peek_double(SP, 1), peek(SP, 0))), put(SP, 2, get_reg(SCRATCH_1)), drop(SP, 1), jmp('next'), ]), ('UD/MOD', [ # ( ud1 u1 -- ud_quot u_rem ) set_reg(SCRATCH_DOUBLE_1, udiv_64_32_64(peek_double(SP, 1), peek(SP, 0))), put(SP, 0, urem_64_32_32(peek_double(SP, 1), peek(SP, 0))), put_double(SP, 1, get_double_reg(SCRATCH_DOUBLE_1)), jmp('next'), ]), # Double-cell math ('DNEGATE', [ # ( d1 -- d2 ) put_double(SP, 0, mul_64(peek_double(SP, 0), const_double_cell(-1))), jmp('next'), ]), ('D+', [ # ( d1|ud1 d2|ud2 -- d3|ud3 ) put_double(SP, 2, add_64(peek_double(SP, 2), peek_double(SP, 0))), drop(SP, 2), jmp('next'), ]), ('D*', [ # ( d1|ud1 d2|ud2 -- d3|ud3 ) put_double(SP, 2, mul_64(peek_double(SP, 2), peek_double(SP, 0))), drop(SP, 2), jmp('next'), ]), ] ================================================ FILE: kernel/forth/core.f ================================================ 1 QUIET ! : IMMEDIATE 1 LATEST @ 1- C! ; : ( SOURCE >IN @ /STRING 41 SCAN DROP CHAR+ SOURCE DROP - >IN ! ; IMMEDIATE : CELLS ( n1 -- n2 ) 0 CELL+ * ; : NFA>CFA ( c-addr1 -- c-addr2 ) ( 127 AND to unsmudge the length in case the definition is hidden ) DUP C@ 127 AND + 1+ ALIGNED ; : DOES> ( R: ret -- ) R> LATEST @ NFA>CFA ! ; : CREATE ( "name" -- ) HEADER lit (dovar) @ , ; : VARIABLE ( "name" -- ) CREATE 0 CELL+ ALLOT ; : CONSTANT ( x "name" -- ) HEADER lit (doconst) @ , , ; : EMBED-STR ( "ccc" -- ) SOURCE >IN @ /STRING OVER >R 34 SCAN DROP R@ - DUP CHAR+ >IN +! DUP , R> HERE ROT DUP >R CMOVE R> ALIGNED ALLOT ; : GET-EMBEDDED-STR ( -- a-addr u ) R> DUP DUP @ + ALIGNED CELL+ >R ( skip the characters when executing ) DUP CELL+ SWAP @ ; : S" ( "ccc" -- ) lit GET-EMBEDDED-STR , EMBED-STR ; IMMEDIATE : ." ( "ccc" -- ) lit GET-EMBEDDED-STR , EMBED-STR lit WRITE , ; IMMEDIATE : IF ( compilation: C: -- orig, runtime: x -- ) lit ?branch , HERE 0 , ( placeholder, filled in by THEN/ELSE ) ; IMMEDIATE : PATCH-IF ( orig -- ) HERE OVER - SWAP ! ; : ELSE ( compilation: C: orig1 -- orig2, runtime: -- ) lit branch , HERE 0 , SWAP PATCH-IF ; IMMEDIATE : THEN ( compilation: C: orig --, runtime: -- ) PATCH-IF ; IMMEDIATE : ' ( "name" -- xt ) BL WORD FIND 0= IF ." word to compile not found: " COUNT WRITE ABORT THEN ; : ['] ( compilation: "name" --, runtime: -- xt ) lit lit , ' , ; IMMEDIATE : POSTPONE ( compilation: "name" -- ) BL WORD FIND DUP 0= IF ." word to postpone not found: " OVER COUNT WRITE ABORT THEN SWAP lit lit , , 1 = IF ['] EXECUTE , ELSE ['] , , THEN ; IMMEDIATE : DO ( compilation: C: -- loop-addr, runtime: n1|u1 n2|u2 -- R: -- loop-end-addr limit index ) ['] (do) , 0 , ( will be patched by LOOP/+LOOP ) HERE ; IMMEDIATE : PATCH-DO ( do-sys -- ) HERE SWAP 1 CELLS - ! ( patch the paren-do-paren introduced by DO ) ; : LOOP ( compilation: C: do-sys --, runtime: R: loop-sys1 -- | loop-sys2 ) ['] (loop) , DUP HERE - , PATCH-DO ; IMMEDIATE : +LOOP ( compilation: C: do-sys --, runtime: n -- R: loop-sys1 -- | loop-sys2 ) ['] (+loop) , DUP HERE - , PATCH-DO ; IMMEDIATE : BEGIN ( compilation: C: -- dest, runtime: -- ) HERE ; IMMEDIATE : UNTIL ( compilation: C: dest -- , runtime: x -- ) ['] ?branch , HERE - , ; IMMEDIATE : WHILE ( compilation: C: dest -- orig dest, runtime: x -- ) ['] ?branch , HERE SWAP 0 , ( placeholder, patched by REPEAT ) ; IMMEDIATE : REPEAT ( compilation: orig dest --, runtime: -- ) ['] branch , HERE - , HERE OVER - SWAP ! ( patch WHILE ?branch offset ) ; IMMEDIATE : AGAIN ( compilation: dest --, runtime: -- ) ['] branch , HERE - , ; IMMEDIATE : [ ( -- ) 0 STATE ! ; IMMEDIATE : ] ( -- ) 1 STATE ! ; : CHAR ( "name" -- char ) BL WORD 1+ C@ ; : [CHAR] ( compilation: "name" --, runtime: -- c ) CHAR ['] lit , , ; IMMEDIATE VARIABLE #SIZE 1024 CONSTANT #MAX-SIZE : #NEXT-FREE-SPACE ( -- c-addr ) HERE #MAX-SIZE + #SIZE @ - ; : <# ( -- ) 0 #SIZE ! ; : HOLD ( char -- ) #NEXT-FREE-SPACE C! 1 #SIZE +! ; : SIGN ( n -- ) 0 < IF [CHAR] - HOLD THEN ; : # ( ud1 -- ud2 ) BASE @ UD/MOD DUP 10 < IF 48 ELSE 65 THEN + HOLD ; : #S ( ud1 -- ud2 ) BEGIN # 2DUP 0= SWAP 0= AND UNTIL ; : #> ( xd -- c-addr u ) 2DROP #NEXT-FREE-SPACE 1+ #SIZE @ ; : */MOD ( n1 n2 n3 -- n4 n5 ) >R M* R> SM/REM ; : */ ( n1 n2 n3 -- n4 ) */MOD SWAP DROP ; : FM/MOD ( d1 n1 -- n2 n3 ) ( note: the sign is in the high cell ) 2DUP 0 < SWAP 0 < XOR IF DUP >R SM/REM 1- SWAP R> + SWAP ELSE SM/REM THEN ; : ABS ( n -- u ) DUP 0 < IF 0 SWAP - THEN ; : TYPE ( c-addr u -- ) WRITE ; : . ( n -- ) DUP ABS S>D <# BL HOLD #S ROT SIGN #> TYPE ; : U. ( u -- ) 0 <# BL HOLD #S #> TYPE ; : 2! ( x1 x2 a-addr -- ) SWAP OVER ! CELL+ ! ; : 2@ ( a-addr -- x1 x2 ) DUP CELL+ @ SWAP @ ; : >BODY ( xt -- a-addr ) CELL+ ; : (ABORT") ( i*x x1 c-addr u -- | i*x R: j*x -- | j*x ) ROT IF TYPE ABORT ELSE 2DROP THEN ; : ABORT" ( compilation: "ccc" --, runtime: i*x x1 -- | i*x R: j*x -- | j*x ) ['] GET-EMBEDDED-STR , EMBED-STR ['] (ABORT") , ; IMMEDIATE : ALIGN ( -- ) HERE ALIGNED HERE - ALLOT ; : CHARS ( n1 -- n2 ) ; : EMIT ( x -- ) PAD C! PAD 1 TYPE ; : CR ( -- ) 10 EMIT ; : S= ( c-addr1 u1 c-addr2 u2 -- flag ) ROT 2DUP = IF DROP 0 DO 2DUP I + C@ SWAP I + C@ = INVERT IF UNLOOP 2DROP 0 EXIT THEN LOOP 2DROP 0 1- ELSE 2DROP 2DROP 0 THEN ; : TRUE ( -- true ) 0 1- ; : ENVIRONMENT? ( c-addr u -- false | i*x true ) 2DUP S" /COUNTED-STRING" S= IF 2DROP 127 TRUE EXIT THEN 2DUP S" /HOLD" S= IF 2DROP #MAX-SIZE TRUE EXIT THEN 2DUP S" /PAD" S= IF 2DROP 4096 TRUE EXIT THEN 2DUP S" ADDRESS-UNIT-BITS" S= IF 2DROP 8 TRUE EXIT THEN 2DUP S" CORE" S= IF 2DROP TRUE TRUE EXIT THEN 2DUP S" CORE-EXT" S= IF 2DROP 0 TRUE EXIT THEN 2DUP S" FLOORED" S= IF 2DROP 0 TRUE EXIT THEN 2DUP S" MAX-CHAR" S= IF 2DROP TRUE TRUE EXIT THEN 2DUP S" MAX-D" S= IF 2DROP 0 INVERT DUP 1 RSHIFT TRUE EXIT THEN 2DUP S" MAX-N" S= IF 2DROP 1 31 LSHIFT 1- TRUE EXIT THEN 2DUP S" MAX-U" S= IF 2DROP 0 INVERT TRUE EXIT THEN 2DUP S" MAX-UD" S= IF 2DROP 0 INVERT DUP TRUE EXIT THEN 2DUP S" RETURN-STACK-CELLS" S= IF 2DROP 1024 TRUE EXIT THEN 2DUP S" STACK-CELLS" S= IF 2DROP 1024 TRUE EXIT THEN 2DROP 0 ; : EVALUATE ( i*x c-addr u -- j*x ) SOURCE-ID @ >R IN-BUF @ >R IN-BUF-EOL @ >R IN-BUF-SIZE @ >R >IN @ >R -1 SOURCE-ID ! 0 >IN ! IN-BUF-EOL ! IN-BUF ! INTERPRET R> >IN ! R> IN-BUF-SIZE ! R> IN-BUF-EOL ! R> IN-BUF ! R> SOURCE-ID ! ; : KEY ( -- char ) >IN @ IN-BUF-EOL @ > IF LINE 2DROP 0 >IN ! THEN IN-BUF @ >IN @ + C@ 1 >IN +! ; : LITERAL ( compilation: x --, runtime: -- x ) ['] lit , , ; IMMEDIATE : MAX ( n1 n2 -- n3 ) 2DUP < IF SWAP THEN DROP ; : MIN ( n1 n2 -- n3 ) 2DUP > IF SWAP THEN DROP ; : MOD ( n1 n2 -- n3 ) /MOD DROP ; : MOVE ( addr1 addr2 u -- ) >R 2DUP < IF R> CMOVE> ELSE R> CMOVE THEN ; : RECURSE ( compilation: -- ) LATEST @ NFA>CFA , ; IMMEDIATE : SPACE ( -- ) BL EMIT ; : SPACES ( n -- ) 0 SWAP DO SPACE LOOP ; : >= ( n1 n2 -- flag ) < INVERT ; : ACCEPT ( c-addr +n1 -- +n2 ) >IN @ IN-BUF-EOL @ >= IF LINE 2DROP 0 >IN ! THEN IN-BUF-EOL @ >IN @ - MIN >R ( c-addr R: n2 ) IN-BUF @ >IN @ + SWAP R@ MOVE R@ >IN +! R> ; : ?DUP ( x -- 0 | x x ) DUP 0= IF DUP THEN ; : FILL ( c-addr u c -- ) ROT ROT 0 DO 2DUP I + C! LOOP 2DROP ; ( core extension words ) ( NOTE: #TIB, .(, .R, :NONAME, ?DO, C" not implemented ) : 0<> ( x -- flag ) 0= INVERT ; : 0> ( x -- flag ) 0 > ; : 2>R ( x1 x2 -- R: -- x1 x2 ) R> ROT >R SWAP >R >R ; : 2R> ( -- x1 x2 R: x1 x2 -- ) R> R> R> SWAP ROT >R ; : 2R@ ( -- x1 x2 R: x1 x2 -- x1 x2 ) R> R> R> 2DUP >R >R ROT >R SWAP ; : <> ( x1 x2 - flag ) = INVERT ; ( non-standard utilities ) : SP0 ( -- addr ) 10 1024 * CELL+ task-base + ; : sl ( -- n ) SP@ CELL+ SP0 SWAP - 0 CELL+ /MOD SWAP DROP ; : .NOSPACE ( n -- ) DUP ABS S>D <# #S ROT SIGN #> TYPE ; : .sl ( -- ) S" <" TYPE sl .NOSPACE S" > " TYPE ; : PEEK ( u -- x ) 1+ CELLS SP0 SWAP - @ ; : .sitem ( u -- ) PEEK . ; : .s ( -- ) .sl sl 0 > IF sl 0 DO I .sitem LOOP THEN ; ( setup cooperative multi tasking ) 11 1024 * CONSTANT task-size 5 1024 * CELL+ CONSTANT task-rs-offset 3 CELLS CONSTANT task-ip-initial-offset 0 CONSTANT ip-mem-offset VARIABLE task-free-block 0 task-free-block ! : find-free-block ( -- addr flag ) task-free-block @ DUP 0= IF 0 EXIT THEN DUP @ task-free-block ! 1 ; : create-block ( -- addr ) HERE task-size ALLOT ; : alloc-block ( -- addr ) find-free-block 0= IF DROP create-block THEN ; : release-block ( addr -- ) task-free-block @ OVER ! task-free-block ! ; : end-task ( -- ) task-base release-block BYE ; : new-task ( xt -- ) alloc-block task-base! >R RESET-SP R> task-base task-rs-offset + RP! EXECUTE end-task ; : start-task ( -- ) task-param new-task ; : ready ( -- ) ." Ready" CR 0 QUIET ! RESET-SP 0 (QUIT) ; : setup-tasks ( -- ) ( must be within word definition, or an async FFI call from the interpreter will mess it up ) task-base task-ip-initial-offset + task-base ip-mem-offset + ! ( start-task is the new main task ) ['] start-task task-base task-ip-initial-offset + ! ( run interpreter in new task ) ['] ready new-task ; : (abort-task") ( c-str u -- ) TYPE end-task ; : abort-task" ( compilation: "quote" --, runtime: -- ) ['] GET-EMBEDDED-STR , EMBED-STR ['] (abort-task") , ; IMMEDIATE setup-tasks ( must be last, since it calls ABORT which empties the I/O buffers ) ================================================ FILE: kernel/forth/vdom.f ================================================ 1 QUIET ! ( utils ) : MB 1024 * 1024 * ; : 2exec ( x w1 w2 -- x1 x2 ) 2>R DUP R> EXECUTE SWAP R> EXECUTE SWAP ; : 2exec1 ( x1 x2 w -- x3 x4 ) DUP >R EXECUTE SWAP R> EXECUTE SWAP ; : exec-under ( x1 x2 w -- x3 x2 ) SWAP >R EXECUTE R> ; : compile-push-word ( "name" -- ) lit lit , ' , ; : /top compile-push-word ['] exec-under , ; IMMEDIATE : 2& compile-push-word ['] 2exec1 , ; IMMEDIATE : pop-here ( -- x ) HERE -1 CELLS + @ -1 CELLS 'HERE +! ; : & pop-here lit lit , , compile-push-word ['] 2exec , ; IMMEDIATE : emit" 34 EMIT ; : buffer ( "name" size -- ) CELLS CREATE DUP HERE + 2 CELLS + , HERE CELL+ , ALLOT DOES> 2 CELLS + ; : buf-next ( buf -- addr ) -1 CELLS + ; : buf-cell-rel ( n buf -- addr ) buf-next @ SWAP CELLS + @ ; : buf-end ( buf -- u ) -2 CELLS + @ ; : buf-reset ( buf -- ) DUP buf-next ! ; : buf-assert-space ( n-bytes buf -- ) buf-end & buf-next @ ROT + < IF abort-task" buffer out of space" THEN ; : ,buf ( x buf -- ) 1 CELLS OVER buf-assert-space TUCK buf-next @ ! buf-next 1 CELLS SWAP +! ; : buf-empty? ( buf -- flag ) DUP buf-next @ = ; : .buffer ( buf -- ) DUP buf-empty? IF DROP ." empty" EXIT THEN DUP buf-next @ SWAP DO I @ . 1 CELLS +LOOP ; : -ROT ( x1 x2 x3 -- x3 x1 x2 ) ROT ROT ; : 2@ ( addr1 addr2 -- x1 x2 ) @ SWAP @ SWAP ; : idiv /MOD SWAP DROP ; : swap-vars ( a1 a2 -- ) 2DUP 2@ >R SWAP ! R> SWAP ! ; : word-cstr ( "name" --, E: -- c-addr ) CREATE LATEST @ , DOES> @ ; : last-char ( addr u -- c ) + 1- C@ ; : trim ( addr u -- addr1 u1 ) BL SKIP BEGIN 2DUP last-char BL = OVER 0 > AND WHILE 1- REPEAT ; ( merge sort ) VARIABLE sort-cell-size : sort-cells ( n1 -- n2 ) sort-cell-size @ * ; : sort-cell+ ( n1 -- n2 ) sort-cell-size @ + ; : sort-cell-cp ( addr1 addr2 -- ) sort-cell-size @ CMOVE ; : sort-cell-aligned ( u1 -- u2 ) sort-cell-size @ /MOD SWAP 0 > IF 1+ THEN sort-cell-size @ * ; 1 31 LSHIFT 1- CONSTANT max-int : /2-aligned 1 RSHIFT sort-cell-aligned ; : cp ( to end start -- to-end ) DO I @ OVER ! CELL+ 1 CELLS +LOOP max-int OVER ! 1 CELLS sort-cell-aligned + ; : prepare ( end mid mid start -- buf-mid buf-start ) HERE -ROT cp DUP >R -ROT cp DROP R> HERE ; : split ( end start -- end mid mid start ) 2DUP SWAP OVER - /2-aligned + DUP ROT ; : merge ( end start -- ) 2DUP split prepare 2SWAP DO 2DUP 2@ < IF SWAP THEN DUP I sort-cell-cp sort-cell+ sort-cell-size @ +LOOP 2DROP ; : merge-sort ( end start -- ) 2DUP - 2 sort-cells < IF 2DROP EXIT THEN 2DUP split RECURSE RECURSE merge ; : sort ( addr n -- ) sort-cells OVER + SWAP merge-sort ; ( DOM VM ) word-cstr text-node-type word-cstr text-attr-type 1 MB buffer ops : push-op ( arg op -- ) ops ,buf ops ,buf ; : prev-op ( -- op ) ops buf-empty? IF 0 ELSE -2 ops buf-cell-rel @ THEN ; : rm-attr ( type -- ) 1 push-op ; : set-attr ( addr -- ) DUP @ text-attr-type = IF 10 push-op ELSE 2 push-op THEN ; : mk-node ( type -- ) DUP text-node-type = IF 9 push-op ELSE 3 push-op THEN ; ( note: this won't advance the position ) : skip-node ( -- ) prev-op 4 = IF 1 -1 ops buf-cell-rel +! ELSE 1 4 push-op THEN ; : rm-node ( -- ) 0 5 push-op ; : enter-node ( -- ) 0 6 push-op ; : leave-node ( -- ) prev-op 6 = IF -2 CELLS ops buf-next +! ELSE 0 7 push-op THEN ; : stop ( -- ) 0 8 push-op ; ( node & attr structures ) ( buffers for use by client code, to keep any non-static strings/event handlers/etc referenced by the vdom ) 1 MB buffer render-buf-1 1 MB buffer render-buf-2 VARIABLE render-buf-n render-buf-1 render-buf-n ! VARIABLE render-buf-c render-buf-2 render-buf-c ! : render-buf ( -- buf ) render-buf-n @ ; : ,rbuf ( x -- ) render-buf ,buf ; : to-rbuf ( addr1 u -- addr2 u ) DUP render-buf buf-assert-space render-buf buf-next @ >R TUCK R@ SWAP CMOVE DUP render-buf buf-next +! R> SWAP ; 1 MB buffer dom-buf-1 1 MB buffer dom-buf-2 VARIABLE dom-n dom-buf-1 dom-n ! VARIABLE dom-c dom-buf-2 dom-c ! : reset-ndom-bufs ( -- ) dom-n @ buf-reset render-buf buf-reset ; : swap-diff-buffers ( -- ) dom-n dom-c swap-vars render-buf-n render-buf-c swap-vars ; : ndom-here ( -- addr ) dom-n @ buf-next ; : cdom-here ( -- addr ) dom-c @ buf-next ; : ,ndom ( n -- ) dom-n @ ,buf ; 3 CELLS CONSTANT attr-size : attr-end-sentinel ( -- ) max-int ,ndom 0 ,ndom 0 ,ndom ; 3 CELLS CONSTANT node-header-size : node-start ( type -- node ) ndom-here @ SWAP ,ndom attr-size ,ndom 0 ,ndom attr-end-sentinel ; : empty-node ( -- node ) 0 node-start ; : node-type ( node -- x ) @ ; : node-attr-size-cell ( node -- addr ) 1 CELLS + ; : node-attr-size ( node -- n ) node-attr-size-cell @ ; : node-children-size-cell ( node -- addr ) 2 CELLS + ; : node-children-size ( node -- n ) node-children-size-cell @ ; : cur-node-size ( node -- node n ) ndom-here @ OVER - ; : node-end ( node -- ) empty-node DROP cur-node-size node-header-size - OVER node-attr-size - SWAP node-children-size-cell ! ; : first-child ( node-addr -- addr ) DUP node-attr-size + node-header-size + ; : next-child ( node-addr -- addr2 ) DUP DUP node-attr-size SWAP node-children-size node-header-size + + + ; : node-n-attrs ( node-addr -- n ) node-attr-size attr-size idiv 1- ; ( don't count sentinel ) : attr-start ( node-addr -- attr-addr ) node-header-size + ; : attr-len-cell ( addr1 -- addr2 ) CELL+ ; : attr-str-cell ( addr1 -- addr2 ) 2 CELLS + ; : attr-type ( addr1 -- x ) @ ; : attr-len ( addr1 -- x ) attr-len-cell @ ; : attr-str ( addr1 -- x ) attr-str-cell @ ; : inc-attr-size ( node -- node ) attr-size OVER node-attr-size-cell +! ; : !attr ( node attr-type value-addr value-len -- node ) attr-size NEGATE ndom-here +! ( remove previous sentinel ) ROT ,ndom ,ndom ,ndom attr-end-sentinel inc-attr-size ; : text ( addr n -- ) text-node-type node-start text-attr-type 2SWAP !attr node-end ; : reset-ndom ( -- ) reset-ndom-bufs empty-node DROP reset-ndom-bufs ; ( diffing ) : sort-attrs ( node-addr -- ) attr-size sort-cell-size ! attr-start & node-n-attrs sort ; ( don't sort sentinel ) : rem-cur-attr ( cur-attr1 next-attr1 -- cur-attr1 next-attr1 ) OVER rm-attr ; : add-next-attr ( cur-attr1 next-attr1 -- cur-attr1 next-attr1 ) DUP set-attr ; : attrs-more? ( addr -- flag ) @ max-int <> ; : is-attr-xt? ( addr -- flag ) attr-len max-int = ; : attr-value-diff ( cur-attr1 next-attr1 -- cur-attr1 next-attr1 ) 2DUP 2DUP 2& attr-len = -ROT 2& attr-str = AND IF EXIT THEN add-next-attr ; : inc-attr ( addr1 -- addr2 ) DUP attrs-more? IF attr-size + THEN ; : attr-diff-1 ( cur-attr1 next-attr1 -- cur-attr2 next-attr2 ) 2DUP 2& attr-type = IF attr-value-diff 2& inc-attr ELSE 2DUP 2& attr-type < IF rem-cur-attr /top inc-attr ELSE ( note: sentinel is max-int ) add-next-attr inc-attr THEN THEN ; : attr-diff ( cur-node next-node -- ) 2DUP sort-attrs sort-attrs 2& attr-start BEGIN 2DUP 2& attrs-more? OR WHILE attr-diff-1 REPEAT 2DROP ; : first-children ( cur-node next-node -- cur-node1 next-node1 ) 2& first-child ; : next-children ( cur-node next-node -- cur-node1 next-node1 ) 2& next-child ; : next-child-next next-child ; : next-child-cur /top next-child ; : is-child? ( parent-node node -- flag ) SWAP next-child < ; : end-node? ( node -- flag ) @ 0= ; : create-attrs ( node -- ) attr-start BEGIN DUP attrs-more? WHILE DUP set-attr attr-size + REPEAT DROP ; : create-tree ( node -- ) DUP node-type mk-node DUP create-attrs first-child enter-node BEGIN DUP end-node? INVERT WHILE DUP RECURSE next-child REPEAT leave-node skip-node DROP ; : node-diff ( cur-node1 next-node1 -- cur-node2 next-node2 ) 2DUP 2& end-node? AND IF leave-node skip-node next-children ELSE 2DUP 2& node-type = IF 2DUP attr-diff enter-node first-children ELSE DUP end-node? IF rm-node next-child-cur ELSE DUP create-tree next-child-next THEN THEN THEN ; : more-nodes? ( cur-node next-node -- flag ) ndom-here @ < SWAP cdom-here @ < OR ; : nodes-diff ( cur-node next-node -- ) BEGIN 2DUP more-nodes? WHILE node-diff REPEAT 2DROP ; : diff ( -- ) ops buf-reset dom-c @ dom-n @ nodes-diff stop swap-diff-buffers ; : render ( xt -- ) reset-ndom EXECUTE diff ops 0 PATCH-BODY ; : def-tag CREATE LATEST @ , DOES> @ node-start ; : closed-by CREATE DOES> DROP node-end ; : def-attr CREATE LATEST @ , DOES> @ -ROT !attr ; : def-event CREATE LATEST @ , DOES> @ SWAP -1 !attr ; : (bind) ( data xt1 -- xt2 ) render-buf buf-next @ >R SWAP lit (docol) @ ,rbuf lit lit ,rbuf ,rbuf ,rbuf lit EXIT ,rbuf R> ; : bind ( "name" -- ) compile-push-word ['] (bind) , ; IMMEDIATE : empty-attr ( -- c-addr u ) S" " ; : fmt-int ( n -- addr u ) S>D <# #S #> to-rbuf ; VARIABLE render-xt : repaint ( -- ) render-xt @ render ; : repaint-with ( "name" -- ) ' render-xt ! ; ( define a few common tags/attrs/events ) def-tag
    closed-by
    def-tag
    closed-by
    def-tag def-tag
      closed-by
    def-tag
  • closed-by
  • def-tag closed-by def-tag closed-by def-tag

    closed-by

    def-tag
    closed-by
    def-tag def-tag closed-by def-tag
    closed-by
    def-tag

    closed-by

    def-tag closed-by def-attr =class def-attr =id def-attr =for def-attr =placeholder def-attr =type def-attr =checked def-attr =value def-attr =href ( virtual attrs ) def-attr =input-value def-attr =focus def-event =onclick def-event =oninput def-event =onchange def-event =onkeydown def-event =onmouseenter def-event =onmouseleave def-event =ondblclick def-event =onblur def-event =onfocus 0 QUIET ! ================================================ FILE: kernel/forth_interpreter.py ================================================ """ Forth interepter, defined in Forth within Python. """ from asm_ops import * from memory_layout import * def forth_def(label, *code, immediate=False): """ Splits each code string into forth byte-string words, and returns a flat list of words. Also allows to define labels using '~