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. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
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 <script> tag.
See https://github.com/stefano/wasm-forth/tree/master/examples/webpack for an example usage with webpack,
and https://github.com/stefano/wasm-forth/tree/master/examples/script for an example usage as a <script> tag.
See https://github.com/stefano/wasm-forth/tree/master/examples/todomvc for an example of a full web app that interacts with the DOM.
Building from source
====================
To build the forth kernel distribution and the interactive environment (see below), you will
first need to install binaryen (https://github.com/WebAssembly/binaryen)
and ensure that `libbinaryen.so` is in the library path (LD_LIBRARY_PATH).
Then build the kernel (Python 3.6 is required):
$ python3.6 -m venv env
$ source env/bin/activate
$ python setup.py build_ext -L path/to/binaryen/lib/
$ python setup.py develop
$ python kernel
$ npm install
$ npm run build # or 'npm run watch'
Interactive Environment
=======================
This repository also contains a REPL static page (see the `repl` directory).
To serve it locally, follow the instructions above and then run the following command:
$ python kernel --demo-repl
The REPL will be served at http://localhost:8080/
================================================
FILE: examples/script/README
================================================
To run this example:
$ npm install
$ python3 -m http.server 8080
then open the browser at http://localhost:8080
================================================
FILE: examples/script/index.html
================================================
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="content"></div>
<script type="text/javascript" src="node_modules/wasm-forth/dist/wasm-forth.js"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
================================================
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 ( -- )
<header> S" header" =class
<h1> S" todos" text </h1>
<input>
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
</input>
</header> ;
: todo-item ( addr -- )
>R
<li>
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
<div> S" view" =class
<input>
S" toggle" =class
S" checkbox" =type
R@ completed IF empty-attr =checked THEN
R@ bind on-item-checked =onchange
</input>
<label> R@ bind on-item-start-editing =ondblclick
R@ todo-text to-rbuf text
</label>
R@ show-remove IF <button> S" destroy" =class R@ bind on-remove-todo =onclick </button> THEN
</div>
<input>
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
</input>
</li>
R> DROP ;
: render-todos ( -- )
count-todos 0= IF EXIT THEN
<section> S" main" =class
<input>
S" toggle-all" =id
S" toggle-all" =class
S" checkbox" =type
toggle-all-state IF S" checked" =checked THEN
['] on-toggle-all =onchange
</input>
<label> S" toggle-all" =for S" Mark all as complete" text </label>
<ul> S" todo-list" =class
['] todo-item each-todo
</ul>
</section> ;
: items-left ( n-left -- )
>R
<span>
<strong> R@ fmt-int text </strong> S" " text
R> 1 = IF S" item left" ELSE S" items left" THEN text
</span> ;
: clear-completed-btn ( -- )
<button> S" clear-completed" =class ['] clear-completed =onclick
S" Clear completed" text
</button> ;
: todo-footer ( n-completed n-left -- )
count-todos 0= IF 2DROP EXIT THEN
2>R
<footer> S" footer" =class
R> items-left
R> 0 > IF clear-completed-btn THEN
</footer> ;
: todo-app ( -- )
<section> S" todoapp" =class
todo-header
render-todos
count-completed count-left todo-footer
</section> ;
: footer-info ( -- )
<footer> S" info" =class
<p> S" Double click to edit a todo" text </p>
<p> S" Part of " text <a> S" https://github.com/stefano/wasm-forth" =href S" wasm-forth" text </a> </p>
</footer> ;
: app <div> todo-app footer-info </div> 0 first-render ! ;
repaint-with app
repaint
0 QUIET !
================================================
FILE: examples/todomvc/index.html
================================================
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TodoMVC</title>
<link rel="stylesheet" href="vendor/index.css">
<script type="text/javascript" src="node_modules/wasm-forth/dist/wasm-forth.js"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body id="body">
</body>
</html>
================================================
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
================================================
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="content"></div>
<script type="text/javascript" src="dist/index.js"></script>
</body>
</html>
================================================
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 <stddef.h>
#include <stdint.h>
{}""".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 ( "<spaces>name" -- )
HEADER lit (dovar) @ , ;
: VARIABLE ( "<spaces>name" -- )
CREATE 0 CELL+ ALLOT ;
: CONSTANT ( x "<spaces>name" -- )
HEADER lit (doconst) @ , , ;
: EMBED-STR ( "ccc<quote>" -- )
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<quote>" -- )
lit GET-EMBEDDED-STR , EMBED-STR ; IMMEDIATE
: ." ( "ccc<quote>" -- )
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
: ' ( "<spaces>name" -- xt )
BL WORD FIND 0= IF ." word to compile not found: " COUNT WRITE ABORT THEN
;
: ['] ( compilation: "<spaces>name" --, runtime: -- xt )
lit lit , ' , ; IMMEDIATE
: POSTPONE ( compilation: "<spaces>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 ( "<spaces>name" -- char )
BL WORD 1+ C@ ;
: [CHAR] ( compilation: "<spaces>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<quote>" --, 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: "<ccc>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 ( "<spaces>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 ( "<space>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 ( "<spaces>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 ( "<spaces>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 ( "<spaces>name" -- ) ' render-xt ! ;
( define a few common tags/attrs/events )
def-tag <footer> closed-by </footer>
def-tag <section> closed-by </section>
def-tag <button> closed-by </button>
def-tag <ul> closed-by </ul>
def-tag <li> closed-by </li>
def-tag <a> closed-by </a>
def-tag <span> closed-by </span>
def-tag <p> closed-by </p>
def-tag <div> closed-by </div>
def-tag <label> closed-by </label>
def-tag <input> closed-by </input>
def-tag <header> closed-by </header>
def-tag <h1> closed-by </h1>
def-tag <strong> closed-by </strong>
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 '~<label name>', which are not returned as words,
and label references using ':~<label-name>', which are replaced by an integer offset
from the current position to the label definition.
"""
# first, find labels and their offset from the start of the colon definition
jump_labels = {}
code_offset = 0
for item in code:
if isinstance(item, int):
# literals use 2 cells
code_offset += 2
continue
else:
for word in item.split(' '):
if word == '':
continue
if word.startswith('~'):
# a label definition
jump_labels[word] = code_offset
continue
elif word.startswith(':~'):
# a label reference, will use 1 cell
code_offset += 1
continue
try:
int(word)
# an int literal
code_offset += 2
except ValueError:
# it's a word reference
code_offset += 1
res = []
for item in code:
if isinstance(item, int):
res.append('lit')
res.append(item)
else:
for word in item.split(' '):
if word == '':
continue
if word.startswith('~'):
# don't add labels to ouput
continue
elif word.startswith(':~'):
jump_label = word[1:]
offset = CELL_SIZE * (jump_labels[jump_label] - len(res))
res.append(offset)
continue
try:
value = int(word)
res.append('lit')
res.append(value)
except ValueError:
res.append(word)
return label, res, immediate
WORD_NOT_FOUND_ERR = b'word not found: '
OK_MSG = b' ok\n'
FORTH_CONSTANTS = [
('IN-BUF-MAX', PAD_START - BUFFER_START),
('PAD', PAD_START),
]
FORTH_VARIABLES = [
('STATE', 0),
('SOURCE-ID', 0),
('IN-BUF', BUFFER_START),
('>IN', 0),
('IN-BUF-EOL', -1), # index of line terminator in input buffer
('IN-BUF-SIZE', 0), # number of chars in input buffer
('\'HERE', 0),
('LATEST', 0), # not standard: pointer to start of the last defined word (points to the address of the name length)
('BASE', 10),
('WORD-NOT-FOUND-ERR', WORD_NOT_FOUND_ERR),
('QUIET', 0), # not standard: tells if the interpreter prints " OK"
('OK-MSG', OK_MSG),
]
FORTH_COL_DEFS = [
forth_def(
'HERE', # ( -- a-addr )
'\'HERE @',
),
forth_def(
'ALLOT', # ( n -- )
'\'HERE +!',
),
forth_def(
'CELL+', # ( a-addr1 -- a-addr2 )
CELL_SIZE, '+',
),
forth_def(
'SOURCE', # ( -- c-addr u )
'IN-BUF @',
'IN-BUF-EOL @',
),
forth_def(
'SCAN-NEWLINE', # ( -- newline-addr u )
'IN-BUF @ IN-BUF-SIZE @', ord('\n'), 'SCAN',
),
forth_def(
'ADDR>IN-BUF-EOL!', # ( newline-addr -- )
'IN-BUF @ - IN-BUF-EOL !',
),
forth_def(
'LINE', # ( -- c-addr u )
'IN-BUF @', # ( in )
'IN-BUF-EOL @ 1+', # ( in index-after-newline )
'OVER +', # ( in new-line-addr+1 )
'SWAP IN-BUF-SIZE @ 1- IN-BUF-EOL @ - DUP >R', # ( new-line-addr+1 in n-remaining R: n-remaining )
'CMOVE', # ( R: n-remaining )
'R> IN-BUF-SIZE !', # ( )
'SCAN-NEWLINE', # ( newline-addr u )
'0 > ?branch :~REFILL', # ( newline-addr )
'ADDR>IN-BUF-EOL! branch :~FINISH',
'~REFILL',
'IN-BUF-MAX IN-BUF-SIZE @ - READ task-param IN-BUF-SIZE +!', # ( )
# even if we don't find a newline now, consider it a newline
# TODO: show an error if we still didn't find a newline, a single line must be less than 4k chars long
'SCAN-NEWLINE DROP ADDR>IN-BUF-EOL!',
'~FINISH SOURCE',
),
forth_def(
'BL', # ( -- c )
ord(b' '),
),
forth_def(
'CHAR+', # ( a-addr1 -- a-addr2 )
'1+'
),
forth_def(
'>COUNTED', # ( a-addr-src n a-addr-dst -- )
'2DUP C! CHAR+ SWAP CMOVE'
),
forth_def(
'/STRING', # ( a-addr u n -- a-addr+n u-n )
'DUP >R -', # ( a-addr u-n R: n )
'SWAP R> +', # ( u-n a-addr+n R: )
'SWAP',
),
forth_def(
'_WORD', # ( dest-addr c -- c-addr )
'>R SOURCE >IN @ /STRING R@ SKIP', # ( dest-addr c-addr-start u-start R: c )
'SWAP DUP ROT', # ( dest-addr c-addr-start c-addr-start u-start R: c )
'R> SCAN', # ( dest-addr c-addr-start c-addr-end u-end R: )
'>R OVER -', # ( dest-addr c-addr-start (c-addr-end-c - addr-start) R: u-end )
'ROT DUP >R >COUNTED R>', # ( dest-addr R: u-end )
'SOURCE R@ - + R>', # ( dest-addr c-addr-end u-end )
'1 /STRING', # ( dest-addr c-addr-end-skipped u-end-skipped )
'SOURCE ROT -', # ( dest-addr c-addr-end-skipped c-addr (u - u-end-skipped) )
'>IN ! DROP DROP', # ( dest-addr )
),
forth_def(
'WORD', # ( c -- c-addr )
'HERE SWAP _WORD',
),
forth_def(
'ALIGNED', # ( u1 -- u2 )
CELL_SIZE, 'OVER', CELL_SIZE - 1, 'AND -', CELL_SIZE - 1, 'AND +',
),
forth_def(
'COUNT', # ( c-addr1 -- c-addr2 u )
'DUP C@ SWAP 1+ SWAP',
),
forth_def(
'FIND', # ( c-addr -- c-addr 0 | xt 1 | xt -1 )
'>R', # ( R: c-addr )
'LATEST @', # ( a-addr R: c-addr )
'~LOOP DUP 0=', # ( a-addr flag R: c-addr )
'?branch :~NOT-ZERO', # ( a-addr R: c-addr )
'DROP R> 0 EXIT', # ( c-addr 0 )
'~NOT-ZERO DUP R@', # ( a-addr a-addr c-addr R: c-addr )
'EQ-COUNTED', # ( a-addr flag R: c-addr )
'?branch :~NOT-EQ', # ( a-addr R: c-addr )
'DUP DUP C@ 127 AND 1+ + ALIGNED', # ( a-addr a-addr' R: c-addr ) 127 AND to remove the smudge bit
'SWAP 1-', # ( a-addr' (a-addr - 1) R: c-addr )
'C@ 1 =', # ( a-addr' is-imm-flag R: c-addr )
'R> DROP', # ( a-addr' is-imm-flag )
'0= 1 OR EXIT', # ( a-addr' -1/1 )
'~NOT-EQ', CELL_SIZE, '- 1-', # ( (a-addr - 5) )
'@ branch :~LOOP'
),
forth_def(
'DIGIT', # ( char -- u flag )
'DUP 48 < OVER 57 > OR ?branch :~parse-dec', # jump when 48 <= c <= 57 (i.e. '0'..'9')
'DUP 65 < OVER 90 > OR ?branch :~parse-alpha-upper', # jump when 65 <= c <= 90 (i.e. 'A'..'Z')
'DUP 97 < OVER 122 > OR ?branch :~parse-alpha-lower', # jump when 97 <= c <= 122 (i.e. 'a'..'z')
'0 EXIT', # else not found
'~parse-dec 48 - branch :~done',
'~parse-alpha-upper 65 - 10 + branch :~done',
'~parse-alpha-lower 97 - 10 + branch :~done',
'~done DUP BASE @ < ?branch :~out-of-base',
'-1 EXIT',
'~out-of-base 0',
),
forth_def(
'SKIP-SIGN', # ( c-addr1 u1 -- c-addr2 u2 )
'DUP ?branch :~DONE', # end if empty
'OVER C@ 45 = ?branch :~DONE', # end if doesn't start with '-'
'1 /STRING',
'~DONE',
),
forth_def(
'NEGATIVE', # ( char -- flag )
ord('-'), '=',
),
forth_def(
'BASE*', # ( ud1 -- ud2 )
'BASE @ S>D D*',
),
forth_def(
'>NUMBER', # ( ud1 c-addr1 u1 -- ud2 c-addr2 u2 )
'~LOOP',
'DUP ?branch :~END', # if empty, go to end
'OVER C@ DIGIT ?branch :~PARTIAL', # if can't parse digit, error
'SWAP >R SWAP >R >R BASE* R> S>D D+ R> R> 1 /STRING branch :~LOOP',
'~PARTIAL DROP', # drop unparsed digit
'~END',
),
forth_def(
'COUNTED>NUMBER', # ( c-addr -- d 1 | n 2 | 0 )
'0 0 ROT', # ( 0 0 c-addr )
'COUNT OVER C@ NEGATIVE >R', # ( 0 0 c-addr1 u R: negative-flag )
'SKIP-SIGN >NUMBER', # ( ud2 c-addr2 u2 R: negative-flag )
'R> ?branch :~FINISH', # ( ud2 c-addr2 u2 )
# negative
'>R >R DNEGATE R> R>',
'~FINISH', # ( ud2 c-addr2 u2 )
'DUP ?branch :~SINGLE', # jump if no char left unconverted
'1 = ?branch :~ERROR', # jump if more than 1 char unconverted ( ud2 c-addr2 )
'DUP C@ 46 = ?branch :~ERROR', # jump if doesn't end in '.'
'DROP 1 EXIT', # double number
'~SINGLE DROP DROP D>S 2 EXIT', # single number
'~ERROR DROP DROP DROP 0', # error
),
forth_def(
',', # ( x -- )
'HERE ! 0 CELL+ ALLOT',
),
forth_def(
'C,', # ( c -- )
'HERE C! 1 ALLOT',
),
forth_def(
'(LITERAL)', # ( x -- )
'lit lit , ,', # yep, literal of itself
),
forth_def(
'INTERPRET', # ( x*j -- y*i flag )
'~I-LOOP',
INTERPRET_WORD, 'BL _WORD',
'DUP C@ ?branch :~EMPTY-WORD', # skip empty words
'FIND',
'DUP ?branch :~NOT-FOUND',
# found
'-1 = ?branch :~IMM', # immediate word
'STATE @ ?branch :~IMM', # interpretation state
# compile
', branch :~DONE',
# execute
'~IMM EXECUTE branch :~DONE',
# parse number
'~NOT-FOUND DROP DUP >R COUNTED>NUMBER',
'DUP ?branch :~NOT-NUMBER',
'R> DROP',
'STATE @ ?branch :~DONE-NUMBER', # am I interpreting?
'DUP 1 = ?branch :~SINGLE-NUMBER',
# compiling double number
'DROP SWAP (LITERAL) (LITERAL) branch :~DONE',
# compiling single number
'~SINGLE-NUMBER DROP (LITERAL) branch :~DONE',
'(LITERAL) branch :~DONE',
'~EMPTY-WORD DROP branch :~DONE',
'~DONE-NUMBER DROP',
'~DONE',
# continue interpreting if there are more words in the parse
# area
'SOURCE SWAP DROP >IN @ SWAP < INVERT ?branch :~I-LOOP',
'-1 EXIT',
'~NOT-NUMBER WORD-NOT-FOUND-ERR', len(WORD_NOT_FOUND_ERR), 'WRITE R> COUNT WRITE',
),
forth_def(
'OK', # ( -- )
'QUIET @ ?branch :~VERBOSE EXIT ~VERBOSE OK-MSG', len(OK_MSG), 'WRITE',
),
forth_def(
'RESET-SP', # ( -- )
'task-base', SP_INITIAL_OFFSET, '+ SP!',
),
forth_def(
'(QUIT)', # ( x*j flag -- y*i ) if flag true, reset I/O buffers (on error, always reset anyway)
'?branch :~IOBUF',
'~START',
'0 SOURCE-ID !',
BUFFER_START, 'IN-BUF !',
-1, 'IN-BUF-EOL !',
0, 'IN-BUF-SIZE !',
'~IOBUF',
'task-base', RS_INITIAL_OFFSET, '+ RP!',
'0 STATE !',
'~LOOP 0 >IN ! LINE DROP DROP INTERPRET',
'0= ?branch :~OK',
'RESET-SP branch :~START', # simulate abort without recursive calls
'~OK STATE @ 0= ?branch :~LOOP OK', # show prompt only if in interpretation state
'branch :~LOOP', # infinite loop
),
forth_def(
'QUIT', # ( x*j -- y*i )
'1 (QUIT)',
),
forth_def(
'ABORT', # ( x*j -- y*i )
'RESET-SP QUIT',
),
forth_def(
'HEADER', # ( -- )
'LATEST @ , 0 C, HERE LATEST ! BL WORD HERE OVER C@ 1+ DUP >R CMOVE R> 1+ ALIGNED 1- ALLOT',
),
forth_def(
':', # ( -- word-addr )
# 128 OR applies the smudge bit to keep this definition hidden
'HEADER LATEST @ DUP C@ 128 OR OVER C! lit (docol) @ , 1 STATE !',
),
forth_def(
';', # ( word-addr -- )
# 127 AND un-smudges the length
'0 STATE ! lit EXIT , DUP C@ 127 AND SWAP C!',
immediate=True,
),
]
================================================
FILE: kernel/memory_layout.py
================================================
"""
Constants that define the memory layout.
"""
from _binaryen_c import lib
CELL_SIZE = 4
CELL_TYPE = lib.BinaryenInt32()
DOUBLE_CELL_TYPE = lib.BinaryenInt64()
# Interpreter parameters
TASK_BASE_PARAM = 0
TASK_PARAM = 1
# registers, stored as local variables in the evaluation function
IP = 2 # instruction pointer
W = 3 # address of the codeword of the word being executed
SP = 4 # stack pointer, points to the top of the stack (grow downwards)
RS = 5 # return stack pointer, points to the top of the stack (grow downwards)
SCRATCH_1 = 6 # whatever
SCRATCH_2 = 7 # whatever
SCRATCH_3 = 8 # whatever
SCRATCH_DOUBLE_1 = 9 # whatever
# Memory layout:
# bytes: 0 .. 11k: main task memory area
MAIN_TASK_BASE_VALUE = 0
# bytes: 0 .. 12: main task saved registers
# register offsets, registers are saved/loaded from get_reg(TASK_BASE_PARAM) + OFFSET
IP_MEM_OFFSET = 0
SP_MEM_OFFSET = IP_MEM_OFFSET + CELL_SIZE
RS_MEM_OFFSET = SP_MEM_OFFSET + CELL_SIZE
# bytes: 12 .. 16: offset to the address of the initial forth word to run when the interpreter starts
IP_INITIAL_OFFSET = RS_MEM_OFFSET + CELL_SIZE
# bytes: 16 ... 1k: random bytes (to avoid a simple return stack
# overflow to overwrite the registers)
# bytes: 1k ... 5k: return stack
RS_INITIAL_OFFSET = 5 * 1024 + CELL_SIZE # stack empty, point one cell above start of stack
# bytes: 5k ... 6k: random bytes (to avoid a simple return stack
# underflow to overwrite the params stack)
# bytes: 6k ... 10k: params stack
SP_INITIAL_OFFSET = 10 * 1024 + CELL_SIZE # stack empty, point one cell above start of stack
# bytes: 10k ... 11k: random bytes (to avoid a simple params stack
# underflow to overwrite the buffers)
# main task memory area ends here
# bytes: 11k ... 15k: I/O buffers
BUFFER_START = 11 * 1024
# bytes: 15k ... 19k: pad (multi-purpose memory area for use by forth code)
PAD_START = 15 * 1024
# bytes: 19k ... 20k: scratch area used by the interpreter to keep
# parsed words
INTERPRET_WORD = 19 * 1024
# bytes: 20k ... : dictionary
HERE_INITIAL = 20 * 1024
================================================
FILE: kernel/vendor/binaryen-c.h
================================================
/*
* Copyright 2016 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//================
// Binaryen C API
//
// The first part of the API lets you create modules and their parts.
//
// The second part of the API lets you perform operations on modules.
//
// The third part of the API lets you provide a general control-flow
// graph (CFG) as input.
//
// The final part of the API contains miscellaneous utilities like
// debugging/tracing for the API itself.
//
// ---------------
//
// Thread safety: You can create Expressions in parallel, as they do not
// refer to global state. BinaryenAddFunction and
// BinaryenAddFunctionType are also thread-safe, which means
// that you can create functions and their contents in multiple
// threads. This is important since functions are where the
// majority of the work is done.
// Other methods - creating imports, exports, etc. - are
// not currently thread-safe (as there is typically no need
// to parallelize them).
//
//================
//
// ========== Module Creation ==========
//
// BinaryenIndex
//
// Used for internal indexes and list sizes.
typedef uint32_t BinaryenIndex;
// Core types (call to get the value of each; you can cache them, they
// never change)
typedef uint32_t BinaryenType;
BinaryenType BinaryenTypeNone(void);
BinaryenType BinaryenTypeInt32(void);
BinaryenType BinaryenTypeInt64(void);
BinaryenType BinaryenTypeFloat32(void);
BinaryenType BinaryenTypeFloat64(void);
BinaryenType BinaryenTypeVec128(void);
BinaryenType BinaryenTypeUnreachable(void);
// Not a real type. Used as the last parameter to BinaryenBlock to let
// the API figure out the type instead of providing one.
BinaryenType BinaryenTypeAuto(void);
BinaryenType BinaryenNone(void);
BinaryenType BinaryenInt32(void);
BinaryenType BinaryenInt64(void);
BinaryenType BinaryenFloat32(void);
BinaryenType BinaryenFloat64(void);
BinaryenType BinaryenUndefined(void);
// Expression ids (call to get the value of each; you can cache them)
typedef uint32_t BinaryenExpressionId;
BinaryenExpressionId BinaryenInvalidId(void);
BinaryenExpressionId BinaryenBlockId(void);
BinaryenExpressionId BinaryenIfId(void);
BinaryenExpressionId BinaryenLoopId(void);
BinaryenExpressionId BinaryenBreakId(void);
BinaryenExpressionId BinaryenSwitchId(void);
BinaryenExpressionId BinaryenCallId(void);
BinaryenExpressionId BinaryenCallIndirectId(void);
BinaryenExpressionId BinaryenGetLocalId(void);
BinaryenExpressionId BinaryenSetLocalId(void);
BinaryenExpressionId BinaryenGetGlobalId(void);
BinaryenExpressionId BinaryenSetGlobalId(void);
BinaryenExpressionId BinaryenLoadId(void);
BinaryenExpressionId BinaryenStoreId(void);
BinaryenExpressionId BinaryenConstId(void);
BinaryenExpressionId BinaryenUnaryId(void);
BinaryenExpressionId BinaryenBinaryId(void);
BinaryenExpressionId BinaryenSelectId(void);
BinaryenExpressionId BinaryenDropId(void);
BinaryenExpressionId BinaryenReturnId(void);
BinaryenExpressionId BinaryenHostId(void);
BinaryenExpressionId BinaryenNopId(void);
BinaryenExpressionId BinaryenUnreachableId(void);
BinaryenExpressionId BinaryenAtomicCmpxchgId(void);
BinaryenExpressionId BinaryenAtomicRMWId(void);
BinaryenExpressionId BinaryenAtomicWaitId(void);
BinaryenExpressionId BinaryenAtomicNotifyId(void);
BinaryenExpressionId BinaryenSIMDExtractId(void);
BinaryenExpressionId BinaryenSIMDReplaceId(void);
BinaryenExpressionId BinaryenSIMDShuffleId(void);
BinaryenExpressionId BinaryenSIMDBitselectId(void);
BinaryenExpressionId BinaryenSIMDShiftId(void);
BinaryenExpressionId BinaryenMemoryInitId(void);
BinaryenExpressionId BinaryenDataDropId(void);
BinaryenExpressionId BinaryenMemoryCopyId(void);
BinaryenExpressionId BinaryenMemoryFillId(void);
// External kinds (call to get the value of each; you can cache them)
typedef uint32_t BinaryenExternalKind;
BinaryenExternalKind BinaryenExternalFunction(void);
BinaryenExternalKind BinaryenExternalTable(void);
BinaryenExternalKind BinaryenExternalMemory(void);
BinaryenExternalKind BinaryenExternalGlobal(void);
// Modules
//
// Modules contain lists of functions, imports, exports, function types. The
// Add* methods create them on a module. The module owns them and will free their
// memory when the module is disposed of.
//
// Expressions are also allocated inside modules, and freed with the module. They
// are not created by Add* methods, since they are not added directly on the
// module, instead, they are arguments to other expressions (and then they are
// the children of that AST node), or to a function (and then they are the body
// of that function).
//
// A module can also contain a function table for indirect calls, a memory,
// and a start method.
typedef void* BinaryenModuleRef;
BinaryenModuleRef BinaryenModuleCreate(void);
void BinaryenModuleDispose(BinaryenModuleRef module);
// Function types
typedef void* BinaryenFunctionTypeRef;
// Add a new function type. This is thread-safe.
// Note: name can be NULL, in which case we auto-generate a name
BinaryenFunctionTypeRef BinaryenAddFunctionType(BinaryenModuleRef module, const char* name, BinaryenType result, BinaryenType* paramTypes, BinaryenIndex numParams);
// Removes a function type.
void BinaryenRemoveFunctionType(BinaryenModuleRef module, const char* name);
// Literals. These are passed by value.
struct BinaryenLiteral {
int32_t type;
union {
int32_t i32;
int64_t i64;
float f32;
double f64;
uint8_t v128[16];
};
};
struct BinaryenLiteral BinaryenLiteralInt32(int32_t x);
struct BinaryenLiteral BinaryenLiteralInt64(int64_t x);
struct BinaryenLiteral BinaryenLiteralFloat32(float x);
struct BinaryenLiteral BinaryenLiteralFloat64(double x);
struct BinaryenLiteral BinaryenLiteralVec128(const uint8_t x[16]);
struct BinaryenLiteral BinaryenLiteralFloat32Bits(int32_t x);
struct BinaryenLiteral BinaryenLiteralFloat64Bits(int64_t x);
// Expressions
//
// Some expressions have a BinaryenOp, which is the more
// specific operation/opcode.
//
// Some expressions have optional parameters, like Return may not
// return a value. You can supply a NULL pointer in those cases.
//
// For more information, see wasm.h
typedef int32_t BinaryenOp;
BinaryenOp BinaryenClzInt32(void);
BinaryenOp BinaryenCtzInt32(void);
BinaryenOp BinaryenPopcntInt32(void);
BinaryenOp BinaryenNegFloat32(void);
BinaryenOp BinaryenAbsFloat32(void);
BinaryenOp BinaryenCeilFloat32(void);
BinaryenOp BinaryenFloorFloat32(void);
BinaryenOp BinaryenTruncFloat32(void);
BinaryenOp BinaryenNearestFloat32(void);
BinaryenOp BinaryenSqrtFloat32(void);
BinaryenOp BinaryenEqZInt32(void);
BinaryenOp BinaryenClzInt64(void);
BinaryenOp BinaryenCtzInt64(void);
BinaryenOp BinaryenPopcntInt64(void);
BinaryenOp BinaryenNegFloat64(void);
BinaryenOp BinaryenAbsFloat64(void);
BinaryenOp BinaryenCeilFloat64(void);
BinaryenOp BinaryenFloorFloat64(void);
BinaryenOp BinaryenTruncFloat64(void);
BinaryenOp BinaryenNearestFloat64(void);
BinaryenOp BinaryenSqrtFloat64(void);
BinaryenOp BinaryenEqZInt64(void);
BinaryenOp BinaryenExtendSInt32(void);
BinaryenOp BinaryenExtendUInt32(void);
BinaryenOp BinaryenWrapInt64(void);
BinaryenOp BinaryenTruncSFloat32ToInt32(void);
BinaryenOp BinaryenTruncSFloat32ToInt64(void);
BinaryenOp BinaryenTruncUFloat32ToInt32(void);
BinaryenOp BinaryenTruncUFloat32ToInt64(void);
BinaryenOp BinaryenTruncSFloat64ToInt32(void);
BinaryenOp BinaryenTruncSFloat64ToInt64(void);
BinaryenOp BinaryenTruncUFloat64ToInt32(void);
BinaryenOp BinaryenTruncUFloat64ToInt64(void);
BinaryenOp BinaryenReinterpretFloat32(void);
BinaryenOp BinaryenReinterpretFloat64(void);
BinaryenOp BinaryenConvertSInt32ToFloat32(void);
BinaryenOp BinaryenConvertSInt32ToFloat64(void);
BinaryenOp BinaryenConvertUInt32ToFloat32(void);
BinaryenOp BinaryenConvertUInt32ToFloat64(void);
BinaryenOp BinaryenConvertSInt64ToFloat32(void);
BinaryenOp BinaryenConvertSInt64ToFloat64(void);
BinaryenOp BinaryenConvertUInt64ToFloat32(void);
BinaryenOp BinaryenConvertUInt64ToFloat64(void);
BinaryenOp BinaryenPromoteFloat32(void);
BinaryenOp BinaryenDemoteFloat64(void);
BinaryenOp BinaryenReinterpretInt32(void);
BinaryenOp BinaryenReinterpretInt64(void);
BinaryenOp BinaryenExtendS8Int32(void);
BinaryenOp BinaryenExtendS16Int32(void);
BinaryenOp BinaryenExtendS8Int64(void);
BinaryenOp BinaryenExtendS16Int64(void);
BinaryenOp BinaryenExtendS32Int64(void);
BinaryenOp BinaryenAddInt32(void);
BinaryenOp BinaryenSubInt32(void);
BinaryenOp BinaryenMulInt32(void);
BinaryenOp BinaryenDivSInt32(void);
BinaryenOp BinaryenDivUInt32(void);
BinaryenOp BinaryenRemSInt32(void);
BinaryenOp BinaryenRemUInt32(void);
BinaryenOp BinaryenAndInt32(void);
BinaryenOp BinaryenOrInt32(void);
BinaryenOp BinaryenXorInt32(void);
BinaryenOp BinaryenShlInt32(void);
BinaryenOp BinaryenShrUInt32(void);
BinaryenOp BinaryenShrSInt32(void);
BinaryenOp BinaryenRotLInt32(void);
BinaryenOp BinaryenRotRInt32(void);
BinaryenOp BinaryenEqInt32(void);
BinaryenOp BinaryenNeInt32(void);
BinaryenOp BinaryenLtSInt32(void);
BinaryenOp BinaryenLtUInt32(void);
BinaryenOp BinaryenLeSInt32(void);
BinaryenOp BinaryenLeUInt32(void);
BinaryenOp BinaryenGtSInt32(void);
BinaryenOp BinaryenGtUInt32(void);
BinaryenOp BinaryenGeSInt32(void);
BinaryenOp BinaryenGeUInt32(void);
BinaryenOp BinaryenAddInt64(void);
BinaryenOp BinaryenSubInt64(void);
BinaryenOp BinaryenMulInt64(void);
BinaryenOp BinaryenDivSInt64(void);
BinaryenOp BinaryenDivUInt64(void);
BinaryenOp BinaryenRemSInt64(void);
BinaryenOp BinaryenRemUInt64(void);
BinaryenOp BinaryenAndInt64(void);
BinaryenOp BinaryenOrInt64(void);
BinaryenOp BinaryenXorInt64(void);
BinaryenOp BinaryenShlInt64(void);
BinaryenOp BinaryenShrUInt64(void);
BinaryenOp BinaryenShrSInt64(void);
BinaryenOp BinaryenRotLInt64(void);
BinaryenOp BinaryenRotRInt64(void);
BinaryenOp BinaryenEqInt64(void);
BinaryenOp BinaryenNeInt64(void);
BinaryenOp BinaryenLtSInt64(void);
BinaryenOp BinaryenLtUInt64(void);
BinaryenOp BinaryenLeSInt64(void);
BinaryenOp BinaryenLeUInt64(void);
BinaryenOp BinaryenGtSInt64(void);
BinaryenOp BinaryenGtUInt64(void);
BinaryenOp BinaryenGeSInt64(void);
BinaryenOp BinaryenGeUInt64(void);
BinaryenOp BinaryenAddFloat32(void);
BinaryenOp BinaryenSubFloat32(void);
BinaryenOp BinaryenMulFloat32(void);
BinaryenOp BinaryenDivFloat32(void);
BinaryenOp BinaryenCopySignFloat32(void);
BinaryenOp BinaryenMinFloat32(void);
BinaryenOp BinaryenMaxFloat32(void);
BinaryenOp BinaryenEqFloat32(void);
BinaryenOp BinaryenNeFloat32(void);
BinaryenOp BinaryenLtFloat32(void);
BinaryenOp BinaryenLeFloat32(void);
BinaryenOp BinaryenGtFloat32(void);
BinaryenOp BinaryenGeFloat32(void);
BinaryenOp BinaryenAddFloat64(void);
BinaryenOp BinaryenSubFloat64(void);
BinaryenOp BinaryenMulFloat64(void);
BinaryenOp BinaryenDivFloat64(void);
BinaryenOp BinaryenCopySignFloat64(void);
BinaryenOp BinaryenMinFloat64(void);
BinaryenOp BinaryenMaxFloat64(void);
BinaryenOp BinaryenEqFloat64(void);
BinaryenOp BinaryenNeFloat64(void);
BinaryenOp BinaryenLtFloat64(void);
BinaryenOp BinaryenLeFloat64(void);
BinaryenOp BinaryenGtFloat64(void);
BinaryenOp BinaryenGeFloat64(void);
BinaryenOp BinaryenCurrentMemory(void);
BinaryenOp BinaryenGrowMemory(void);
BinaryenOp BinaryenAtomicRMWAdd(void);
BinaryenOp BinaryenAtomicRMWSub(void);
BinaryenOp BinaryenAtomicRMWAnd(void);
BinaryenOp BinaryenAtomicRMWOr(void);
BinaryenOp BinaryenAtomicRMWXor(void);
BinaryenOp BinaryenAtomicRMWXchg(void);
BinaryenOp BinaryenTruncSatSFloat32ToInt32(void);
BinaryenOp BinaryenTruncSatSFloat32ToInt64(void);
BinaryenOp BinaryenTruncSatUFloat32ToInt32(void);
BinaryenOp BinaryenTruncSatUFloat32ToInt64(void);
BinaryenOp BinaryenTruncSatSFloat64ToInt32(void);
BinaryenOp BinaryenTruncSatSFloat64ToInt64(void);
BinaryenOp BinaryenTruncSatUFloat64ToInt32(void);
BinaryenOp BinaryenTruncSatUFloat64ToInt64(void);
BinaryenOp BinaryenSplatVecI8x16(void);
BinaryenOp BinaryenExtractLaneSVecI8x16(void);
BinaryenOp BinaryenExtractLaneUVecI8x16(void);
BinaryenOp BinaryenReplaceLaneVecI8x16(void);
BinaryenOp BinaryenSplatVecI16x8(void);
BinaryenOp BinaryenExtractLaneSVecI16x8(void);
BinaryenOp BinaryenExtractLaneUVecI16x8(void);
BinaryenOp BinaryenReplaceLaneVecI16x8(void);
BinaryenOp BinaryenSplatVecI32x4(void);
BinaryenOp BinaryenExtractLaneVecI32x4(void);
BinaryenOp BinaryenReplaceLaneVecI32x4(void);
BinaryenOp BinaryenSplatVecI64x2(void);
BinaryenOp BinaryenExtractLaneVecI64x2(void);
BinaryenOp BinaryenReplaceLaneVecI64x2(void);
BinaryenOp BinaryenSplatVecF32x4(void);
BinaryenOp BinaryenExtractLaneVecF32x4(void);
BinaryenOp BinaryenReplaceLaneVecF32x4(void);
BinaryenOp BinaryenSplatVecF64x2(void);
BinaryenOp BinaryenExtractLaneVecF64x2(void);
BinaryenOp BinaryenReplaceLaneVecF64x2(void);
BinaryenOp BinaryenEqVecI8x16(void);
BinaryenOp BinaryenNeVecI8x16(void);
BinaryenOp BinaryenLtSVecI8x16(void);
BinaryenOp BinaryenLtUVecI8x16(void);
BinaryenOp BinaryenGtSVecI8x16(void);
BinaryenOp BinaryenGtUVecI8x16(void);
BinaryenOp BinaryenLeSVecI8x16(void);
BinaryenOp BinaryenLeUVecI8x16(void);
BinaryenOp BinaryenGeSVecI8x16(void);
BinaryenOp BinaryenGeUVecI8x16(void);
BinaryenOp BinaryenEqVecI16x8(void);
BinaryenOp BinaryenNeVecI16x8(void);
BinaryenOp BinaryenLtSVecI16x8(void);
BinaryenOp BinaryenLtUVecI16x8(void);
BinaryenOp BinaryenGtSVecI16x8(void);
BinaryenOp BinaryenGtUVecI16x8(void);
BinaryenOp BinaryenLeSVecI16x8(void);
BinaryenOp BinaryenLeUVecI16x8(void);
BinaryenOp BinaryenGeSVecI16x8(void);
BinaryenOp BinaryenGeUVecI16x8(void);
BinaryenOp BinaryenEqVecI32x4(void);
BinaryenOp BinaryenNeVecI32x4(void);
BinaryenOp BinaryenLtSVecI32x4(void);
BinaryenOp BinaryenLtUVecI32x4(void);
BinaryenOp BinaryenGtSVecI32x4(void);
BinaryenOp BinaryenGtUVecI32x4(void);
BinaryenOp BinaryenLeSVecI32x4(void);
BinaryenOp BinaryenLeUVecI32x4(void);
BinaryenOp BinaryenGeSVecI32x4(void);
BinaryenOp BinaryenGeUVecI32x4(void);
BinaryenOp BinaryenEqVecF32x4(void);
BinaryenOp BinaryenNeVecF32x4(void);
BinaryenOp BinaryenLtVecF32x4(void);
BinaryenOp BinaryenGtVecF32x4(void);
BinaryenOp BinaryenLeVecF32x4(void);
BinaryenOp BinaryenGeVecF32x4(void);
BinaryenOp BinaryenEqVecF64x2(void);
BinaryenOp BinaryenNeVecF64x2(void);
BinaryenOp BinaryenLtVecF64x2(void);
BinaryenOp BinaryenGtVecF64x2(void);
BinaryenOp BinaryenLeVecF64x2(void);
BinaryenOp BinaryenGeVecF64x2(void);
BinaryenOp BinaryenNotVec128(void);
BinaryenOp BinaryenAndVec128(void);
BinaryenOp BinaryenOrVec128(void);
BinaryenOp BinaryenXorVec128(void);
BinaryenOp BinaryenNegVecI8x16(void);
BinaryenOp BinaryenAnyTrueVecI8x16(void);
BinaryenOp BinaryenAllTrueVecI8x16(void);
BinaryenOp BinaryenShlVecI8x16(void);
BinaryenOp BinaryenShrSVecI8x16(void);
BinaryenOp BinaryenShrUVecI8x16(void);
BinaryenOp BinaryenAddVecI8x16(void);
BinaryenOp BinaryenAddSatSVecI8x16(void);
BinaryenOp BinaryenAddSatUVecI8x16(void);
BinaryenOp BinaryenSubVecI8x16(void);
BinaryenOp BinaryenSubSatSVecI8x16(void);
BinaryenOp BinaryenSubSatUVecI8x16(void);
BinaryenOp BinaryenMulVecI8x16(void);
BinaryenOp BinaryenNegVecI16x8(void);
BinaryenOp BinaryenAnyTrueVecI16x8(void);
BinaryenOp BinaryenAllTrueVecI16x8(void);
BinaryenOp BinaryenShlVecI16x8(void);
BinaryenOp BinaryenShrSVecI16x8(void);
BinaryenOp BinaryenShrUVecI16x8(void);
BinaryenOp BinaryenAddVecI16x8(void);
BinaryenOp BinaryenAddSatSVecI16x8(void);
BinaryenOp BinaryenAddSatUVecI16x8(void);
BinaryenOp BinaryenSubVecI16x8(void);
BinaryenOp BinaryenSubSatSVecI16x8(void);
BinaryenOp BinaryenSubSatUVecI16x8(void);
BinaryenOp BinaryenMulVecI16x8(void);
BinaryenOp BinaryenNegVecI32x4(void);
BinaryenOp BinaryenAnyTrueVecI32x4(void);
BinaryenOp BinaryenAllTrueVecI32x4(void);
BinaryenOp BinaryenShlVecI32x4(void);
BinaryenOp BinaryenShrSVecI32x4(void);
BinaryenOp BinaryenShrUVecI32x4(void);
BinaryenOp BinaryenAddVecI32x4(void);
BinaryenOp BinaryenSubVecI32x4(void);
BinaryenOp BinaryenMulVecI32x4(void);
BinaryenOp BinaryenNegVecI64x2(void);
BinaryenOp BinaryenAnyTrueVecI64x2(void);
BinaryenOp BinaryenAllTrueVecI64x2(void);
BinaryenOp BinaryenShlVecI64x2(void);
BinaryenOp BinaryenShrSVecI64x2(void);
BinaryenOp BinaryenShrUVecI64x2(void);
BinaryenOp BinaryenAddVecI64x2(void);
BinaryenOp BinaryenSubVecI64x2(void);
BinaryenOp BinaryenAbsVecF32x4(void);
BinaryenOp BinaryenNegVecF32x4(void);
BinaryenOp BinaryenSqrtVecF32x4(void);
BinaryenOp BinaryenAddVecF32x4(void);
BinaryenOp BinaryenSubVecF32x4(void);
BinaryenOp BinaryenMulVecF32x4(void);
BinaryenOp BinaryenDivVecF32x4(void);
BinaryenOp BinaryenMinVecF32x4(void);
BinaryenOp BinaryenMaxVecF32x4(void);
BinaryenOp BinaryenAbsVecF64x2(void);
BinaryenOp BinaryenNegVecF64x2(void);
BinaryenOp BinaryenSqrtVecF64x2(void);
BinaryenOp BinaryenAddVecF64x2(void);
BinaryenOp BinaryenSubVecF64x2(void);
BinaryenOp BinaryenMulVecF64x2(void);
BinaryenOp BinaryenDivVecF64x2(void);
BinaryenOp BinaryenMinVecF64x2(void);
BinaryenOp BinaryenMaxVecF64x2(void);
BinaryenOp BinaryenTruncSatSVecF32x4ToVecI32x4(void);
BinaryenOp BinaryenTruncSatUVecF32x4ToVecI32x4(void);
BinaryenOp BinaryenTruncSatSVecF64x2ToVecI64x2(void);
BinaryenOp BinaryenTruncSatUVecF64x2ToVecI64x2(void);
BinaryenOp BinaryenConvertSVecI32x4ToVecF32x4(void);
BinaryenOp BinaryenConvertUVecI32x4ToVecF32x4(void);
BinaryenOp BinaryenConvertSVecI64x2ToVecF64x2(void);
BinaryenOp BinaryenConvertUVecI64x2ToVecF64x2(void);
typedef void* BinaryenExpressionRef;
// Block: name can be NULL. Specifying BinaryenUndefined() as the 'type'
// parameter indicates that the block's type shall be figured out
// automatically instead of explicitly providing it. This conforms
// to the behavior before the 'type' parameter has been introduced.
BinaryenExpressionRef BinaryenBlock(BinaryenModuleRef module, const char* name, BinaryenExpressionRef* children, BinaryenIndex numChildren, BinaryenType type);
// If: ifFalse can be NULL
BinaryenExpressionRef BinaryenIf(BinaryenModuleRef module, BinaryenExpressionRef condition, BinaryenExpressionRef ifTrue, BinaryenExpressionRef ifFalse);
BinaryenExpressionRef BinaryenLoop(BinaryenModuleRef module, const char* in, BinaryenExpressionRef body);
// Break: value and condition can be NULL
BinaryenExpressionRef BinaryenBreak(BinaryenModuleRef module, const char* name, BinaryenExpressionRef condition, BinaryenExpressionRef value);
// Switch: value can be NULL
BinaryenExpressionRef BinaryenSwitch(BinaryenModuleRef module, const char** names, BinaryenIndex numNames, const char* defaultName, BinaryenExpressionRef condition, BinaryenExpressionRef value);
// Call: Note the 'returnType' parameter. You must declare the
// type returned by the function being called, as that
// function might not have been created yet, so we don't
// know what it is.
BinaryenExpressionRef BinaryenCall(BinaryenModuleRef module, const char* target, BinaryenExpressionRef* operands, BinaryenIndex numOperands, BinaryenType returnType);
BinaryenExpressionRef BinaryenCallIndirect(BinaryenModuleRef module, BinaryenExpressionRef target, BinaryenExpressionRef* operands, BinaryenIndex numOperands, const char* type);
// GetLocal: Note the 'type' parameter. It might seem redundant, since the
// local at that index must have a type. However, this API lets you
// build code "top-down": create a node, then its parents, and so
// on, and finally create the function at the end. (Note that in fact
// you do not mention a function when creating ExpressionRefs, only
// a module.) And since GetLocal is a leaf node, we need to be told
// its type. (Other nodes detect their type either from their
// type or their opcode, or failing that, their children. But
// GetLocal has no children, it is where a "stream" of type info
// begins.)
// Note also that the index of a local can refer to a param or
// a var, that is, either a parameter to the function or a variable
// declared when you call BinaryenAddFunction. See BinaryenAddFunction
// for more details.
BinaryenExpressionRef BinaryenGetLocal(BinaryenModuleRef module, BinaryenIndex index, BinaryenType type);
BinaryenExpressionRef BinaryenSetLocal(BinaryenModuleRef module, BinaryenIndex index, BinaryenExpressionRef value);
BinaryenExpressionRef BinaryenTeeLocal(BinaryenModuleRef module, BinaryenIndex index, BinaryenExpressionRef value);
BinaryenExpressionRef BinaryenGetGlobal(BinaryenModuleRef module, const char* name, BinaryenType type);
BinaryenExpressionRef BinaryenSetGlobal(BinaryenModuleRef module, const char* name, BinaryenExpressionRef value);
// Load: align can be 0, in which case it will be the natural alignment (equal to bytes)
BinaryenExpressionRef BinaryenLoad(BinaryenModuleRef module, uint32_t bytes, int8_t signed_, uint32_t offset, uint32_t align, BinaryenType type, BinaryenExpressionRef ptr);
// Store: align can be 0, in which case it will be the natural alignment (equal to bytes)
BinaryenExpressionRef BinaryenStore(BinaryenModuleRef module, uint32_t bytes, uint32_t offset, uint32_t align, BinaryenExpressionRef ptr, BinaryenExpressionRef value, BinaryenType type);
BinaryenExpressionRef BinaryenConst(BinaryenModuleRef module, struct BinaryenLiteral value);
BinaryenExpressionRef BinaryenUnary(BinaryenModuleRef module, BinaryenOp op, BinaryenExpressionRef value);
BinaryenExpressionRef BinaryenBinary(BinaryenModuleRef module, BinaryenOp op, BinaryenExpressionRef left, BinaryenExpressionRef right);
BinaryenExpressionRef BinaryenSelect(BinaryenModuleRef module, BinaryenExpressionRef condition, BinaryenExpressionRef ifTrue, BinaryenExpressionRef ifFalse);
BinaryenExpressionRef BinaryenDrop(BinaryenModuleRef module, BinaryenExpressionRef value);
// Return: value can be NULL
BinaryenExpressionRef BinaryenReturn(BinaryenModuleRef module, BinaryenExpressionRef value);
// Host: name may be NULL
BinaryenExpressionRef BinaryenHost(BinaryenModuleRef module, BinaryenOp op, const char* name, BinaryenExpressionRef* operands, BinaryenIndex numOperands);
BinaryenExpressionRef BinaryenNop(BinaryenModuleRef module);
BinaryenExpressionRef BinaryenUnreachable(BinaryenModuleRef module);
BinaryenExpressionRef BinaryenAtomicLoad(BinaryenModuleRef module, uint32_t bytes, uint32_t offset, BinaryenType type, BinaryenExpressionRef ptr);
BinaryenExpressionRef BinaryenAtomicStore(BinaryenModuleRef module, uint32_t bytes, uint32_t offset, BinaryenExpressionRef ptr, BinaryenExpressionRef value, BinaryenType type);
BinaryenExpressionRef BinaryenAtomicRMW(BinaryenModuleRef module, BinaryenOp op, BinaryenIndex bytes, BinaryenIndex offset, BinaryenExpressionRef ptr, BinaryenExpressionRef value, BinaryenType type);
BinaryenExpressionRef BinaryenAtomicCmpxchg(BinaryenModuleRef module, BinaryenIndex bytes, BinaryenIndex offset, BinaryenExpressionRef ptr, BinaryenExpressionRef expected, BinaryenExpressionRef replacement, BinaryenType type);
BinaryenExpressionRef BinaryenAtomicWait(BinaryenModuleRef module, BinaryenExpressionRef ptr, BinaryenExpressionRef expected, BinaryenExpressionRef timeout, BinaryenType type);
BinaryenExpressionRef BinaryenAtomicNotify(BinaryenModuleRef module, BinaryenExpressionRef ptr, BinaryenExpressionRef notifyCount);
BinaryenExpressionRef BinaryenSIMDExtract(BinaryenModuleRef module, BinaryenOp op, BinaryenExpressionRef vec, uint8_t index);
BinaryenExpressionRef BinaryenSIMDReplace(BinaryenModuleRef module, BinaryenOp op, BinaryenExpressionRef vec, uint8_t index, BinaryenExpressionRef value);
BinaryenExpressionRef BinaryenSIMDShuffle(BinaryenModuleRef module, BinaryenExpressionRef left, BinaryenExpressionRef right, const uint8_t mask[16]);
BinaryenExpressionRef BinaryenSIMDBitselect(BinaryenModuleRef module, BinaryenExpressionRef left, BinaryenExpressionRef right, BinaryenExpressionRef cond);
BinaryenExpressionRef BinaryenSIMDShift(BinaryenModuleRef module, BinaryenOp op, BinaryenExpressionRef vec, BinaryenExpressionRef shift);
BinaryenExpressionRef BinaryenMemoryInit(BinaryenModuleRef module, uint32_t segment, BinaryenExpressionRef dest, BinaryenExpressionRef offset, BinaryenExpressionRef size);
BinaryenExpressionRef BinaryenDataDrop(BinaryenModuleRef module, uint32_t segment);
BinaryenExpressionRef BinaryenMemoryCopy(BinaryenModuleRef module, BinaryenExpressionRef dest, BinaryenExpressionRef source, BinaryenExpressionRef size);
BinaryenExpressionRef BinaryenMemoryFill(BinaryenModuleRef module, BinaryenExpressionRef dest, BinaryenExpressionRef value, BinaryenExpressionRef size);
BinaryenExpressionId BinaryenExpressionGetId(BinaryenExpressionRef expr);
BinaryenType BinaryenExpressionGetType(BinaryenExpressionRef expr);
void BinaryenExpressionPrint(BinaryenExpressionRef expr);
const char* BinaryenBlockGetName(BinaryenExpressionRef expr);
BinaryenIndex BinaryenBlockGetNumChildren(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenBlockGetChild(BinaryenExpressionRef expr, BinaryenIndex index);
BinaryenExpressionRef BinaryenIfGetCondition(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenIfGetIfTrue(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenIfGetIfFalse(BinaryenExpressionRef expr);
const char* BinaryenLoopGetName(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenLoopGetBody(BinaryenExpressionRef expr);
const char* BinaryenBreakGetName(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenBreakGetCondition(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenBreakGetValue(BinaryenExpressionRef expr);
BinaryenIndex BinaryenSwitchGetNumNames(BinaryenExpressionRef expr);
const char* BinaryenSwitchGetName(BinaryenExpressionRef expr, BinaryenIndex index);
const char* BinaryenSwitchGetDefaultName(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSwitchGetCondition(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSwitchGetValue(BinaryenExpressionRef expr);
const char* BinaryenCallGetTarget(BinaryenExpressionRef expr);
BinaryenIndex BinaryenCallGetNumOperands(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenCallGetOperand(BinaryenExpressionRef expr, BinaryenIndex index);
BinaryenExpressionRef BinaryenCallIndirectGetTarget(BinaryenExpressionRef expr);
BinaryenIndex BinaryenCallIndirectGetNumOperands(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenCallIndirectGetOperand(BinaryenExpressionRef expr, BinaryenIndex index);
BinaryenIndex BinaryenGetLocalGetIndex(BinaryenExpressionRef expr);
int BinaryenSetLocalIsTee(BinaryenExpressionRef expr);
BinaryenIndex BinaryenSetLocalGetIndex(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSetLocalGetValue(BinaryenExpressionRef expr);
const char* BinaryenGetGlobalGetName(BinaryenExpressionRef expr);
const char* BinaryenSetGlobalGetName(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSetGlobalGetValue(BinaryenExpressionRef expr);
BinaryenOp BinaryenHostGetOp(BinaryenExpressionRef expr);
const char* BinaryenHostGetNameOperand(BinaryenExpressionRef expr);
BinaryenIndex BinaryenHostGetNumOperands(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenHostGetOperand(BinaryenExpressionRef expr, BinaryenIndex index);
int BinaryenLoadIsAtomic(BinaryenExpressionRef expr);
int BinaryenLoadIsSigned(BinaryenExpressionRef expr);
uint32_t BinaryenLoadGetOffset(BinaryenExpressionRef expr);
uint32_t BinaryenLoadGetBytes(BinaryenExpressionRef expr);
uint32_t BinaryenLoadGetAlign(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenLoadGetPtr(BinaryenExpressionRef expr);
int BinaryenStoreIsAtomic(BinaryenExpressionRef expr);
uint32_t BinaryenStoreGetBytes(BinaryenExpressionRef expr);
uint32_t BinaryenStoreGetOffset(BinaryenExpressionRef expr);
uint32_t BinaryenStoreGetAlign(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenStoreGetPtr(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenStoreGetValue(BinaryenExpressionRef expr);
int32_t BinaryenConstGetValueI32(BinaryenExpressionRef expr);
int64_t BinaryenConstGetValueI64(BinaryenExpressionRef expr);
int32_t BinaryenConstGetValueI64Low(BinaryenExpressionRef expr);
int32_t BinaryenConstGetValueI64High(BinaryenExpressionRef expr);
float BinaryenConstGetValueF32(BinaryenExpressionRef expr);
double BinaryenConstGetValueF64(BinaryenExpressionRef expr);
void BinaryenConstGetValueV128(BinaryenExpressionRef expr, uint8_t* out);
BinaryenOp BinaryenUnaryGetOp(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenUnaryGetValue(BinaryenExpressionRef expr);
BinaryenOp BinaryenBinaryGetOp(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenBinaryGetLeft(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenBinaryGetRight(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSelectGetIfTrue(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSelectGetIfFalse(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSelectGetCondition(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenDropGetValue(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenReturnGetValue(BinaryenExpressionRef expr);
BinaryenOp BinaryenAtomicRMWGetOp(BinaryenExpressionRef expr);
uint32_t BinaryenAtomicRMWGetBytes(BinaryenExpressionRef expr);
uint32_t BinaryenAtomicRMWGetOffset(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenAtomicRMWGetPtr(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenAtomicRMWGetValue(BinaryenExpressionRef expr);
uint32_t BinaryenAtomicCmpxchgGetBytes(BinaryenExpressionRef expr);
uint32_t BinaryenAtomicCmpxchgGetOffset(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenAtomicCmpxchgGetPtr(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenAtomicCmpxchgGetExpected(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenAtomicCmpxchgGetReplacement(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenAtomicWaitGetPtr(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenAtomicWaitGetExpected(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenAtomicWaitGetTimeout(BinaryenExpressionRef expr);
BinaryenType BinaryenAtomicWaitGetExpectedType(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenAtomicNotifyGetPtr(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenAtomicNotifyGetNotifyCount(BinaryenExpressionRef expr);
BinaryenOp BinaryenSIMDExtractGetOp(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSIMDExtractGetVec(BinaryenExpressionRef expr);
uint8_t BinaryenSIMDExtractGetIndex(BinaryenExpressionRef expr);
BinaryenOp BinaryenSIMDReplaceGetOp(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSIMDReplaceGetVec(BinaryenExpressionRef expr);
uint8_t BinaryenSIMDReplaceGetIndex(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSIMDReplaceGetValue(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSIMDShuffleGetLeft(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSIMDShuffleGetRight(BinaryenExpressionRef expr);
void BinaryenSIMDShuffleGetMask(BinaryenExpressionRef expr, uint8_t *mask);
BinaryenExpressionRef BinaryenSIMDBitselectGetLeft(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSIMDBitselectGetRight(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSIMDBitselectGetCond(BinaryenExpressionRef expr);
BinaryenOp BinaryenSIMDShiftGetOp(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSIMDShiftGetVec(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenSIMDShiftGetShift(BinaryenExpressionRef expr);
uint32_t BinaryenMemoryInitGetSegment(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenMemoryInitGetDest(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenMemoryInitGetOffset(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenMemoryInitGetSize(BinaryenExpressionRef expr);
uint32_t BinaryenDataDropGetSegment(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenMemoryCopyGetDest(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenMemoryCopyGetSource(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenMemoryCopyGetSize(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenMemoryFillGetDest(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenMemoryFillGetValue(BinaryenExpressionRef expr);
BinaryenExpressionRef BinaryenMemoryFillGetSize(BinaryenExpressionRef expr);
// Functions
typedef void* BinaryenFunctionRef;
// Adds a function to the module. This is thread-safe.
// @varTypes: the types of variables. In WebAssembly, vars share
// an index space with params. In other words, params come from
// the function type, and vars are provided in this call, and
// together they are all the locals. The order is first params
// and then vars, so if you have one param it will be at index
// 0 (and written $0), and if you also have 2 vars they will be
// at indexes 1 and 2, etc., that is, they share an index space.
BinaryenFunctionRef BinaryenAddFunction(BinaryenModuleRef module, const char* name, BinaryenFunctionTypeRef type, BinaryenType* varTypes, BinaryenIndex numVarTypes, BinaryenExpressionRef body);
// Gets a function reference by name.
BinaryenFunctionRef BinaryenGetFunction(BinaryenModuleRef module, const char* name);
// Removes a function by name.
void BinaryenRemoveFunction(BinaryenModuleRef module, const char* name);
// Imports
void BinaryenAddFunctionImport(BinaryenModuleRef module, const char* internalName, const char* externalModuleName, const char* externalBaseName, BinaryenFunctionTypeRef functionType);
void BinaryenAddTableImport(BinaryenModuleRef module, const char* internalName, const char* externalModuleName, const char* externalBaseName);
void BinaryenAddMemoryImport(BinaryenModuleRef module, const char* internalName, const char* externalModuleName, const char* externalBaseName, uint8_t shared);
void BinaryenAddGlobalImport(BinaryenModuleRef module, const char* internalName, const char* externalModuleName, const char* externalBaseName, BinaryenType globalType);
// Exports
typedef void* BinaryenExportRef;
BinaryenExportRef BinaryenAddExport(BinaryenModuleRef module, const char* internalName, const char* externalName);
BinaryenExportRef BinaryenAddFunctionExport(BinaryenModuleRef module, const char* internalName, const char* externalName);
BinaryenExportRef BinaryenAddTableExport(BinaryenModuleRef module, const char* internalName, const char* externalName);
BinaryenExportRef BinaryenAddMemoryExport(BinaryenModuleRef module, const char* internalName, const char* externalName);
BinaryenExportRef BinaryenAddGlobalExport(BinaryenModuleRef module, const char* internalName, const char* externalName);
void BinaryenRemoveExport(BinaryenModuleRef module, const char* externalName);
// Globals
typedef void* BinaryenGlobalRef;
BinaryenGlobalRef BinaryenAddGlobal(BinaryenModuleRef module, const char* name, BinaryenType type, int8_t mutable_, BinaryenExpressionRef init);
void BinaryenRemoveGlobal(BinaryenModuleRef module, const char* name);
// Function table. One per module
void BinaryenSetFunctionTable(BinaryenModuleRef module, BinaryenIndex initial, BinaryenIndex maximum, const char** funcNames, BinaryenIndex numFuncNames);
// Memory. One per module
// Each segment has data in segments, a start offset in segmentOffsets, and a size in segmentSizes.
// exportName can be NULL
void BinaryenSetMemory(BinaryenModuleRef module, BinaryenIndex initial, BinaryenIndex maximum, const char* exportName, const char** segments, int8_t* segmentPassive, BinaryenExpressionRef* segmentOffsets, BinaryenIndex* segmentSizes, BinaryenIndex numSegments, uint8_t shared);
// Start function. One per module
void BinaryenSetStart(BinaryenModuleRef module, BinaryenFunctionRef start);
//
// ========== Module Operations ==========
//
// Parse a module in s-expression text format
BinaryenModuleRef BinaryenModuleParse(const char* text);
// Print a module to stdout in s-expression text format. Useful for debugging.
void BinaryenModulePrint(BinaryenModuleRef module);
// Print a module to stdout in asm.js syntax.
void BinaryenModulePrintAsmjs(BinaryenModuleRef module);
// Validate a module, showing errors on problems.
// @return 0 if an error occurred, 1 if validated succesfully
int BinaryenModuleValidate(BinaryenModuleRef module);
// Runs the standard optimization passes on the module. Uses the currently set
// global optimize and shrink level.
void BinaryenModuleOptimize(BinaryenModuleRef module);
// Gets the currently set optimize level. Applies to all modules, globally.
// 0, 1, 2 correspond to -O0, -O1, -O2 (default), etc.
int BinaryenGetOptimizeLevel(void);
// Sets the optimization level to use. Applies to all modules, globally.
// 0, 1, 2 correspond to -O0, -O1, -O2 (default), etc.
void BinaryenSetOptimizeLevel(int level);
// Gets the currently set shrink level. Applies to all modules, globally.
// 0, 1, 2 correspond to -O0, -Os (default), -Oz.
int BinaryenGetShrinkLevel(void);
// Sets the shrink level to use. Applies to all modules, globally.
// 0, 1, 2 correspond to -O0, -Os (default), -Oz.
void BinaryenSetShrinkLevel(int level);
// Gets whether generating debug information is currently enabled or not.
// Applies to all modules, globally.
int BinaryenGetDebugInfo(void);
// Enables or disables debug information in emitted binaries.
// Applies to all modules, globally.
void BinaryenSetDebugInfo(int on);
// Runs the specified passes on the module. Uses the currently set global
// optimize and shrink level.
void BinaryenModuleRunPasses(BinaryenModuleRef module, const char** passes, BinaryenIndex numPasses);
// Auto-generate drop() operations where needed. This lets you generate code without
// worrying about where they are needed. (It is more efficient to do it yourself,
// but simpler to use autodrop).
void BinaryenModuleAutoDrop(BinaryenModuleRef module);
// Serialize a module into binary form. Uses the currently set global debugInfo option.
// @return how many bytes were written. This will be less than or equal to outputSize
size_t BinaryenModuleWrite(BinaryenModuleRef module, char* output, size_t outputSize);
typedef struct BinaryenBufferSizes {
size_t outputBytes;
size_t sourceMapBytes;
} BinaryenBufferSizes;
// Serialize a module into binary form including its source map. Uses the currently set
// global debugInfo option.
// @returns how many bytes were written. This will be less than or equal to outputSize
BinaryenBufferSizes BinaryenModuleWriteWithSourceMap(BinaryenModuleRef module, const char* url, char* output, size_t outputSize, char* sourceMap, size_t sourceMapSize);
// Result structure of BinaryenModuleAllocateAndWrite. Contained buffers have been allocated
// using malloc() and the user is expected to free() them manually once not needed anymore.
typedef struct BinaryenModuleAllocateAndWriteResult {
void* binary;
size_t binaryBytes;
char* sourceMap;
} BinaryenModuleAllocateAndWriteResult;
// Serializes a module into binary form, optionally including its source map if
// sourceMapUrl has been specified. Uses the currently set global debugInfo option.
// Differs from BinaryenModuleWrite in that it implicitly allocates appropriate buffers
// using malloc(), and expects the user to free() them manually once not needed anymore.
BinaryenModuleAllocateAndWriteResult BinaryenModuleAllocateAndWrite(BinaryenModuleRef module, const char* sourceMapUrl);
// Deserialize a module from binary form.
BinaryenModuleRef BinaryenModuleRead(char* input, size_t inputSize);
// Execute a module in the Binaryen interpreter. This will create an instance of
// the module, run it in the interpreter - which means running the start method -
// and then destroying the instance.
void BinaryenModuleInterpret(BinaryenModuleRef module);
// Adds a debug info file name to the module and returns its index.
BinaryenIndex BinaryenModuleAddDebugInfoFileName(BinaryenModuleRef module, const char* filename);
// Gets the name of the debug info file at the specified index. Returns `NULL` if it
// does not exist.
const char* BinaryenModuleGetDebugInfoFileName(BinaryenModuleRef module, BinaryenIndex index);
//
// ======== FunctionType Operations ========
//
// Gets the name of the specified `FunctionType`.
const char* BinaryenFunctionTypeGetName(BinaryenFunctionTypeRef ftype);
// Gets the number of parameters of the specified `FunctionType`.
BinaryenIndex BinaryenFunctionTypeGetNumParams(BinaryenFunctionTypeRef ftype);
// Gets the type of the parameter at the specified index of the specified `FunctionType`.
BinaryenType BinaryenFunctionTypeGetParam(BinaryenFunctionTypeRef ftype, BinaryenIndex index);
// Gets the result type of the specified `FunctionType`.
BinaryenType BinaryenFunctionTypeGetResult(BinaryenFunctionTypeRef ftype);
//
// ========== Function Operations ==========
//
// Gets the name of the specified `Function`.
const char* BinaryenFunctionGetName(BinaryenFunctionRef func);
// Gets the name of the `FunctionType` associated with the specified `Function`. May be `NULL` if the signature is implicit.
const char* BinaryenFunctionGetType(BinaryenFunctionRef func);
// Gets the number of parameters of the specified `Function`.
BinaryenIndex BinaryenFunctionGetNumParams(BinaryenFunctionRef func);
// Gets the type of the parameter at the specified index of the specified `Function`.
BinaryenType BinaryenFunctionGetParam(BinaryenFunctionRef func, BinaryenIndex index);
// Gets the result type of the specified `Function`.
BinaryenType BinaryenFunctionGetResult(BinaryenFunctionRef func);
// Gets the number of additional locals within the specified `Function`.
BinaryenIndex BinaryenFunctionGetNumVars(BinaryenFunctionRef func);
// Gets the type of the additional local at the specified index within the specified `Function`.
BinaryenType BinaryenFunctionGetVar(BinaryenFunctionRef func, BinaryenIndex index);
// Gets the body of the specified `Function`.
BinaryenExpressionRef BinaryenFunctionGetBody(BinaryenFunctionRef func);
// Runs the standard optimization passes on the function. Uses the currently set
// global optimize and shrink level.
void BinaryenFunctionOptimize(BinaryenFunctionRef func, BinaryenModuleRef module);
// Runs the specified passes on the function. Uses the currently set global
// optimize and shrink level.
void BinaryenFunctionRunPasses(BinaryenFunctionRef func, BinaryenModuleRef module, const char** passes, BinaryenIndex numPasses);
// Sets the debug location of the specified `Expression` within the specified `Function`.
void BinaryenFunctionSetDebugLocation(BinaryenFunctionRef func, BinaryenExpressionRef expr, BinaryenIndex fileIndex, BinaryenIndex lineNumber, BinaryenIndex columnNumber);
//
// ========== Import Operations ==========
//
// Gets the external module name of the specified import.
const char* BinaryenFunctionImportGetModule(BinaryenFunctionRef import);
// const char* BinaryeGlobalImportGetModule(BinaryenGlobalRef import);
// Gets the external base name of the specified import.
const char* BinaryenFunctionImportGetBase(BinaryenFunctionRef import);
const char* BinaryenGlobalImportGetBase(BinaryenGlobalRef import);
//
// ========== Export Operations ==========
//
// Gets the external kind of the specified export.
BinaryenExternalKind BinaryenExportGetKind(BinaryenExportRef export_);
// Gets the external name of the specified export.
const char* BinaryenExportGetName(BinaryenExportRef export_);
// Gets the internal name of the specified export.
const char* BinaryenExportGetValue(BinaryenExportRef export_);
//
// ========== CFG / Relooper ==========
//
// General usage is (1) create a relooper, (2) create blocks, (3) add
// branches between them, (4) render the output.
//
// For more details, see src/cfg/Relooper.h and
// https://github.com/WebAssembly/binaryen/wiki/Compiling-to-WebAssembly-with-Binaryen#cfg-api
typedef void* RelooperRef;
typedef void* RelooperBlockRef;
// Create a relooper instance
RelooperRef RelooperCreate(BinaryenModuleRef module);
// Create a basic block that ends with nothing, or with some simple branching
RelooperBlockRef RelooperAddBlock(RelooperRef relooper, BinaryenExpressionRef code);
// Create a branch to another basic block
// The branch can have code on it, that is executed as the branch happens. this is useful for phis. otherwise, code can be NULL
void RelooperAddBranch(RelooperBlockRef from, RelooperBlockRef to, BinaryenExpressionRef condition, BinaryenExpressionRef code);
// Create a basic block that ends a switch on a condition
RelooperBlockRef RelooperAddBlockWithSwitch(RelooperRef relooper, BinaryenExpressionRef code, BinaryenExpressionRef condition);
// Create a switch-style branch to another basic block. The block's switch table will have these indexes going to that target
void RelooperAddBranchForSwitch(RelooperBlockRef from, RelooperBlockRef to, BinaryenIndex* indexes, BinaryenIndex numIndexes, BinaryenExpressionRef code);
// Generate structed wasm control flow from the CFG of blocks and branches that were created
// on this relooper instance. This returns the rendered output, and also disposes of the
// relooper and its blocks and branches, as they are no longer needed.
// @param labelHelper To render irreducible control flow, we may need a helper variable to
// guide us to the right target label. This value should be an index of
// an i32 local variable that is free for us to use.
BinaryenExpressionRef RelooperRenderAndDispose(RelooperRef relooper, RelooperBlockRef entry, BinaryenIndex labelHelper);
//
// ========= Other APIs =========
//
// Sets whether API tracing is on or off. It is off by default. When on, each call
// to an API method will print out C code equivalent to it, which is useful for
// auto-generating standalone testcases from projects using the API.
// When calling this to turn on tracing, the prelude of the full program is printed,
// and when calling it to turn it off, the ending of the program is printed, giving
// you the full compilable testcase.
// TODO: compile-time option to enable/disable this feature entirely at build time?
void BinaryenSetAPITracing(int on);
//
// ========= Utilities =========
//
// Note that this function has been added because there is no better alternative
// currently and is scheduled for removal once there is one. It takes the same set
// of parameters as BinaryenAddFunctionType but instead of adding a new function
// signature, it returns a pointer to the existing signature or NULL if there is no
// such signature yet.
BinaryenFunctionTypeRef BinaryenGetFunctionTypeBySignature(BinaryenModuleRef module, BinaryenType result, BinaryenType* paramTypes, BinaryenIndex numParams);
================================================
FILE: package.json
================================================
{
"name": "wasm-forth",
"version": "2.0.0",
"description": "A Forth implementation compiling to WebAssembly.",
"main": "dist/wasm-forth.js",
"module": "src/index.js",
"files": [
"dist/wasm-forth.js",
"dist/kernel.wasm",
"dist/core.f",
"dist/vdom.f",
"README.md",
"LICENSE"
],
"scripts": {
"build": "webpack",
"watch": "webpack --watch",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"forth",
"wasm",
"WebAssembly",
"compiler",
"interpreter"
],
"author": "Stefano Dissegna",
"license": "GPL-3.0",
"devDependencies": {
"webpack": "^3.10.0"
}
}
================================================
FILE: repl/index.html
================================================
<!DOCTYPE html>
<html>
<head>
<title>WASM Forth - Interactive Environment</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="repl.css"/>
</head>
<body>
<h1>WASM Forth - Interactive Environment</h1>
<div id="loading">Loading...</div>
<pre id="output"></pre>
<div id="input" style="display: none">
<textarea id="source-input" type="text" placeholder="Evaluate code" tabindex="0"></textarea>
<button id="enter">Enter</button>
</div>
<script type="text/javascript" src="dist/repl.js"></script>
</body>
</html>
================================================
FILE: repl/repl.css
================================================
html, body {
height: 100%;
}
html {
background-color: #002b36;
color: #93a1a1;
font-family: monospace;
}
body {
margin: 0 auto;
padding: 2em;
max-width: 70ch;
font-size: 14px;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
h1 {
font-size: 1.5em;
}
#output {
white-space: pre-wrap;
overflow-y: auto;
}
#input {
display: flex;
flex-shrink: 0;
}
#source-input {
flex: 1;
margin-right: 1em;
border: none;
caret-color: #859900;
border-bottom: 1px solid #859900;
padding-bottom: 0.5em;
color: #93a1a1;
font-family: monospace;
background-color: #002b36;
outline: none;
resize: none;
height: 1.25em;
}
button {
background: none;
border: none;
color: #859900;
cursor: pointer;
padding: 0;
}
button::-moz-focus-inner, input::-moz-focus-inner {
border: 0;
padding: 0;
}
button:active {
padding: 0;
color: #2aa198;
}
================================================
FILE: repl/repl.js
================================================
import * as WasmForth from '../src/index';
let loadingElement = document.getElementById('loading');
let inputElement = document.getElementById('input');
let sourceInputElement = document.getElementById('source-input');
let enterElement = document.getElementById('enter');
let outputElement = document.getElementById('output');
function onInputLine(evt) {
if (evt.keyCode === 13) {
evt.preventDefault();
processLine();
}
}
function processLine() {
let line = sourceInputElement.value;
outputElement.innerText += line + ' ';
sourceInputElement.value = '';
WasmForth.source(line + '\n');
sourceInputElement.focus();
}
WasmForth.boot({
wasmURL: 'dist/kernel.wasm',
sources: ['dist/core.f', 'dist/vdom.f'],
write: (text) => {
outputElement.innerText += text;
outputElement.scrollTop = outputElement.scrollHeight;
}
}).then(() => {
sourceInputElement.addEventListener('keypress', onInputLine);
enterElement.addEventListener('click', processLine);
loadingElement.parentElement.removeChild(loadingElement);
inputElement.removeAttribute('style');
sourceInputElement.focus();
});
================================================
FILE: setup.py
================================================
from os import path
from setuptools import setup, find_packages
def get_long_description():
readme_path = path.join(path.abspath(path.dirname(__file__)), 'README.md')
with open(readme_path, encoding='utf-8') as readme:
return readme.read()
setup(
name='wasm-forth',
version='1.0.0',
author='Stefano Dissegna',
description='A Forth implementation compiling to WebAssembly.',
long_description=get_long_description(),
url='https://github.com/stefano/wasm-forth/',
license='GPLv3',
keywords='forth wasm WebAssembly compiler interpreter',
classifiers=[
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Interpreters',
],
packages=find_packages(),
setup_requires=['cffi>=1.0.0'],
cffi_modules=['kernel/build_binaryen_ext.py:ffibuilder'],
install_requires=['cffi>=1.0.0'],
)
================================================
FILE: src/index.js
================================================
let interpreter;
let memBytes;
let memCells;
let inputBuffer = '';
let onSourceAvailable;
function decodeString(memoryIndex, nBytes) {
let chars = [];
for (let i = 0; i < nBytes; i++) {
chars.push(String.fromCharCode(memBytes[memoryIndex + i]));
}
return chars.join('');
}
function encodeString(target, value, limit) {
limit = Math.min(limit, value.length);
for (let i = 0; i < limit; i++) {
memBytes[target + i] = value.charCodeAt(i);
}
return limit;
}
function makeFFI(config) {
let currentEvent = null;
let io = {
read: (token, memoryIndex, nBytes) => {
let continuation = () => {
let limit = encodeString(memoryIndex, inputBuffer, nBytes);
inputBuffer = inputBuffer.substr(limit);
onSourceAvailable = undefined;
interpreter.exports.exec(token, limit);
};
if (inputBuffer.length > 0) {
setTimeout(continuation, 0);
} else {
onSourceAvailable = continuation;
}
},
patchBody: (memoryIndex, unused) => {
let parent = document.querySelector('#body'), nodeIdx = 0;
let parentStack = [], idxStack = [];
loop:
for (let idx = memoryIndex / 4;; idx += 2) {
switch (memCells[idx]) {
case 1: {
// remove attr
let structAddr = memCells[idx+1];
let nameAddr = memCells[structAddr/4];
let name = decodeString(nameAddr+2, memBytes[nameAddr]-1);
let valueNBytes = memCells[structAddr/4+1];
if (valueNBytes === 0xFFFFFFFF) {
parent.childNodes[nodeIdx][name] = undefined;
} else if (name === 'focus') {
// nothing
} else if (name === 'input-value') {
parent.childNodes[nodeIdx].value = '';
} else if (name === 'checked') {
parent.childNodes[nodeIdx].checked = false;
} else {
parent.childNodes[nodeIdx].removeAttribute(name);
}
break;
}
case 2: {
// set attr
let structAddr = memCells[idx+1];
let nameAddr = memCells[structAddr/4];
let name = decodeString(nameAddr+2, memBytes[nameAddr]-1);
let valueNBytes = memCells[structAddr/4+1];
let valueAddr = memCells[structAddr/4+2];
if (valueNBytes === 0xFFFFFFFF) {
parent.childNodes[nodeIdx][name] = (evt) => {
currentEvent = evt;
interpreter.exports.exec(0, valueAddr);
};
} else if (name === 'focus') {
parent.childNodes[nodeIdx].focus();
} else if (name === 'input-value') {
parent.childNodes[nodeIdx].value = decodeString(valueAddr, valueNBytes);
} else if (name === 'checked') {
parent.childNodes[nodeIdx].checked = true;
} else {
parent.childNodes[nodeIdx].setAttribute(name, decodeString(valueAddr, valueNBytes));
}
break;
}
case 3: // create
let addr = memCells[idx+1];
let nBytes = memBytes[addr];
let name = decodeString(addr+2, nBytes-2); // skip starting '<' and ending '>'
let elem = document.createElement(name);
parent.insertBefore(elem, parent.childNodes[nodeIdx]);
break;
case 4: // skip
nodeIdx += memCells[idx+1];
break;
case 5: // remove
parent.removeChild(parent.childNodes[nodeIdx]);
break;
case 6: // enter
parentStack.push(parent);
idxStack.push(nodeIdx);
parent = parent.childNodes[nodeIdx];
nodeIdx = 0;
break;
case 7: // leave
parent = parentStack.pop();
nodeIdx = idxStack.pop();
break;
case 8: // stop
break loop;
case 9: // create text node
parent.insertBefore(document.createTextNode(''), parent.childNodes[nodeIdx]);
break;
case 10: // set text content
let textNBytes = memCells[memCells[idx+1]/4+1];
let textAddr = memCells[memCells[idx+1]/4+2];
parent.childNodes[nodeIdx].textContent = decodeString(textAddr, textNBytes);
break;
default:
console.log('unknown opcode:' + memCells[idx]);
break loop;
}
}
},
write: (memoryIndex, nBytes) => {
try {
config.write(decodeString(memoryIndex, nBytes));
} catch (e) {
console.error(e);
}
},
evtAttr: (memoryIndex, nBytes, targetAddr, limit) => {
let path = decodeString(memoryIndex, nBytes).split('.');
let value = currentEvent;
for (let item of path) {
value = value[item];
}
if (value === true || value === false) {
return value;
}
if (typeof value === 'number') {
return value;
}
return encodeString(targetAddr, value, limit);
}
};
return { io };
}
/**
* Provide Forth source code to be executed.
*
* @param {string} text
*/
export function source(text) {
inputBuffer += text;
if (onSourceAvailable) {
onSourceAvailable();
}
}
/**
* Boots the forth system.
*
* @param config
* {
* wasm: string; // URL to dist/kernel.wasm
* sources: string[]; // URLs to forth source code (should at least include dist/core.f)
* write: (text) => void; // a function called with the output emitted by Forth code
* }
*
* @returns {Promise} resolved when the system is ready to process forth code.
*/
export function boot(config) {
return fetch(config.wasmURL).then(
res => res.arrayBuffer()
).then(
bytes => WebAssembly.instantiate(bytes, makeFFI(config))
).then(compiled => {
interpreter = compiled.instance;
memBytes = new Uint8Array(interpreter.exports.mem.buffer);
memCells = new Uint32Array(interpreter.exports.mem.buffer);
window.memBytes = memBytes;
window.memCells = memCells;
interpreter.exports.exec(0, 0);
}).then(
() => Promise.all(config.sources.map(url => fetch(url)))
).then(
results => Promise.all(results.map(res => res.text()))
).then(
texts => texts.forEach(source)
);
}
================================================
FILE: webpack.config.js
================================================
let path = require('path');
let wasmForth = {
entry: {
main: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'wasm-forth.js',
library: 'WasmForth',
libraryTarget: 'umd'
}
};
let repl = {
entry: {
main: './repl/repl.js'
},
output: {
path: path.resolve(__dirname, 'repl/dist'),
filename: 'repl.js'
}
};
module.exports = [wasmForth, repl];
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
SYMBOL INDEX (122 symbols across 9 files)
FILE: kernel/asm_ops.py
function block (line 14) | def block(*instrs, label=None):
function _flatten (line 33) | def _flatten(lst, res=None):
function loop (line 46) | def loop(label, expr):
function switch (line 54) | def switch(labels, default_label, cond_expr):
function jmp (line 63) | def jmp(label, cond_expr=ffi.NULL):
function call_iiin (line 70) | def call_iiin(label, expr1, expr2, expr3):
function call_iin (line 78) | def call_iin(label, expr1, expr2):
function call_iiii_i (line 86) | def call_iiii_i(label, expr1, expr2, expr3, expr4):
function get_reg (line 97) | def get_reg(reg):
function get_double_reg (line 101) | def get_double_reg(reg):
function set_reg (line 105) | def set_reg(reg, expr):
function load_cell (line 109) | def load_cell(addr_expr, cells_offset=0):
function load_double_cell (line 121) | def load_double_cell(addr_expr, cells_offset=0):
function store_cell (line 133) | def store_cell(addr_expr, value_expr, cells_offset=0):
function store_double_cell (line 145) | def store_double_cell(addr_expr, value_expr, cells_offset=0):
function load_byte (line 157) | def load_byte(addr_expr):
function store_byte (line 169) | def store_byte(addr_expr, value_expr):
function invert_double_cell (line 184) | def invert_double_cell(expr):
function peek (line 193) | def peek(stack_reg, cells_offset):
function peek_double (line 197) | def peek_double(stack_reg, cells_offset):
function put (line 201) | def put(stack_reg, cells_offset, expr):
function put_double (line 205) | def put_double(stack_reg, cells_offset, expr):
function inc (line 209) | def inc(reg, n_cells):
function drop (line 213) | def drop(reg, n_cells):
function push (line 217) | def push(stack_reg, expr):
function add_cell_size (line 228) | def add_cell_size(reg, n_cells):
function cmp_neg (line 238) | def cmp_neg(cmp_op):
function cmp_neg_zero (line 256) | def cmp_neg_zero(cmp_op):
function op_on_tos (line 273) | def op_on_tos(op, rhs_expr, stack_reg=SP):
function bin_op (line 281) | def bin_op(op):
function bin_op_32_32_64 (line 288) | def bin_op_32_32_64(op):
function bin_op_64_32_64 (line 292) | def bin_op_64_32_64(op):
function const_cell (line 302) | def const_cell(value):
function const_double_cell (line 306) | def const_double_cell(value):
function u_32_to_64 (line 313) | def u_32_to_64(expr):
function u_64_to_32 (line 317) | def u_64_to_32(expr):
function s_32_to_64 (line 321) | def s_32_to_64(expr):
function s_64_to_32 (line 325) | def s_64_to_32(expr):
function eqz (line 332) | def eqz(expr):
function eq (line 336) | def eq(expr1, expr2):
function ne (line 340) | def ne(expr1, expr2):
function ge_s (line 344) | def ge_s(expr1, expr2):
function ge_u (line 348) | def ge_u(expr1, expr2):
function le_s (line 352) | def le_s(expr1, expr2):
function le_u (line 356) | def le_u(expr1, expr2):
function l_s (line 360) | def l_s(expr1, expr2):
function add (line 367) | def add(expr1, expr2):
function add_64_32 (line 371) | def add_64_32(expr1, expr2):
function add_64 (line 375) | def add_64(expr1, expr2):
function sub (line 379) | def sub(expr1, expr2):
function mul (line 383) | def mul(expr1, expr2):
function mul_32_32_64 (line 387) | def mul_32_32_64(expr1, expr2):
function mul_64 (line 391) | def mul_64(expr1, expr2):
function umul_32_32_64 (line 395) | def umul_32_32_64(expr1, expr2):
function div (line 399) | def div(expr1, expr2):
function rem (line 403) | def rem(expr1, expr2):
function div_64_32_32 (line 407) | def div_64_32_32(expr1, expr2):
function udiv_64_32_32 (line 411) | def udiv_64_32_32(expr1, expr2):
function udiv_64_32_64 (line 415) | def udiv_64_32_64(expr1, expr2):
function rem_64_32_32 (line 419) | def rem_64_32_32(expr1, expr2):
function urem_64_32_32 (line 423) | def urem_64_32_32(expr1, expr2):
function ls (line 427) | def ls(expr1, expr2):
function a_rs (line 431) | def a_rs(expr1, expr2):
function l_rs (line 435) | def l_rs(expr1, expr2):
function bit_and (line 439) | def bit_and(expr1, expr2):
function bit_or (line 443) | def bit_or(expr1, expr2):
function bit_xor (line 447) | def bit_xor(expr1, expr2):
FILE: kernel/assembler.py
function build_kernel (line 10) | def build_kernel(output_file):
function assemble (line 21) | def assemble():
function add_imports (line 32) | def add_imports():
function add_exports (line 56) | def add_exports():
function add_initial_memory (line 64) | def add_initial_memory():
function add_interpreter (line 110) | def add_interpreter():
function assemble_interpreter (line 138) | def assemble_interpreter():
function add_code_primitives_dict_entries (line 163) | def add_code_primitives_dict_entries(dictionary_bytes, forth_words_addrs...
function add_forth_constants_dict_entries (line 172) | def add_forth_constants_dict_entries(dictionary_bytes, forth_words_addrs...
function add_forth_variables_dict_entries (line 184) | def add_forth_variables_dict_entries(dictionary_bytes, forth_words_addrs...
function replace_forth_variable_value (line 200) | def replace_forth_variable_value(dictionary_bytes, forth_words_addrs, la...
function add_forth_col_defs_dict_entries (line 204) | def add_forth_col_defs_dict_entries(dictionary_bytes, forth_words_addrs,...
function find_code_primitive_addr (line 225) | def find_code_primitive_addr(primitive_label):
function append_dict_header (line 233) | def append_dict_header(dictionary_bytes, forth_words_addrs, last_name_ad...
function append_aligned_bytes (line 262) | def append_aligned_bytes(dictionary_bytes, value):
function append_padding (line 267) | def append_padding(dictionary_bytes):
function append_cell (line 275) | def append_cell(dictionary_bytes, value):
function replace_cell (line 283) | def replace_cell(dictionary_bytes, offset, value):
function print_debug (line 291) | def print_debug():
function save_kernel (line 295) | def save_kernel(output_file):
function destroy (line 313) | def destroy():
FILE: kernel/binaryen_module.py
function retain_gc (line 7) | def retain_gc(*items):
function release_gc (line 11) | def release_gc():
FILE: kernel/code_words.py
function store_registers (line 8) | def store_registers():
function load_registers (line 23) | def load_registers():
function _register_mem_addr (line 36) | def _register_mem_addr(offset):
function _branch (line 40) | def _branch():
function _call_iin_sync (line 61) | def _call_iin_sync(name):
function _call_iiii_i_sync (line 68) | def _call_iiii_i_sync(name):
function _call_iiin_async (line 75) | def _call_iiin_async(name):
FILE: kernel/forth_interpreter.py
function forth_def (line 9) | def forth_def(label, *code, immediate=False):
FILE: kernel/vendor/binaryen-c.h
type BinaryenIndex (line 52) | typedef uint32_t BinaryenIndex;
type BinaryenType (line 57) | typedef uint32_t BinaryenType;
type BinaryenExpressionId (line 79) | typedef uint32_t BinaryenExpressionId;
type BinaryenExternalKind (line 120) | typedef uint32_t BinaryenExternalKind;
type BinaryenLiteral (line 159) | struct BinaryenLiteral {
type BinaryenLiteral (line 170) | struct BinaryenLiteral
type BinaryenLiteral (line 171) | struct BinaryenLiteral
type BinaryenLiteral (line 172) | struct BinaryenLiteral
type BinaryenLiteral (line 173) | struct BinaryenLiteral
type BinaryenLiteral (line 174) | struct BinaryenLiteral
type BinaryenLiteral (line 175) | struct BinaryenLiteral
type BinaryenLiteral (line 176) | struct BinaryenLiteral
type BinaryenOp (line 188) | typedef int32_t BinaryenOp;
type BinaryenLiteral (line 513) | struct BinaryenLiteral
type BinaryenBufferSizes (line 799) | typedef struct BinaryenBufferSizes {
type BinaryenModuleAllocateAndWriteResult (line 811) | typedef struct BinaryenModuleAllocateAndWriteResult {
FILE: repl/repl.js
function onInputLine (line 9) | function onInputLine(evt) {
function processLine (line 16) | function processLine() {
FILE: setup.py
function get_long_description (line 6) | def get_long_description():
FILE: src/index.js
function decodeString (line 7) | function decodeString(memoryIndex, nBytes) {
function encodeString (line 17) | function encodeString(target, value, limit) {
function makeFFI (line 25) | function makeFFI(config) {
function source (line 164) | function source(text) {
function boot (line 184) | function boot(config) {
Condensed preview — 37 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (198K chars).
[
{
"path": ".gitignore",
"chars": 100,
"preview": "dist\nnode_modules\n/wasm_forth.egg-info\n/_binaryen_c.abi3.so\n/.eggs\n/.vscode\n/build\n/env\n__pycache__\n"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 3235,
"preview": "WASM Forth\n==========\n\nA Forth implementation compiling to WebAssembly.\n\nIt includes an ANS Forth standard environment c"
},
{
"path": "examples/script/README",
"chars": 122,
"preview": "To run this example:\n\n $ npm install\n $ python3 -m http.server 8080\n\nthen open the browser at http://localhost:808"
},
{
"path": "examples/script/index.html",
"chars": 304,
"preview": "<!DOCTYPE html>\n\n<html>\n <head>\n <title>Example</title>\n </head>\n <body>\n <div id=\"content\"></div"
},
{
"path": "examples/script/index.js",
"chars": 346,
"preview": "WasmForth.boot({\n wasmURL: 'node_modules/wasm-forth/dist/kernel.wasm',\n sources: ['node_modules/wasm-forth/dist/co"
},
{
"path": "examples/script/package.json",
"chars": 181,
"preview": "{\n \"name\": \"example\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"author\": \"\",\n \"license\": \"GP"
},
{
"path": "examples/todomvc/README",
"chars": 122,
"preview": "To run this example:\n\n $ npm install\n $ python3 -m http.server 8080\n\nthen open the browser at http://localhost:808"
},
{
"path": "examples/todomvc/index.f",
"chars": 6796,
"preview": "1 QUIET !\n\nVARIABLE first-render TRUE first-render !\n\n( each todo has: 4 byte length [excluding flags], 1 byte completed"
},
{
"path": "examples/todomvc/index.html",
"chars": 415,
"preview": "<!DOCTYPE html>\n\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initi"
},
{
"path": "examples/todomvc/index.js",
"chars": 217,
"preview": "WasmForth.boot({\n wasmURL: 'node_modules/wasm-forth/dist/kernel.wasm',\n sources: ['node_modules/wasm-forth/dist/co"
},
{
"path": "examples/todomvc/package.json",
"chars": 181,
"preview": "{\n \"name\": \"example\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"author\": \"\",\n \"license\": \"GP"
},
{
"path": "examples/todomvc/vendor/index.css",
"chars": 7039,
"preview": "/*\n * Copied from https://github.com/tastejs/todomvc/\n */\n\nhtml,\nbody {\n\tmargin: 0;\n\tpadding: 0;\n}\n\nbutton {\n\tmargin: 0;"
},
{
"path": "examples/webpack/README",
"chars": 142,
"preview": "To run this example:\n\n $ npm install\n $ npm run build\n $ python3 -m http.server 8080\n\nthen open the browser at "
},
{
"path": "examples/webpack/index.html",
"chars": 211,
"preview": "<!DOCTYPE html>\n\n<html>\n <head>\n <title>Example</title>\n </head>\n <body>\n <div id=\"content\"></div"
},
{
"path": "examples/webpack/index.js",
"chars": 427,
"preview": "import * as WasmForth from 'wasm-forth';\nimport wasmURL from 'wasm-forth/dist/kernel.wasm';\nimport coreURL from 'wasm-fo"
},
{
"path": "examples/webpack/package.json",
"chars": 306,
"preview": "{\n \"name\": \"example\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"author\": \"\",\n \"license\": \"GP"
},
{
"path": "examples/webpack/webpack.config.js",
"chars": 378,
"preview": "let path = require('path');\n\nmodule.exports = {\n entry: {\n main: './index.js'\n },\n output: {\n pat"
},
{
"path": "kernel/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "kernel/__main__.py",
"chars": 1302,
"preview": "import shutil\nimport sys\nimport os\n\nimport assembler\n\n\nBASE_PATH = os.path.abspath(os.path.dirname(__file__))\nDIST_PATH "
},
{
"path": "kernel/asm_ops.py",
"chars": 10048,
"preview": "\"\"\"\nUtilities to make it easier to write webassembly opcodes.\n\"\"\"\n\nfrom _binaryen_c import ffi, lib\n\nfrom binaryen_modul"
},
{
"path": "kernel/assembler.py",
"chars": 11298,
"preview": "from _binaryen_c import ffi, lib\n\nfrom asm_ops import *\nfrom binaryen_module import module, retain_gc, release_gc\nfrom c"
},
{
"path": "kernel/binaryen_module.py",
"chars": 181,
"preview": "from _binaryen_c import lib\n\n_no_gc = []\nmodule = lib.BinaryenModuleCreate()\n\n\ndef retain_gc(*items):\n _no_gc.extend("
},
{
"path": "kernel/build_binaryen_ext.py",
"chars": 562,
"preview": "from os import path\n\nfrom cffi import FFI\n\n\nffibuilder = FFI()\n\nbase_path = path.abspath(path.dirname(__file__))\nheader_"
},
{
"path": "kernel/code_words.py",
"chars": 19227,
"preview": "\"\"\"\nBasic Forth words defined directly in WebAssembly.\n\"\"\"\n\nfrom asm_ops import *\n\n\ndef store_registers():\n \"\"\"\n S"
},
{
"path": "kernel/forth/core.f",
"chars": 8678,
"preview": "1 QUIET !\n\n: IMMEDIATE 1 LATEST @ 1- C! ;\n\n: ( SOURCE >IN @ /STRING 41 SCAN DROP CHAR+ SOURCE DROP - >IN ! ; IMMEDIATE\n\n"
},
{
"path": "kernel/forth/vdom.f",
"chars": 9558,
"preview": "1 QUIET !\n\n( utils )\n\n: MB 1024 * 1024 * ;\n\n: 2exec ( x w1 w2 -- x1 x2 ) 2>R DUP R> EXECUTE SWAP R> EXECUTE SWAP ;\n: 2ex"
},
{
"path": "kernel/forth_interpreter.py",
"chars": 11968,
"preview": "\"\"\"\nForth interepter, defined in Forth within Python.\n\"\"\"\n\nfrom asm_ops import *\nfrom memory_layout import *\n\n\ndef forth"
},
{
"path": "kernel/memory_layout.py",
"chars": 2047,
"preview": "\"\"\"\nConstants that define the memory layout.\n\"\"\"\n\nfrom _binaryen_c import lib\n\n\nCELL_SIZE = 4\nCELL_TYPE = lib.BinaryenIn"
},
{
"path": "kernel/vendor/binaryen-c.h",
"chars": 47250,
"preview": "/*\n * Copyright 2016 WebAssembly Community Group participants\n *\n * Licensed under the Apache License, Version 2.0 (the "
},
{
"path": "package.json",
"chars": 657,
"preview": "{\n \"name\": \"wasm-forth\",\n \"version\": \"2.0.0\",\n \"description\": \"A Forth implementation compiling to WebAssembly.\",\n \""
},
{
"path": "repl/index.html",
"chars": 724,
"preview": "<!DOCTYPE html>\n\n<html>\n <head>\n <title>WASM Forth - Interactive Environment</title>\n <meta charset=\"ut"
},
{
"path": "repl/repl.css",
"chars": 980,
"preview": "html, body {\n height: 100%;\n}\n\nhtml {\n background-color: #002b36;\n color: #93a1a1;\n font-family: monospace;\n"
},
{
"path": "repl/repl.js",
"chars": 1174,
"preview": "import * as WasmForth from '../src/index';\n\nlet loadingElement = document.getElementById('loading');\nlet inputElement = "
},
{
"path": "setup.py",
"chars": 960,
"preview": "from os import path\n\nfrom setuptools import setup, find_packages\n\n\ndef get_long_description():\n readme_path = path.jo"
},
{
"path": "src/index.js",
"chars": 7313,
"preview": "let interpreter;\nlet memBytes;\nlet memCells;\nlet inputBuffer = '';\nlet onSourceAvailable;\n\nfunction decodeString(memoryI"
},
{
"path": "webpack.config.js",
"chars": 467,
"preview": "let path = require('path');\n\nlet wasmForth = {\n entry: {\n main: './src/index.js'\n },\n output: {\n "
}
]
About this extraction
This page contains the full source code of the stefano/wasm-forth GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 37 files (185.6 KB), approximately 51.9k tokens, and a symbol index with 122 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.