Compare commits

..

82 Commits

Author SHA1 Message Date
Scott Richmond
d52faeff41 asdf 2025-07-04 15:57:16 -04:00
Scott Richmond
ed6976fe35 asdf 2025-07-04 15:37:39 -04:00
Scott Richmond
22ac3cb0fe release build 2025-07-04 15:30:26 -04:00
Scott Richmond
8851002a90 add is_starting_up 2025-07-04 15:29:44 -04:00
Scott Richmond
cd80e65528 release build 2025-07-04 15:19:32 -04:00
Scott Richmond
f853e02f00 fix slice_n 2025-07-04 15:18:49 -04:00
Scott Richmond
dc11d6cc58 release build 2025-07-04 15:10:51 -04:00
Scott Richmond
7cffa43c3e globalize key_down and key_up 2025-07-04 15:09:02 -04:00
Scott Richmond
294d7d6be2 release build 2025-07-04 14:44:50 -04:00
Scott Richmond
2808c0b709 add slice_n to prelude 2025-07-04 14:44:09 -04:00
Scott Richmond
55483d54a2 release build 2025-07-04 14:11:01 -04:00
Scott Richmond
3b8d3ff5e3 consolidate js functions 2025-07-04 14:10:27 -04:00
Scott Richmond
9228e060bb keep working on panics: tracebacks sort of work? 2025-07-04 14:10:03 -04:00
Scott Richmond
050a0f987d also put the new panic mod under version control 2025-07-04 01:23:31 -04:00
Scott Richmond
0d8b42662b working on panics 2025-07-04 01:23:16 -04:00
Scott Richmond
f97f6670bd pretty good parsing errors 2025-07-03 23:23:14 -04:00
Scott Richmond
d6a004d9ac scanning errors are now nice 2025-07-03 20:45:55 -04:00
Scott Richmond
c6709bb2e8 use serde to serialize the things 2025-07-03 20:22:11 -04:00
Scott Richmond
9f9f59b33b string keys on dicts now fully work 2025-07-03 15:30:51 -04:00
Scott Richmond
659fdd3506 add string keys to dicts 2025-07-03 12:41:00 -04:00
Scott Richmond
d334e483a5 work on errors 2025-07-02 23:47:02 -04:00
Scott Richmond
2ffff9edd9 properly scan escape chars 2025-07-02 20:54:21 -04:00
Scott Richmond
28d6dc24f0 make an attempt at fixing string escaping 2025-07-02 19:44:12 -04:00
Scott Richmond
0cd682de21 method syntax sugar achieved 2025-07-02 19:29:49 -04:00
Scott Richmond
12389ae371 do and panic are now simple forms 2025-07-02 17:29:09 -04:00
Scott Richmond
bf204696a5 release build 2025-07-02 16:56:59 -04:00
Scott Richmond
6bdb9779d8 don't discard initial messages 2025-07-02 16:56:30 -04:00
Scott Richmond
2f4ab41a62 add log to input 2025-07-02 16:20:22 -04:00
Scott Richmond
1316c8228f release build 2025-07-02 16:05:49 -04:00
Scott Richmond
dcf550ba2f wasm->build 2025-07-02 16:05:38 -04:00
Scott Richmond
df5c745ce9 fix complete reset 2025-07-02 16:05:06 -04:00
Scott Richmond
1435e753e8 move default to the top 2025-07-02 15:47:33 -04:00
Scott Richmond
f6ad3b6966 clean up justfile 2025-07-02 15:43:44 -04:00
Scott Richmond
5a778d9a55 try again w/ justfile 2025-07-02 15:37:56 -04:00
Scott Richmond
62ad321a88 finish release recipe? 2025-07-02 15:35:19 -04:00
Scott Richmond
14a41dc1bd justinging 2025-07-02 15:34:36 -04:00
Scott Richmond
d9b095c3f3 keep justing 2025-07-02 15:26:19 -04:00
Scott Richmond
44739adfe5 keep working on justfile 2025-07-02 15:19:54 -04:00
Scott Richmond
624c0bd2f8 start work on release recipe 2025-07-02 15:04:54 -04:00
Scott Richmond
1158821aff build 2025-07-02 14:52:22 -04:00
Scott Richmond
cfe8009861 ready handshake for better message passing 2025-07-02 14:51:42 -04:00
Scott Richmond
33b7f78038 build 2025-07-02 13:49:36 -04:00
Scott Richmond
116a5b2ed9 prevent rust panic on kill signal 2025-07-02 13:44:26 -04:00
Scott Richmond
9414dc64d9 actually (?!) fix drunk turtle problem 2025-07-01 20:10:24 -04:00
Scott Richmond
197cbfc795 try again 2025-07-01 20:07:02 -04:00
Scott Richmond
f3801b3c37 maybe fix drunk turtle bug? 2025-07-01 19:55:49 -04:00
Scott Richmond
f8983d24a4 another wasm release 2025-07-01 19:20:33 -04:00
Scott Richmond
e5467e9e7e wasm release 2025-07-01 19:08:13 -04:00
Scott Richmond
bba3e1e800 thoughts 2025-07-01 19:07:16 -04:00
Scott Richmond
b7ff0eda80 get reading input up and running 2025-07-01 19:04:38 -04:00
Scott Richmond
5b2fd5e2d7 get fetch up & running 2025-07-01 18:52:03 -04:00
Scott Richmond
b12d0e00aa get input working 2025-07-01 16:59:42 -04:00
Scott Richmond
808368d2b9 update worker url resolution 2025-07-01 16:30:17 -04:00
Scott Richmond
88ff5886bb fix worker path 2025-07-01 16:07:01 -04:00
Scott Richmond
1ec60b9362 get commands wired up, probs 2025-07-01 14:35:36 -04:00
Scott Richmond
400bd5864b fix FF event loop bug 2025-07-01 12:54:11 -04:00
Scott Richmond
991705e734 add thoughts 2025-07-01 11:10:50 -04:00
Scott Richmond
989e217917 stash changes 2025-07-01 10:42:34 -04:00
Scott Richmond
4e7557cbcc fix truly heinous memory bug 2025-07-01 01:30:10 -04:00
Scott Richmond
2f3f362f49 hook the things up and discover a possible stop-the-world bug 2025-07-01 00:43:01 -04:00
Scott Richmond
4eceb62ce5 integration work continues 2025-06-30 18:59:59 -04:00
Scott Richmond
173fdb913c also add the new io file 2025-06-30 12:49:07 -04:00
Scott Richmond
bc49ece0cf stub out first pass of io system 2025-06-30 12:48:50 -04:00
Scott Richmond
5478e5e40e use a hashset instead of vec for dead ids 2025-06-29 18:14:06 -04:00
Scott Richmond
f6cbe3f800 start working on packaging better 2025-06-29 18:13:49 -04:00
Scott Richmond
c62b5c903d update chumsky, lose ariadne, update parser to conform to new chumsky 2025-06-29 18:08:44 -04:00
Scott Richmond
de6cb5380d add a justfile, some project management 2025-06-29 17:47:08 -04:00
Scott Richmond
4dd47dd56c save work 2025-06-29 11:38:45 -04:00
Scott Richmond
f710beff46 actually get receive working???? 2025-06-28 16:40:31 -04:00
Scott Richmond
f873be7668 some notes 2025-06-27 20:54:48 -04:00
Scott Richmond
48342ba4ea make progress, I guess 2025-06-27 20:41:29 -04:00
Scott Richmond
db52bc2687 parser housekeeping; add receive to lexer and parser 2025-06-27 19:15:59 -04:00
Scott Richmond
a175ee7a41 move Ast into its own module 2025-06-27 19:05:17 -04:00
Scott Richmond
759fc63cae ugh. spin my wheels a lot. decide to start work on the receive special form 2025-06-27 18:48:27 -04:00
Scott Richmond
8923581eed add sleep, which was unexpectedly titchy! 2025-06-27 14:27:42 -04:00
Scott Richmond
90505f89fe make some new process functions 2025-06-27 12:27:54 -04:00
Scott Richmond
00ebac17ce some notes for tomorrow's work 2025-06-26 23:28:17 -04:00
Scott Richmond
888f5b62da send messages, motherfucker! 2025-06-26 20:30:40 -04:00
Scott Richmond
c144702b98 add a process value 2025-06-26 17:17:41 -04:00
Scott Richmond
801e5bcc01 devise a way of communicating between ludus and processes 2025-06-26 17:15:00 -04:00
Scott Richmond
b35657e698 refactor to have a world run a process 2025-06-26 16:11:35 -04:00
Scott Richmond
b5528ced8f start work on actor model 2025-06-26 01:28:33 -04:00
49 changed files with 16690 additions and 242 deletions

21
Cargo.toml Normal file
View File

@ -0,0 +1,21 @@
[package]
name = "rudus"
version = "0.0.1"
edition = "2021"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
chumsky = "0.10.1"
imbl = "3.0.0"
num-derive = "0.4.2"
num-traits = "0.2.19"
regex = "1.11.1"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4.50"
serde = {version = "1.0", features = ["derive"]}
serde_json = "1.0"
console_error_panic_hook = "0.1.7"
struct_scalpel = "0.1.1"
serde-wasm-bindgen = "0.6.5"

235
LICENSE Normal file
View File

@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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.
rudus
Copyright (C) 2024 scott
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
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 AGPL, see <http://www.gnu.org/licenses/>.

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# rudus
A Rust implementation of Ludus.

31
assets/agent.ld Normal file
View File

@ -0,0 +1,31 @@
fn agent (val) -> receive {
(:set, new) -> agent (new)
(:get, pid) -> {
send (pid, (:response, val))
agent (val)
}
(:update, f) -> agent (f (val))
}
fn agent/set (pid, val) -> {
send (pid, (:set, val))
val
}
fn agent/get (pid) -> {
send (pid, (:get, self ()))
receive {
(:response, val) -> val
}
}
fn agent/update (pid, f) -> {
send (pid, (:update, f))
agent/get (pid)
}
let myagent = spawn! (fn () -> agent (42))
print! ("incrementing agent value to", agent/update (myagent, inc))
:done!

1474
assets/prelude.ld Normal file

File diff suppressed because it is too large Load Diff

1528
assets/test_prelude.ld Normal file

File diff suppressed because it is too large Load Diff

255
bytecode_thoughts.md Normal file
View File

@ -0,0 +1,255 @@
# Working notes on bytecode stuff
### 2024-12-15
So far, I've done the easy stuff: constants, and ifs.
There's still some easy stuff left:
* [ ] lists
* [ ] dicts
* [ ] when
* [ ] panic
So I'll do those next.
But then we've got two doozies: patterns and bindings, and tuples.
#### Tuples make things hard
In fact, it's tuples that make things hard.
The idea is that, when possible, tuples should be stored on the stack.
That makes them a different creature than anything else.
But the goal is to be able, in a function call, to just push a tuple onto the stack, and then match against it.
Because a tuple _isn't_ just another `Value`, that makes things challenging.
BUT: matching against all other `Values` should be straightforward enough?
I think that the way to do this is to reify patterns.
Rather than try to emit bytecodes to embody patterns, the patterns are some kind of data that get compiled and pushed onto a stack like keywords and interned strings and whatnot.
And then you can push a pattern onto the stack right behind a value, and then have a `match` opcode that pops them off.
Things get a bit gnarly since patterns can be nested. I'll start with the basic cases and run from there.
But when things get *very* gnarly is considering tuples on the stack.
How do you pop off a tuple?
Two thoughts:
1. Just put tuples on the heap. And treat function arguments/matching differently.
2. Have a "register" that stages values to be pattern matched.
##### Regarding the first option
I recall seeing somebody somewhere make a comment that trying to represent function arguments as tuples caused tons of pain.
I can see why that would be the case, from an implementation standpoint.
We should have _values_, and don't do fancy bookkeeping if we don't have to.
_Conceptually_, it makes a great deal of sense to think of tuples as being deeply the same as function invocation.
But _practically_, they are different things, especially with Rust underneath.
This feels like this cuts along the grain, and so this is what I will try.
I suspect that I'll end up specializing a lot around function arguments and calling, but that feels more tractable than the bookkeeping around stack-based tuples.
### 2024-12-17
Next thoughts: take some things systematically rather than choosing an approach first.
#### Things that always match
* Placeholder.
- I _think_ this is just a no-op. A `let` expression leaves its rhs pushed on the stack.
* Word: put something on the stack, and bind a name.
- This should follow the logic of locals as articulated in _Crafting Interpreters_.
In both of these cases, there's no conditional logic, simply a bind.
#### Things that never bind
* Atomic values: put the rhs on the stack, then do an equality check, and panic if it fails. Leave the thing on the stack.
#### Analysis
In terms of bytecode, I think one thing to do, in the simple case, is to do the following:
* `push` a `pattern` onto the stack
* `match`--pops the pattern and the value off the stack, and then applies the pattern to the value. It leaves the value on the stack, and pushes a special value onto the stack representing a match, or not.
- We'll probably want `match-1`, `match-2`, `match-3`, etc., opcodes for matching a value that's that far back in the stack. E.g., `match-1` matches against not the top element, but the `top - 1` element.
- This is _specifically_ for matching function arguments and `loop` forms.
* There are a few different things we might do from here:
- `panic_if_no_match`: panic if the last thing is a `no_match`, or just keep going if not.
- `jump_if_no_match`: in a `match` form or a function, we'll want to move to the next clause if there's no match, so jump to the next clause's `pattern` `push` code.
* Compound patterns are going to be more complex.
- I think, for example, what you're going to need to do is to get opcodes that work on our data structures, so, for example, when you have a `match_compound` opcode and you start digging into the pattern.
* Compound patterns are specifically _data structures_. So simple structures should be stack-allocated, and and complex structures should be pointers to something on the heap. Maybe?
#### A little note
For instructions that need more than 256 possibilities, we'll need to mush two `u8`s together into a `u16`. The one liner for this is:
```rust
let number = ((first as u16) << 8) | second as u16;
```
#### Oy, stacks and expressions
One thing that's giving me grief is when to pop and when to note on the value stack.
So, like, we need to make sure that a line of code leaves the stack exactly where it was before it ran, with the exception of binding forms: `let`, `fn`, `box`, etc. Those leave one (or more!) items on the stack.
In the simplest case, we have a line of code that's just a constant:
```
false
```
This should emit the bytecode instructions (more or less):
```
push false
pop
```
The push comes from the `false` value.
The pop comes from the end of a (nonbinding) line.
The problem is that there's no way (at all, in Ludus) to distinguish between an expression that's just a constant and a line that is a complete line of code that's an expression.
So if we have the following:
```
let foo = false
```
We want:
```
push false
```
Or, rather, given that `foo` is a word pattern, what we actually want is:
```
push false # constant
push pattern/word # load pattern
pop
pop # compare
push false # for the binding
```
But it's worth it here to explore Ludus's semantics.
It's the case that there are actually only three binding forms (for now): `let`, `fn`, and `box`.
Figuring out `let` will help a great deal.
Match also binds things, but at the very least, match doesn't bind with expressions on the rhs, but a single value.
Think, too about expressions: everything comes down to a single value (of course), even tuples (especially now that I'm separating function calls from tuple values (probably)).
So: anything that *isn't* a binding form should, before the `pop` from the end of a line, only leave a single value on the stack.
Which suggests that, as odd as it is, pushing a single `nil` onto the stack, just to pop it, might make sense.
Or, perhaps the thing to do is to peek: if the line in question is binding or not, then emit different bytecode.
That's probably the thing to do. Jesus, Scott.
And **another** thing worth internalizing: every single instruction that's not an explicit push or pop should leave the stack length unchanged.
So store and load need always to swap in a `nil`
### 2024-12-23
Compiling functions.
So I'm working through the functions chapter of _CI_, and there are a few things that I'm trying to wrap my head around.
First, I'm thinking that since we're not using raw pointers, we'll need some functional indirection to get our current byte.
So one of the hard things here is that, unlike with Lox, Ludus doesn't have fixed-arity functions. That means that the bindings for function calls can't be as dead simple as in Lox. More to the point, because we don't know everything statically, we'll need to do some dynamic magic.
The Bob Nystrom program uses three useful auxiliary constructs to make functions straightforward:
* `CallFrame`s, which know which function is being called, has their own instruction pointer, and an offset for the first stack slot that can be used by the function.
```c
typedef struct {
ObjFunction* function;
uint8_t* ip;
Value* slots;
} CallFrame;
```
Or the Rust equivalent:
```rust
struct CallFrame {
function: LFn,
ip: usize,
stack_root: usize,
}
```
* `Closure`s, which are actual objects that live alongside functions. They have a reference to a function and to an array of "upvalues"...
* `Upvalue`s, which are ways of pointing to values _below_ the `stack_root` of the call frame.
##### Digression: Prelude
I decided to skip the Prelude resolution in the compiler and only work with locals. But actually, closures, arguments, and the prelude are kind of the same problem: referring to values that aren't currently available on the stack.
We do, however, know at compile time the following:
* If a binding's target is on the stack, in a closure, or in the prelude.
* This does, however, require that the function arguments work in a different way.
The way to do this, I reckon, is this:
* Limit arguments (to, say, no more than 7).
* A `CallFrame` includes an arity field.
* It also includes an array of length 7.
* Each `match` operation in function arguments clones from the call frame, and the first instruction for any given body (i.e. once we've done the match) is to clear the arguments registers in the `CallFrame`, thus decrementing all the refcounts of all the heap-allocated objects.
* And the current strategy of scoping and popping in the current implementation of `match` will work just fine!
Meanwhile, we don't actually need upvalues, because bindings cannot change in Ludus. So instead of upvalues and their indirection, we can just emit a bunch of instructions to have a `values` field on a closure. The compiler, meanwhile, will know how to extract and emit instructions both to emit those values *and* to offer correct offsets.
The only part I haven't figured out quite yet is how to encode access to what's stored in a closure.
Also, I'm not certain we need the indirection of a closure object in Ludus. The function object itself can do the work, no?
And the compiler knows which function it's closing over, and we can emit a bunch of instructions to close stuff over easily, after compiling the function and putting it in the constants table. The way to do this is to yank the value to the top of the stack using normal name resolution procedures, and then use a two-byte operand, `Op::Close` + index of the function in the constants table.
##### End of digression.
And, because we know exactly is bound in a given closure, we can actually emit instructions to close over a given value easily.
#### A small optimization
The lifetimes make things complicated; but I'm not sure that I would want to actually manage them manually, given how much they make my head hurt with Rust. I do get the sense that we will, at some point, need some lifetimes. A `Chunk` right now is chunky, with lots of owned `vec`s.
Uncle Bob separates `Chunk`s and `Compiler`s, which, yes! But then we have a problem: all of the information to climb back to source code is in the `Compiler` and not in the `Chunk`. How to manage that encoding?
(Also the keyword and string intern tables should be global, and not only in a single compiler, since we're about to get nested compilers...)
### 2024-12-24
Other interesting optimizations abound:
* `add`, `sub`, `inc`, `dec`, `type`, and other extremely frequently used, simple functions can be compiled directly to built-in opcodes. We still need functions for them, with the same arities, for higher order function use.
- The special-case logic is in the `Synthetic` compiler branch, rather than anywhere else.
- It's probably best to disallow re-binding these names anywhere _except_ Prelude, where we'll want them shadowed.
- We can enforce this in `Validator` rather than `Compiler`.
* `or` and `and` are likewise built-in, but because they don't evaluate their arguments eagerly, that's another, different special case that's a series of eval, `jump_if_false`, eval, `jump_if_false`, instructions.
* More to the point, the difference between `or` and `and` here and the built-ins is that `or` and `and` are variadic, where I was originally thinking about `and` and co. as fixed-arity, with variadic behaviours defined by a shadowing/backing Ludus function. That isn't necessary, I don't think.
* Meanwhile, `and` and `or` will also, of necessity, have backing shadowing functions.
#### More on CallFrames and arg passing
* We don't actually need the arguments register! I was complicating things. The stack between the `stack_root` and the top will be _exactly_ the same as an arguments register would have been in my imagination. So we can determine the number of arguments passed in with `stack.len() - stack_root`, and we can access argument positions with `stack_root + n`, since the first argument is at `stack_root`.
- This has the added benefit of not having to do any dances to keep the refcount of any heap-allocated objects as low as possible. No extra `Clone`s here.
* In addition, we need two `check_arity` ops: one for fixed-arity clauses, and one for clauses with splatterns. Easily enough done. Remember: opcodes are for special cases!
#### Tail calls
* The way to implement tail calls is actually now really straightforward! The idea is to simply have a `TailCall` rather than a `Call` opcode. In place of creating a new stack frame and pushing it to the call stack on top of the old call frame, you pop the old call frame, then push the new one to the call stack.
* That does mean the `Compiler` will need to keep track of tail calls. This should be pretty straightforward, actually, and the logic is already there in `Validator`.
* The thing here is that the new stack frame simply requires the same return location as the old one it's replacing.
* That reminds me that there's an issue in terms of keeping track of not just the IP, but the chunk. In Lox, the IP is a pointer to a `u8`, which works great in C. But in Rust, we can't use a raw pointer like that, but an index into a `vec<u8>`. Which means the return location needs both a chunk and an index, not just a `u8` pointer:
```rust
struct StackFrame<'a> {
function: LFn,
stack_root: usize,
return: (&'a Chunk, usize),
}
```
(I hate that there's a lifetime here.)
This gives us a way to access everything we need: where to return to, the root of the stack, the chunk (function->chunk), the closures (function->closures).
### 2024-12-26
One particular concern here, which needs some work: recursion is challenging.
In particular, the issue is that if, as I have been planning, a function closes over all its values at the moment it is compiled, the only value type that requires updating is a function. A function can be declared but not yet defined, and then when another function that uses that function is defined, the closed-over value will be to the declaration but not the definition.
One way to handle this, I think is using `std::cell::OnceCell`. Rather than a `RefCell`, `OnceCell` has no runtime overhead. Instead, what happens is you effectively put a `None` in the cell. Then, once you have the value you want to put in there, you call `set` on the `OnceCell`, and it does what it needs to.
This allows for the closures to be closed over right after compilation.
### 2024-12-27
Working on `loop` and `recur`, rather than `fn`--this is the gentler slope.
And discovering that we actually need a `[Value; 15]` return register.
`recur` needs to push all the arguments to the stack, then yank them off into the return register, then pop back to the loop root, then push all the things back onto the stack, then jump to the beginning of the loop.
And that also means I need a different `Value` variant that's a true `Nothing`, not even `nil`, which will _never_ end up anywhere other than a placeholder value in the register and on the stack.
So, next steps:
1. Add `Value::Nothing` and fix all the compiler errors
2. Make the return register `[Value; 15]`, populated with `Value::Nothing`s at initialization.
3. Update `load` and `store` to work with the array rather than a single value.
4. Create `store_n` and `load_n` to work with multiple values.
5. Create a `Vm.arity` method that computes how many non-nothings were passed into the register.
6. Then, implement `recur`
7. And, then, fix up jump indexes in `loop`
8. Fix all the off-by-one errors in the jumps

40
justfile Normal file
View File

@ -0,0 +1,40 @@
default:
@just --list
# build optimized wasm
build: && clean-wasm-pack
# build with wasm-pack
wasm-pack build --target web
# build dev wasm
dev: && clean-wasm-pack
wasm-pack build --dev --target web
# clean up after wasm-pack
clean-wasm-pack:
# delete cruft from wasm-pack
rm pkg/.gitignore pkg/package.json pkg/README.md
rm -rf pkg/snippets
# fix imports of rudus.js
cp pkg/rudus.js pkg/rudus.js.backup
echo 'import { io } from "./worker.js"' > pkg/rudus.js
cat pkg/rudus.js.backup | tail -n+2>> pkg/rudus.js
rm pkg/rudus.js.backup
from_branch := `git branch --show-current`
git_status := `git status -s`
# publish this branch into release
release:
echo {{ if git_status == "" {"git status ok"} else {error("please commit changes first")} }}
just build
-git commit -am "release build"
git checkout release
git merge {{from_branch}}
git push
git checkout {{from_branch}}
# serve the pkg directory
serve:
live-server pkg

1210
may_2025_thoughts.md Normal file

File diff suppressed because it is too large Load Diff

1594
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "@ludus/rudus",
"version": "0.1.3",
"description": "A Rust-based Ludus bytecode interpreter.",
"type": "module",
"main": "pkg/ludus.js",
"directories": {},
"keywords": [],
"author": "Scott Richmond",
"license": "GPL-3.0",
"files": [
"pkg/rudus.js",
"pkg/ludus.js",
"pkg/rudus_bg.wasm",
"pkg/rudus_bg.wasm.d.ts",
"pkg/rudus.d.ts"
],
"devDependencies": {
}
}

15
pkg/index.html Normal file
View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
<title>Testing Ludus/WASM integration</title>
</head>
<body>
<script src="./ludus.js" type="module"></script>
<p>
Open the console. All the action's in there.
</p>
</body>
</html>

View File

@ -1,32 +1,188 @@
import init, {ludus} from "./rudus.js";
if (window) window.ludus = {run, kill, flush_stdout, stdout, p5, svg, flush_commands, commands, result, flush_result, input, is_running, key_down, key_up, is_starting_up}
await init();
let res = null
const worker_url = new URL("worker.js", import.meta.url)
const worker = new Worker(worker_url, {type: "module"})
let outbox = []
let ludus_console = ""
let ludus_commands = []
let ludus_result = null
let code = null
let running = false
let ready = false
let io_interval_id = null
let keys_down = new Set();
function reset_ludus () {
outbox = []
ludus_console = ""
ludus_commands = []
ludus_result = null
code = null
running = false
ready = false
io_interval_id = null
keys_down = new Set()
}
worker.onmessage = handle_messages
async function handle_messages (e) {
let msgs
try {
msgs = JSON.parse(e.data)
} catch {
console.log(e.data)
throw Error("Main: bad json from Ludus")
}
for (const msg of msgs) {
switch (msg.verb) {
case "Complete": {
console.log("Main: ludus completed with => ", msg.data)
ludus_result = msg.data
running = false
ready = false
outbox = []
break
}
case "Error": {
console.log("Main: ludus errored with => ", msg.data)
ludus_result = msg.data
running = false
ready = false
outbox = []
break
}
// TODO: do more than report these
case "Console": {
let new_lines = msg.data.join("\n");
ludus_console = ludus_console + new_lines
console.log("Main: ludus says => ", new_lines)
break
}
case "Commands": {
console.log("Main: ludus commands => ", msg.data)
for (const command of msg.data) {
// attempt to solve out-of-order command bug
ludus_commands[command[1]] = command
}
break
}
case "Fetch": {
console.log("Main: ludus requests => ", msg.data)
const res = await fetch(msg.data, {mode: "cors"})
const text = await res.text()
console.log("Main: js responds => ", text)
outbox.push({verb: "Fetch", data: [msg.data, res.status, text]})
}
case "Ready": {
console.log("Main: ludus is ready")
ready = true
}
}
}
}
function io_poller () {
if (io_interval_id && !running) {
// flush the outbox one last time
// (presumably, with the kill message)
worker.postMessage(outbox)
// cancel the poller
clearInterval(io_interval_id)
outbox = []
}
if (ready && running) {
worker.postMessage(outbox)
outbox = []
}
}
function start_io_polling () {
io_interval_id = setInterval(io_poller, 10)
}
// runs a ludus script; does not return the result
// the result must be explicitly polled with `result`
export function run (source) {
code = source
const output = ludus(source)
res = JSON.parse(output)
return res
if (running || ready) {
return "TODO: handle this? should not be running"
}
worker.postMessage([{verb: "Run", data: source}])
reset_ludus()
start_io_polling()
}
export function is_starting_up() {
return running && !ready
}
// tells if the ludus script is still running
export function is_running() {
return running && ready
}
// kills a ludus script
export function kill () {
running = false
outbox.push({verb: "Kill"})
console.log("Main: Killed Ludus")
}
// sends text into ludus (status: not working)
export function input (text) {
console.log("Main: calling `input` with ", text)
outbox.push({verb: "Input", data: text})
}
// returns the contents of the ludus console and resets the console
export function flush_stdout () {
let out = ludus_console
ludus_console = ""
return out
}
// returns the contents of the ludus console, retaining them
export function stdout () {
if (!res) return ""
return res.io.stdout.data
return ludus_console
}
export function turtle_commands () {
if (!res) return []
return res.io.turtle.data
// returns the array of turtle commands
export function commands () {
return ludus_commands
}
// returns the array of turtle commands and clears it
export function flush_commands () {
let out = ludus_commands
ludus_commands = []
return out
}
// returns the ludus result
// this is effectively Option<String>:
// null if no result has been returned, or
// a string representation of the result
export function result () {
return res
return ludus_result
}
export function flush_result () {
let out = ludus_result
ludus_result = null
return out
}
export function key_down (str) {
if (is_running()) keys_down.add(str)
}
export function key_up (str) {
if (is_running()) keys_down.delete(str)
}
//////////// turtle plumbing below
// TODO: refactor this out into modules
const turtle_init = {
position: [0, 0],
heading: 0,
@ -81,8 +237,9 @@ function unit_of (heading) {
return [Math.cos(radians), Math.sin(radians)]
}
function command_to_state (prev_state, curr_command) {
const verb = curr_command[0]
function command_to_state (prev_state, command) {
const [_target, _id, curr_command] = command
const [verb] = curr_command
switch (verb) {
case "goto": {
const [_, x, y] = curr_command
@ -299,7 +456,7 @@ export function svg (commands) {
return accum
}, {maxX: 0, maxY: 0, minX: 0, minY: 0})
const [r, g, b, a] = resolve_color(background_color)
const [r, g, b] = resolve_color(background_color)
if ((r+g+b)/3 > 128) turtle_color = [0, 0, 0, 150]
const view_width = (maxX - minX) * 1.2
const view_height = (maxY - minY) * 1.2
@ -376,4 +533,4 @@ export function p5 (commands) {
return p5_calls
}
window.ludus = {p5, svg, run, stdout, turtle_commands, result, extract_ludus};

View File

@ -1,16 +1,21 @@
/* tslint:disable */
/* eslint-disable */
export function ludus(src: string): string;
export function ludus(src: string): Promise<void>;
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
export interface InitOutput {
readonly memory: WebAssembly.Memory;
readonly ludus: (a: number, b: number) => [number, number];
readonly __wbindgen_export_0: WebAssembly.Table;
readonly ludus: (a: number, b: number) => any;
readonly __wbindgen_exn_store: (a: number) => void;
readonly __externref_table_alloc: () => number;
readonly __wbindgen_export_2: WebAssembly.Table;
readonly __wbindgen_free: (a: number, b: number, c: number) => void;
readonly __wbindgen_malloc: (a: number, b: number) => number;
readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
readonly __wbindgen_free: (a: number, b: number, c: number) => void;
readonly __wbindgen_export_6: WebAssembly.Table;
readonly closure338_externref_shim: (a: number, b: number, c: any) => void;
readonly closure351_externref_shim: (a: number, b: number, c: any, d: any) => void;
readonly __wbindgen_start: () => void;
}

415
pkg/rudus.js Normal file
View File

@ -0,0 +1,415 @@
import { io } from "./worker.js"
let wasm;
function addToExternrefTable0(obj) {
const idx = wasm.__externref_table_alloc();
wasm.__wbindgen_export_2.set(idx, obj);
return idx;
}
function handleError(f, args) {
try {
return f.apply(this, args);
} catch (e) {
const idx = addToExternrefTable0(e);
wasm.__wbindgen_exn_store(idx);
}
}
const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );
if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };
let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
}
function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
let WASM_VECTOR_LEN = 0;
const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } );
const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
? function (arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
}
: function (arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
});
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === undefined) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length, 1) >>> 0;
getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len, 1) >>> 0;
const mem = getUint8ArrayMemory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 0x7F) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
ptr = realloc(ptr, len, offset, 1) >>> 0;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
let cachedDataViewMemory0 = null;
function getDataViewMemory0() {
if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
}
return cachedDataViewMemory0;
}
function isLikeNone(x) {
return x === undefined || x === null;
}
const CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(state => {
wasm.__wbindgen_export_6.get(state.dtor)(state.a, state.b)
});
function makeMutClosure(arg0, arg1, dtor, f) {
const state = { a: arg0, b: arg1, cnt: 1, dtor };
const real = (...args) => {
// First up with a closure we increment the internal reference
// count. This ensures that the Rust closure environment won't
// be deallocated while we're invoking it.
state.cnt++;
const a = state.a;
state.a = 0;
try {
return f(a, state.b, ...args);
} finally {
if (--state.cnt === 0) {
wasm.__wbindgen_export_6.get(state.dtor)(a, state.b);
CLOSURE_DTORS.unregister(state);
} else {
state.a = a;
}
}
};
real.original = state;
CLOSURE_DTORS.register(real, state, state);
return real;
}
/**
* @param {string} src
* @returns {Promise<void>}
*/
export function ludus(src) {
const ptr0 = passStringToWasm0(src, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.ludus(ptr0, len0);
return ret;
}
function __wbg_adapter_18(arg0, arg1, arg2) {
wasm.closure338_externref_shim(arg0, arg1, arg2);
}
function __wbg_adapter_44(arg0, arg1, arg2, arg3) {
wasm.closure351_externref_shim(arg0, arg1, arg2, arg3);
}
async function __wbg_load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports);
} catch (e) {
if (module.headers.get('Content-Type') != 'application/wasm') {
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
} else {
throw e;
}
}
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return { instance, module };
} else {
return instance;
}
}
}
function __wbg_get_imports() {
const imports = {};
imports.wbg = {};
imports.wbg.__wbg_call_672a4d21634d4a24 = function() { return handleError(function (arg0, arg1) {
const ret = arg0.call(arg1);
return ret;
}, arguments) };
imports.wbg.__wbg_call_7cccdd69e0791ae2 = function() { return handleError(function (arg0, arg1, arg2) {
const ret = arg0.call(arg1, arg2);
return ret;
}, arguments) };
imports.wbg.__wbg_error_7534b8e9a36f1ab4 = function(arg0, arg1) {
let deferred0_0;
let deferred0_1;
try {
deferred0_0 = arg0;
deferred0_1 = arg1;
console.error(getStringFromWasm0(arg0, arg1));
} finally {
wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);
}
};
imports.wbg.__wbg_io_5a3c8ea72d8c6ea3 = function() { return handleError(function (arg0, arg1) {
let deferred0_0;
let deferred0_1;
try {
deferred0_0 = arg0;
deferred0_1 = arg1;
const ret = io(getStringFromWasm0(arg0, arg1));
return ret;
} finally {
wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);
}
}, arguments) };
imports.wbg.__wbg_log_11652c6a56eeddfb = function(arg0, arg1) {
console.log(getStringFromWasm0(arg0, arg1));
};
imports.wbg.__wbg_new_23a2665fac83c611 = function(arg0, arg1) {
try {
var state0 = {a: arg0, b: arg1};
var cb0 = (arg0, arg1) => {
const a = state0.a;
state0.a = 0;
try {
return __wbg_adapter_44(a, state0.b, arg0, arg1);
} finally {
state0.a = a;
}
};
const ret = new Promise(cb0);
return ret;
} finally {
state0.a = state0.b = 0;
}
};
imports.wbg.__wbg_new_8a6f238a6ece86ea = function() {
const ret = new Error();
return ret;
};
imports.wbg.__wbg_newnoargs_105ed471475aaf50 = function(arg0, arg1) {
const ret = new Function(getStringFromWasm0(arg0, arg1));
return ret;
};
imports.wbg.__wbg_now_8dddb61fa4928554 = function() {
const ret = Date.now();
return ret;
};
imports.wbg.__wbg_queueMicrotask_97d92b4fcc8a61c5 = function(arg0) {
queueMicrotask(arg0);
};
imports.wbg.__wbg_queueMicrotask_d3219def82552485 = function(arg0) {
const ret = arg0.queueMicrotask;
return ret;
};
imports.wbg.__wbg_random_57c118f142535bb6 = function() {
const ret = Math.random();
return ret;
};
imports.wbg.__wbg_resolve_4851785c9c5f573d = function(arg0) {
const ret = Promise.resolve(arg0);
return ret;
};
imports.wbg.__wbg_stack_0ed75d68575b0f3c = function(arg0, arg1) {
const ret = arg1.stack;
const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len1 = WASM_VECTOR_LEN;
getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
};
imports.wbg.__wbg_static_accessor_GLOBAL_88a902d13a557d07 = function() {
const ret = typeof global === 'undefined' ? null : global;
return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
};
imports.wbg.__wbg_static_accessor_GLOBAL_THIS_56578be7e9f832b0 = function() {
const ret = typeof globalThis === 'undefined' ? null : globalThis;
return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
};
imports.wbg.__wbg_static_accessor_SELF_37c5d418e4bf5819 = function() {
const ret = typeof self === 'undefined' ? null : self;
return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
};
imports.wbg.__wbg_static_accessor_WINDOW_5de37043a91a9c40 = function() {
const ret = typeof window === 'undefined' ? null : window;
return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
};
imports.wbg.__wbg_then_44b73946d2fb3e7d = function(arg0, arg1) {
const ret = arg0.then(arg1);
return ret;
};
imports.wbg.__wbg_then_48b406749878a531 = function(arg0, arg1, arg2) {
const ret = arg0.then(arg1, arg2);
return ret;
};
imports.wbg.__wbindgen_cb_drop = function(arg0) {
const obj = arg0.original;
if (obj.cnt-- == 1) {
obj.a = 0;
return true;
}
const ret = false;
return ret;
};
imports.wbg.__wbindgen_closure_wrapper1034 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 339, __wbg_adapter_18);
return ret;
};
imports.wbg.__wbindgen_init_externref_table = function() {
const table = wasm.__wbindgen_export_2;
const offset = table.grow(4);
table.set(0, undefined);
table.set(offset + 0, undefined);
table.set(offset + 1, null);
table.set(offset + 2, true);
table.set(offset + 3, false);
;
};
imports.wbg.__wbindgen_is_function = function(arg0) {
const ret = typeof(arg0) === 'function';
return ret;
};
imports.wbg.__wbindgen_is_undefined = function(arg0) {
const ret = arg0 === undefined;
return ret;
};
imports.wbg.__wbindgen_string_get = function(arg0, arg1) {
const obj = arg1;
const ret = typeof(obj) === 'string' ? obj : undefined;
var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
};
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
return imports;
}
function __wbg_init_memory(imports, memory) {
}
function __wbg_finalize_init(instance, module) {
wasm = instance.exports;
__wbg_init.__wbindgen_wasm_module = module;
cachedDataViewMemory0 = null;
cachedUint8ArrayMemory0 = null;
wasm.__wbindgen_start();
return wasm;
}
function initSync(module) {
if (wasm !== undefined) return wasm;
if (typeof module !== 'undefined') {
if (Object.getPrototypeOf(module) === Object.prototype) {
({module} = module)
} else {
console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
}
}
const imports = __wbg_get_imports();
__wbg_init_memory(imports);
if (!(module instanceof WebAssembly.Module)) {
module = new WebAssembly.Module(module);
}
const instance = new WebAssembly.Instance(module, imports);
return __wbg_finalize_init(instance, module);
}
async function __wbg_init(module_or_path) {
if (wasm !== undefined) return wasm;
if (typeof module_or_path !== 'undefined') {
if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
({module_or_path} = module_or_path)
} else {
console.warn('using deprecated parameters for the initialization function; pass a single object instead')
}
}
if (typeof module_or_path === 'undefined') {
module_or_path = new URL('rudus_bg.wasm', import.meta.url);
}
const imports = __wbg_get_imports();
if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
module_or_path = fetch(module_or_path);
}
__wbg_init_memory(imports);
const { instance, module } = await __wbg_load(await module_or_path, imports);
return __wbg_finalize_init(instance, module);
}
export { initSync };
export default __wbg_init;

BIN
pkg/rudus_bg.wasm Normal file

Binary file not shown.

14
pkg/rudus_bg.wasm.d.ts vendored Normal file
View File

@ -0,0 +1,14 @@
/* tslint:disable */
/* eslint-disable */
export const memory: WebAssembly.Memory;
export const ludus: (a: number, b: number) => any;
export const __wbindgen_exn_store: (a: number) => void;
export const __externref_table_alloc: () => number;
export const __wbindgen_export_2: WebAssembly.Table;
export const __wbindgen_free: (a: number, b: number, c: number) => void;
export const __wbindgen_malloc: (a: number, b: number) => number;
export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
export const __wbindgen_export_6: WebAssembly.Table;
export const closure338_externref_shim: (a: number, b: number, c: any) => void;
export const closure351_externref_shim: (a: number, b: number, c: any, d: any) => void;
export const __wbindgen_start: () => void;

55
pkg/worker.js Normal file
View File

@ -0,0 +1,55 @@
import init, {ludus} from "./rudus.js";
let initialized_wasm = false
onmessage = run
// exposed in rust as:
// async fn io (out: String) -> Result<JsValue, JsValue>
// rust calls this to perform io
export function io (out) {
// only send messages if we have some
if (out.length > 0) postMessage(out)
// make an event handler that captures and delivers messages from the main thread
// because our promise resolution isn't about calculating a value but setting a global variable, we can't asyncify it
// explicitly return a promise
return new Promise((resolve, reject) => {
// deliver the response to ludus when we get a response from the main thread
onmessage = (e) => {
resolve(JSON.stringify(e.data))
}
// cancel the response if it takes too long
setTimeout(() => reject("io took too long"), 500)
})
}
// set as default event handler from main thread
async function run(e) {
// we must NEVER run `await init()` twice
if (!initialized_wasm) {
// this must come before the init call
initialized_wasm = true
await init()
console.log("Worker: Ludus has been initialized.")
}
// the data is always an array; we only really expect one member tho
let msgs = e.data
for (const msg of msgs) {
// evaluate source if we get some
if (msg.verb === "Run" && typeof msg.data === 'string') {
// temporarily stash an empty function so we don't keep calling this one if we receive additional messages
onmessage = () => {}
// actually run the ludus--which will call `io`--and replace `run` as the event handler for ipc
await ludus(msg.data)
// once we've returned from `ludus`, make this the event handler again
onmessage = run
} else {
// report and swallow any malformed startup messages
console.log("Worker: Did not get valid startup message. Instead got:")
console.log(e.data)
}
}
}

211
rudus.js
View File

@ -1,211 +0,0 @@
let wasm;
let WASM_VECTOR_LEN = 0;
let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
}
const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } );
const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
? function (arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
}
: function (arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
});
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === undefined) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length, 1) >>> 0;
getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len, 1) >>> 0;
const mem = getUint8ArrayMemory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 0x7F) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
ptr = realloc(ptr, len, offset, 1) >>> 0;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );
if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };
function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
/**
* @param {string} src
* @returns {string}
*/
export function ludus(src) {
let deferred2_0;
let deferred2_1;
try {
const ptr0 = passStringToWasm0(src, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.ludus(ptr0, len0);
deferred2_0 = ret[0];
deferred2_1 = ret[1];
return getStringFromWasm0(ret[0], ret[1]);
} finally {
wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
}
}
async function __wbg_load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports);
} catch (e) {
if (module.headers.get('Content-Type') != 'application/wasm') {
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
} else {
throw e;
}
}
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return { instance, module };
} else {
return instance;
}
}
}
function __wbg_get_imports() {
const imports = {};
imports.wbg = {};
imports.wbg.__wbindgen_init_externref_table = function() {
const table = wasm.__wbindgen_export_0;
const offset = table.grow(4);
table.set(0, undefined);
table.set(offset + 0, undefined);
table.set(offset + 1, null);
table.set(offset + 2, true);
table.set(offset + 3, false);
;
};
return imports;
}
function __wbg_init_memory(imports, memory) {
}
function __wbg_finalize_init(instance, module) {
wasm = instance.exports;
__wbg_init.__wbindgen_wasm_module = module;
cachedUint8ArrayMemory0 = null;
wasm.__wbindgen_start();
return wasm;
}
function initSync(module) {
if (wasm !== undefined) return wasm;
if (typeof module !== 'undefined') {
if (Object.getPrototypeOf(module) === Object.prototype) {
({module} = module)
} else {
console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
}
}
const imports = __wbg_get_imports();
__wbg_init_memory(imports);
if (!(module instanceof WebAssembly.Module)) {
module = new WebAssembly.Module(module);
}
const instance = new WebAssembly.Instance(module, imports);
return __wbg_finalize_init(instance, module);
}
async function __wbg_init(module_or_path) {
if (wasm !== undefined) return wasm;
if (typeof module_or_path !== 'undefined') {
if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
({module_or_path} = module_or_path)
} else {
console.warn('using deprecated parameters for the initialization function; pass a single object instead')
}
}
if (typeof module_or_path === 'undefined') {
module_or_path = new URL('rudus_bg.wasm', import.meta.url);
}
const imports = __wbg_get_imports();
if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
module_or_path = fetch(module_or_path);
}
__wbg_init_memory(imports);
const { instance, module } = await __wbg_load(await module_or_path, imports);
return __wbg_finalize_init(instance, module);
}
export { initSync };
export default __wbg_init;

Binary file not shown.

9
rudus_bg.wasm.d.ts vendored
View File

@ -1,9 +0,0 @@
/* tslint:disable */
/* eslint-disable */
export const memory: WebAssembly.Memory;
export const ludus: (a: number, b: number) => [number, number];
export const __wbindgen_export_0: WebAssembly.Table;
export const __wbindgen_malloc: (a: number, b: number) => number;
export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
export const __wbindgen_free: (a: number, b: number, c: number) => void;
export const __wbindgen_start: () => void;

34
sandbox.ld Normal file
View File

@ -0,0 +1,34 @@
fn inputter () -> {
if do input > unbox > empty?
then {
yield! ()
inputter ()
}
else receive {
(:get, pid) -> send (pid, (:reply, unbox (input)))
(:flush, pid) -> {
send (pid, (:reply, unbox (input)))
store! (input, "")
}
(:clear) -> store! (input, "")
}
}
fn clear_input () -> store! (input, "")
fn read_input () -> {
let reader = spawn! (inputter)
send (reader, (:get, self ()))
receive {
(:reply, msg) -> msg
}
}
fn flush_input () -> {
let reader = spawn! (inputter)
send (reader, (:flush, self ()))
receive {
(:reply, msg) -> msg
}
}

444
sandbox_run.txt Normal file
View File

@ -0,0 +1,444 @@
entering world loop; active process is axolotl_0
closing over in type at 1: #{:sin fn sin/base, ...
closing over in eq? at 1: #{:sin fn sin/base, ...
closing over in eq? at 2: fn eq?
closing over in first at 1: #{:sin fn sin/base, ...
closing over in rest at 1: #{:sin fn sin/base, ...
closing over in inc at 1: #{:sin fn sin/base, ...
closing over in dec at 1: #{:sin fn sin/base, ...
closing over in count at 1: #{:sin fn sin/base, ...
closing over in any? at 1: fn empty?
closing over in any? at 2: fn not
closing over in list at 1: #{:sin fn sin/base, ...
closing over in append at 1: #{:sin fn sin/base, ...
closing over in fold at 1: fn fold
closing over in fold at 2: fn first
closing over in fold at 3: fn rest
closing over in foldr at 1: fn foldr
closing over in foldr at 2: fn first
closing over in foldr at 3: fn rest
closing over in map at 1: fn map
closing over in map at 2: fn append
closing over in map at 3: fn fold
closing over in filter at 1: fn filter
closing over in filter at 2: fn append
closing over in filter at 3: fn fold
closing over in keep at 1: fn some?
closing over in keep at 2: fn filter
closing over in concat at 1: #{:sin fn sin/base, ...
closing over in concat at 2: fn concat
closing over in concat at 3: fn fold
closing over in contains? at 1: fn first
closing over in contains? at 2: fn eq?
closing over in contains? at 3: fn rest
closing over in unbox at 1: #{:sin fn sin/base, ...
closing over in store! at 1: #{:sin fn sin/base, ...
closing over in update! at 1: fn unbox
closing over in update! at 2: fn store!
closing over in show at 1: #{:sin fn sin/base, ...
closing over in string at 1: fn show
closing over in string at 2: fn string
closing over in string at 3: fn concat
closing over in join at 1: fn join
closing over in join at 2: fn concat
closing over in join at 3: fn fold
closing over in split at 1: #{:sin fn sin/base, ...
closing over in trim at 1: #{:sin fn sin/base, ...
closing over in upcase at 1: #{:sin fn sin/base, ...
closing over in downcase at 1: #{:sin fn sin/base, ...
closing over in chars at 1: #{:sin fn sin/base, ...
closing over in chars/safe at 1: #{:sin fn sin/base, ...
closing over in strip at 1: fn strip
closing over in words at 1: fn strip
closing over in words at 2: fn split
closing over in words at 3: fn empty?
closing over in words at 4: fn append
closing over in words at 5: fn fold
closing over in sentence at 1: fn join
closing over in to_number at 1: #{:sin fn sin/base, ...
closing over in print! at 1: fn string
closing over in print! at 2: fn map
closing over in print! at 3: fn join
closing over in print! at 4: #{:sin fn sin/base, ...
closing over in print! at 5: box { [] }
closing over in print! at 6: fn append
closing over in print! at 7: fn update!
closing over in report! at 1: fn print!
closing over in report! at 2: fn show
closing over in report! at 3: fn concat
closing over in doc! at 1: #{:sin fn sin/base, ...
closing over in doc! at 2: fn print!
closing over in add at 1: #{:sin fn sin/base, ...
closing over in add at 2: fn add
closing over in add at 3: fn fold
closing over in sub at 1: #{:sin fn sin/base, ...
closing over in sub at 2: fn sub
closing over in sub at 3: fn fold
closing over in mult at 1: #{:sin fn sin/base, ...
closing over in mult at 2: fn mult
closing over in mult at 3: fn fold
closing over in div at 1: #{:sin fn sin/base, ...
closing over in div at 2: fn mult
closing over in div at 3: fn fold
closing over in div at 4: fn div
closing over in div/0 at 1: #{:sin fn sin/base, ...
closing over in div/0 at 2: fn mult
closing over in div/0 at 3: fn fold
closing over in div/0 at 4: fn div/0
closing over in div/safe at 1: fn div
closing over in div/safe at 2: fn mult
closing over in div/safe at 3: fn fold
closing over in div/safe at 4: fn div/safe
closing over in inv at 1: fn div
closing over in inv/0 at 1: fn div/0
closing over in inv/safe at 1: fn div/safe
closing over in neg at 1: fn mult
closing over in gt? at 1: #{:sin fn sin/base, ...
closing over in gte? at 1: #{:sin fn sin/base, ...
closing over in lt? at 1: #{:sin fn sin/base, ...
closing over in lte? at 1: #{:sin fn sin/base, ...
closing over in between? at 1: fn gte?
closing over in between? at 2: fn lt?
closing over in neg? at 1: fn lt?
closing over in pos? at 1: fn gt?
closing over in abs at 1: fn neg?
closing over in abs at 2: fn mult
closing over in turn/deg at 1: fn mult
closing over in deg/turn at 1: fn div
closing over in turn/rad at 1: 6.283185307179586
closing over in turn/rad at 2: fn mult
closing over in rad/turn at 1: 6.283185307179586
closing over in rad/turn at 2: fn div
closing over in deg/rad at 1: 6.283185307179586
closing over in deg/rad at 2: fn div
closing over in deg/rad at 3: fn mult
closing over in rad/deg at 1: 6.283185307179586
closing over in rad/deg at 2: fn div
closing over in rad/deg at 3: fn mult
closing over in sin at 1: fn turn/rad
closing over in sin at 2: #{:sin fn sin/base, ...
closing over in sin at 3: fn deg/rad
closing over in cos at 1: fn turn/rad
closing over in cos at 2: #{:sin fn sin/base, ...
closing over in cos at 3: fn deg/rad
closing over in tan at 1: fn turn/rad
closing over in tan at 2: #{:sin fn sin/base, ...
closing over in tan at 3: fn deg/rad
closing over in rotate at 1: fn rotate
closing over in rotate at 2: fn cos
closing over in rotate at 3: fn mult
closing over in rotate at 4: fn sin
closing over in rotate at 5: fn sub
closing over in rotate at 6: fn add
closing over in atan/2 at 1: #{:sin fn sin/base, ...
closing over in atan/2 at 2: fn rad/turn
closing over in atan/2 at 3: fn atan/2
closing over in atan/2 at 4: fn rad/deg
closing over in angle at 1: fn atan/2
closing over in angle at 2: fn sub
closing over in mod at 1: #{:sin fn sin/base, ...
closing over in mod/0 at 1: #{:sin fn sin/base, ...
closing over in mod/safe at 1: #{:sin fn sin/base, ...
closing over in even? at 1: fn mod
closing over in even? at 2: fn eq?
closing over in odd? at 1: fn mod
closing over in odd? at 2: fn eq?
closing over in square at 1: fn mult
closing over in sqrt at 1: fn neg?
closing over in sqrt at 2: fn not
closing over in sqrt at 3: #{:sin fn sin/base, ...
closing over in sqrt/safe at 1: fn neg?
closing over in sqrt/safe at 2: fn not
closing over in sqrt/safe at 3: #{:sin fn sin/base, ...
closing over in sum_of_squares at 1: fn square
closing over in sum_of_squares at 2: fn add
closing over in sum_of_squares at 3: fn sum_of_squares
closing over in sum_of_squares at 4: fn fold
closing over in dist at 1: fn sum_of_squares
closing over in dist at 2: fn sqrt
closing over in dist at 3: fn dist
closing over in heading/vector at 1: fn neg
closing over in heading/vector at 2: fn add
closing over in heading/vector at 3: fn cos
closing over in heading/vector at 4: fn sin
closing over in floor at 1: #{:sin fn sin/base, ...
closing over in ceil at 1: #{:sin fn sin/base, ...
closing over in round at 1: #{:sin fn sin/base, ...
closing over in range at 1: #{:sin fn sin/base, ...
closing over in at at 1: #{:sin fn sin/base, ...
closing over in second at 1: fn ordered?
closing over in second at 2: fn at
closing over in last at 1: fn ordered?
closing over in last at 2: fn count
closing over in last at 3: fn dec
closing over in last at 4: fn at
closing over in slice at 1: fn slice
closing over in slice at 2: fn gte?
closing over in slice at 3: fn count
closing over in slice at 4: fn gt?
closing over in slice at 5: fn neg?
closing over in slice at 6: #{:sin fn sin/base, ...
closing over in butlast at 1: fn count
closing over in butlast at 2: fn dec
closing over in butlast at 3: fn slice
closing over in assoc at 1: #{:sin fn sin/base, ...
closing over in dissoc at 1: #{:sin fn sin/base, ...
closing over in get at 1: fn get
closing over in get at 2: #{:sin fn sin/base, ...
closing over in update at 1: fn get
closing over in update at 2: fn assoc
closing over in keys at 1: fn list
closing over in keys at 2: fn first
closing over in keys at 3: fn map
closing over in values at 1: fn list
closing over in values at 2: fn second
closing over in values at 3: fn map
closing over in has? at 1: fn has?
closing over in has? at 2: fn get
closing over in has? at 3: fn some?
closing over in dict at 1: fn assoc
closing over in dict at 2: fn fold
closing over in dict at 3: fn list
closing over in dict at 4: fn dict
closing over in each! at 1: fn each!
closing over in random at 1: #{:sin fn sin/base, ...
closing over in random at 2: fn random
closing over in random at 3: fn mult
closing over in random at 4: fn sub
closing over in random at 5: fn add
closing over in random at 6: fn count
closing over in random at 7: fn floor
closing over in random at 8: fn at
closing over in random at 9: fn keys
closing over in random at 10: fn get
closing over in random_int at 1: fn random
closing over in random_int at 2: fn floor
closing over in add_command! at 1: box { [] }
closing over in add_command! at 2: fn append
closing over in add_command! at 3: fn update!
closing over in add_command! at 4: box { #{:penwidth 1,...
closing over in add_command! at 5: fn unbox
closing over in add_command! at 6: fn apply_command
closing over in add_command! at 7: fn store!
closing over in forward! at 1: fn add_command!
closing over in back! at 1: fn add_command!
closing over in left! at 1: fn add_command!
closing over in right! at 1: fn add_command!
closing over in penup! at 1: fn add_command!
closing over in pendown! at 1: fn add_command!
closing over in pencolor! at 1: fn add_command!
closing over in penwidth! at 1: fn add_command!
closing over in background! at 1: fn add_command!
closing over in home! at 1: fn add_command!
closing over in clear! at 1: fn add_command!
closing over in goto! at 1: fn add_command!
closing over in goto! at 2: fn goto!
closing over in setheading! at 1: fn add_command!
closing over in showturtle! at 1: fn add_command!
closing over in hideturtle! at 1: fn add_command!
closing over in loadstate! at 1: fn add_command!
closing over in apply_command at 1: fn assoc
closing over in apply_command at 2: fn add
closing over in apply_command at 3: fn update
closing over in apply_command at 4: fn sub
closing over in apply_command at 5: fn heading/vector
closing over in apply_command at 6: fn mult
closing over in position at 1: box { #{:penwidth 1,...
closing over in position at 2: fn unbox
closing over in heading at 1: box { #{:penwidth 1,...
closing over in heading at 2: fn unbox
closing over in pendown? at 1: box { #{:penwidth 1,...
closing over in pendown? at 2: fn unbox
closing over in pencolor at 1: box { #{:penwidth 1,...
closing over in pencolor at 2: fn unbox
closing over in penwidth at 1: box { #{:penwidth 1,...
closing over in penwidth at 2: fn unbox
closing over in self at 1: #{:sin fn sin/base, ...
closing over in send at 1: #{:sin fn sin/base, ...
closing over in spawn! at 1: #{:sin fn sin/base, ...
closing over in yield! at 1: #{:sin fn sin/base, ...
closing over in alive? at 1: #{:sin fn sin/base, ...
closing over in link! at 1: fn link!
closing over in link! at 2: #{:sin fn sin/base, ...
closing over in msgs at 1: #{:sin fn sin/base, ...
closing over in flush! at 1: #{:sin fn sin/base, ...
closing over in flush_i! at 1: #{:sin fn sin/base, ...
closing over in sleep! at 1: #{:sin fn sin/base, ...
yielded from axolotl_0
***match clause: : (:set, x)
binding `x` in sandbox
stack depth: 3; match depth: 0
at stack index: 2
new locals: x@2//1
resolving binding `x` in sandbox
locals: x@2//1
at locals position 2
leaving scope 1
releasing binding x@2//1
leaving scope 0
***leaving block before pop stack depth: 1
popping back from 1 to 0
=== source code ===
& fn receive (receiver) -> {
& fn looper {
& ([], _) -> yield! ()
& (xs, i) -> {
& print!("looping through messages:", xs)
& match receiver (first (xs), i) with {
& :does_not_understand -> looper (rest (xs), inc (i))
& x -> x
& }}
& }
& print! ("receiving in", self (), "with messages", msgs())
& looper (msgs (), 0)
& }
& fn agent (x) -> receive (fn (msg, i) -> {
& print!("received msg in agent: ", msg)
& match msg with {
& (:get, pid) -> {
& flush_i! (i)
& print!("getted from {pid}")
& send (pid, (:response, x))
& agent (x)
& }
& (:set, y) -> {flush_i!(i); print!("setted! {y}"); agent (y)}
& (:update, f) -> {flush_i!(i);print!("updated: {f}"); agent (f (x))}
& y -> {print!("no agent reception match!!!! {y}");:does_not_understand}
& }
& })
& fn agent/get (pid) -> {
& send (pid, (:get, self ()))
& yield! ()
& receive (fn (msg, i) -> match msg with {
& (:response, x) -> {flush_i! (i); x}
& })
& }
& fn agent/set (pid, val) -> send (pid, (:set, val))
& fn agent/update (pid, f) -> send (pid, (:update, f))
& let counter = spawn! (fn () -> agent (0))
& agent/set (counter, 12)
match (:set, 12) with {
(:set, x) -> x
}
=== chunk: sandbox ===
IDX | CODE | INFO
0000: constant 00000: :set
0003: constant 00001: 12
0006: push_tuple 002
0008: ***match clause: : (:set, x)
0010: match_tuple 002
0012: jump_if_no_match 00028
0015: load_tuple
0016: match_depth 001
0018: match_constant 00000: :set
0021: jump_if_no_match 00017
0024: match_depth 000
0026: match
0027: binding `x` in sandbox
0029: stack depth: 3; match depth: 0
0031: at stack index: 2
0033: new locals: x@2//1
0035: jump_if_no_match 00003
0038: jump 00002
0041: pop_n 002
0043: jump_if_no_match 00016
0046: resolving binding `x` in sandbox
locals: x@2//1
0048: at locals position 2
0050: push_binding 002
0052: store
0053: leaving scope 1
0055: releasing binding x@2//1
0057: pop_n 002
0059: jump 00001
0062: panic_no_match
0063: load
0064: store
0065: leaving scope 0
0067: ***leaving block before pop stack depth: 1
0069: popping back from 1 to 0
0071: pop
0072: load
=== vm run ===
entering world loop; active process is cormorant_0
0000: [] (_,_,_,_,_,_,_,_) cormorant_0 {}
0000: constant 00000: :set
0003: [->:set<-] (_,_,_,_,_,_,_,_) cormorant_0 {}
0003: constant 00001: 12
0006: [->:set<-|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0006: push_tuple 002
0008: [->(:set, 12)<-] (_,_,_,_,_,_,_,_) cormorant_0 {}
0008: ***match clause: : (:set, x)
0010: [->(:set, 12)<-] (_,_,_,_,_,_,_,_) cormorant_0 {}
0010: match_tuple 002
0012: [->(:set, 12)<-] (_,_,_,_,_,_,_,_) cormorant_0 {}
0012: jump_if_no_match 00028
0015: [->(:set, 12)<-] (_,_,_,_,_,_,_,_) cormorant_0 {}
0015: load_tuple
0016: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0016: match_depth 001
0018: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0018: match_constant 00000: :set
0021: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0021: jump_if_no_match 00017
0024: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0024: match_depth 000
0026: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0026: match
0027: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0027: binding `x` in sandbox
0029: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0029: stack depth: 3; match depth: 0
0031: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0031: at stack index: 2
0033: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0033: new locals: x@2//1
0035: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0035: jump_if_no_match 00003
0038: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0038: jump 00002
0043: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0043: jump_if_no_match 00016
0046: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0046: resolving binding `x` in sandbox
locals: x@2//1
0048: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0048: at locals position 2
0050: [->(:set, 12)<-|:set|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0050: push_binding 002
0052: [->(:set, 12)<-|:set|12|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0052: store
0053: [->(:set, 12)<-|:set|12] (12,_,_,_,_,_,_,_) cormorant_0 {}
0053: leaving scope 1
0055: [->(:set, 12)<-|:set|12] (12,_,_,_,_,_,_,_) cormorant_0 {}
0055: releasing binding x@2//1
0057: [->(:set, 12)<-|:set|12] (12,_,_,_,_,_,_,_) cormorant_0 {}
0057: pop_n 002
0059: [->(:set, 12)<-] (12,_,_,_,_,_,_,_) cormorant_0 {}
0059: jump 00001
0063: [->(:set, 12)<-] (12,_,_,_,_,_,_,_) cormorant_0 {}
0063: load
0064: [->(:set, 12)<-|12] (_,_,_,_,_,_,_,_) cormorant_0 {}
0064: store
0065: [->(:set, 12)<-] (12,_,_,_,_,_,_,_) cormorant_0 {}
0065: leaving scope 0
0067: [->(:set, 12)<-] (12,_,_,_,_,_,_,_) cormorant_0 {}
0067: ***leaving block before pop stack depth: 1
0069: [->(:set, 12)<-] (12,_,_,_,_,_,_,_) cormorant_0 {}
0069: popping back from 1 to 0
0071: [->(:set, 12)<-] (12,_,_,_,_,_,_,_) cormorant_0 {}
0071: pop
0072: [] (12,_,_,_,_,_,_,_) cormorant_0 {}
0072: load
yielded from cormorant_0
{"result":"12","io":{"stdout":{"proto":["text-stream","0.1.0"],"data":""},"turtle":{"proto":["turtle-graphics","0.1.0"],"data":[]}}}

249
scratch/first.txt Normal file
View File

@ -0,0 +1,249 @@
=== vm run: test ===
0000: [] (_,_,_,_,_,_,_,_)
0000: reset_match
0001: [] (_,_,_,_,_,_,_,_)
0001: constant 00000: 2
0004: [->2<-] (_,_,_,_,_,_,_,_)
0004: match
0005: [->2<-] (_,_,_,_,_,_,_,_)
0005: panic_if_no_match
0006: [->2<-] (_,_,_,_,_,_,_,_)
0006: push_list
0007: [->2<-|[]] (_,_,_,_,_,_,_,_)
0007: constant 00001: 1
0010: [->2<-|[]|1] (_,_,_,_,_,_,_,_)
0010: append_list
0011: [->2<-|[1]] (_,_,_,_,_,_,_,_)
0011: constant 00000: 2
0014: [->2<-|[1]|2] (_,_,_,_,_,_,_,_)
0014: append_list
0015: [->2<-|[1, 2]] (_,_,_,_,_,_,_,_)
0015: constant 00002: 3
0018: [->2<-|[1, 2]|3] (_,_,_,_,_,_,_,_)
0018: append_list
0019: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0019: ***entering loop with stack depth of 2
0021: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0021: store_n 001
0023: [->2<-] ([1, 2, 3],_,_,_,_,_,_,_)
0023: ***after store, stack depth is now 2
0025: [->2<-] ([1, 2, 3],_,_,_,_,_,_,_)
0025: load
0026: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0026: ***after load, stack depth is now 2
0028: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0028: reset_match
0029: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0029: match_depth 000
0031: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0031: match_list 000
0033: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0033: jump_if_no_match 00006
0042: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0042: jump_if_no_match 00010
0055: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0055: reset_match
0056: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0056: match_depth 000
0058: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0058: match_list 001
0060: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0060: jump_if_no_match 00012
0075: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0075: jump_if_no_match 00030
0108: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0108: reset_match
0109: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0109: match_depth 000
0111: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0111: match_splatted_list 002
0113: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0113: jump_if_no_match 00019
0116: [->2<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0116: load_splatted_list 002
0118: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0118: match_depth 001
0120: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0120: match
0121: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0121: jump_if_no_match 00010
0124: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0124: match_depth 000
0126: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0126: match
0127: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0127: jump_if_no_match 00004
0130: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0130: jump 00002
0135: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0135: jump_if_no_match 00068
0138: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0138: ***before visiting body, the stack depth is 4
0140: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0140: ***calling function eq? stack depth: 4
0142: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0142: ***calling function first stack depth: 4
0144: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0144: resolving binding `xs` in test
0146: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0146: push_binding 003
0148: [->2<-|[1, 2, 3]|1|[2, 3]|[2, 3]] (_,_,_,_,_,_,_,_)
0148: resolving binding `first` in test
0150: [->2<-|[1, 2, 3]|1|[2, 3]|[2, 3]] (_,_,_,_,_,_,_,_)
0150: constant 00004: :first
0153: [->2<-|[1, 2, 3]|1|[2, 3]|[2, 3]|:first] (_,_,_,_,_,_,_,_)
0153: push_global
0154: [->2<-|[1, 2, 3]|1|[2, 3]|[2, 3]|fn first] (_,_,_,_,_,_,_,_)
0154: ***after 1 args stack depth: 6
0156: [->2<-|[1, 2, 3]|1|[2, 3]|[2, 3]|fn first] (_,_,_,_,_,_,_,_)
0156: call 001
=== calling into fn first/1 ===
0000: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0000: reset_match
0001: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0001: match_depth 000
0003: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0003: match_list 000
0005: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0005: jump_if_no_match 00006
0014: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0014: jump_if_no_match 00003
0020: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0020: jump_if_no_match 00005
0028: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0028: match_depth 000
0030: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0030: constant 00000: :list
0033: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|:list] (_,_,_,_,_,_,_,_)
0033: match_type
0034: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0034: jump_if_no_match 00003
0037: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0037: jump 00000
0040: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0040: jump_if_no_match 00024
0043: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0043: ***accessing keyword: base :first stack depth: 1
0045: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0045: resolving binding `base` in first
0047: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0047: get_upvalue 000
0049: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|#{:rest fn rest/base...] (_,_,_,_,_,_,_,_)
0049: constant 00001: :first
0052: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|#{:rest fn rest/base...|:first] (_,_,_,_,_,_,_,_)
0052: get_key
0053: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|fn first/base] (_,_,_,_,_,_,_,_)
0053: ***after keyword access stack depth: 2
0055: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|fn first/base] (_,_,_,_,_,_,_,_)
0055: stash
0056: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|fn first/base] (fn first/base,_,_,_,_,_,_,_)
0056: pop
0057: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (fn first/base,_,_,_,_,_,_,_)
0057: resolving binding `xs` in first
0059: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (fn first/base,_,_,_,_,_,_,_)
0059: push_binding 000
0061: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|[2, 3]] (fn first/base,_,_,_,_,_,_,_)
0061: load
0062: [2|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|[2, 3]|fn first/base] (_,_,_,_,_,_,_,_)
0062: tail_call 001
=== tail call into fn first/base/1 from first ===
0158: [->2<-|[1, 2, 3]|1|[2, 3]|2] (_,_,_,_,_,_,_,_)
0158: resolving binding `test` in test
0160: [->2<-|[1, 2, 3]|1|[2, 3]|2] (_,_,_,_,_,_,_,_)
0160: push_binding 000
0162: [->2<-|[1, 2, 3]|1|[2, 3]|2|2] (_,_,_,_,_,_,_,_)
0162: resolving binding `eq?` in test
0164: [->2<-|[1, 2, 3]|1|[2, 3]|2|2] (_,_,_,_,_,_,_,_)
0164: constant 00003: :eq?
0167: [->2<-|[1, 2, 3]|1|[2, 3]|2|2|:eq?] (_,_,_,_,_,_,_,_)
0167: push_global
0168: [->2<-|[1, 2, 3]|1|[2, 3]|2|2|fn eq?] (_,_,_,_,_,_,_,_)
0168: ***after 2 args stack depth: 7
0170: [->2<-|[1, 2, 3]|1|[2, 3]|2|2|fn eq?] (_,_,_,_,_,_,_,_)
0170: call 002
=== calling into fn eq?/2 ===
0000: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0000: reset_match
0001: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0001: match_depth 001
0003: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0003: match
0004: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0004: jump_if_no_match 00009
0007: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0007: match_depth 000
0009: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0009: match
0010: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0010: jump_if_no_match 00003
0013: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0013: jump 00000
0016: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0016: jump_if_no_match 00029
0019: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0019: ***accessing keyword: base :eq? stack depth: 2
0021: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0021: resolving binding `base` in eq?
0023: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (_,_,_,_,_,_,_,_)
0023: get_upvalue 000
0025: [2|[1, 2, 3]|1|[2, 3]|->2<-|2|#{:rest fn rest/base...] (_,_,_,_,_,_,_,_)
0025: constant 00000: :eq?
0028: [2|[1, 2, 3]|1|[2, 3]|->2<-|2|#{:rest fn rest/base...|:eq?] (_,_,_,_,_,_,_,_)
0028: get_key
0029: [2|[1, 2, 3]|1|[2, 3]|->2<-|2|fn eq?/base] (_,_,_,_,_,_,_,_)
0029: ***after keyword access stack depth: 3
0031: [2|[1, 2, 3]|1|[2, 3]|->2<-|2|fn eq?/base] (_,_,_,_,_,_,_,_)
0031: stash
0032: [2|[1, 2, 3]|1|[2, 3]|->2<-|2|fn eq?/base] (fn eq?/base,_,_,_,_,_,_,_)
0032: pop
0033: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (fn eq?/base,_,_,_,_,_,_,_)
0033: resolving binding `x` in eq?
0035: [2|[1, 2, 3]|1|[2, 3]|->2<-|2] (fn eq?/base,_,_,_,_,_,_,_)
0035: push_binding 000
0037: [2|[1, 2, 3]|1|[2, 3]|->2<-|2|2] (fn eq?/base,_,_,_,_,_,_,_)
0037: resolving binding `y` in eq?
0039: [2|[1, 2, 3]|1|[2, 3]|->2<-|2|2] (fn eq?/base,_,_,_,_,_,_,_)
0039: push_binding 001
0041: [2|[1, 2, 3]|1|[2, 3]|->2<-|2|2|2] (fn eq?/base,_,_,_,_,_,_,_)
0041: load
0042: [2|[1, 2, 3]|1|[2, 3]|->2<-|2|2|2|fn eq?/base] (_,_,_,_,_,_,_,_)
0042: tail_call 002
=== tail call into fn eq?/base/2 from eq? ===
0172: [->2<-|[1, 2, 3]|1|[2, 3]|true] (_,_,_,_,_,_,_,_)
0172: jump_if_false 00004
0175: [->2<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0175: true
0176: [->2<-|[1, 2, 3]|1|[2, 3]|true] (_,_,_,_,_,_,_,_)
0176: jump 00018
0197: [->2<-|[1, 2, 3]|1|[2, 3]|true] (_,_,_,_,_,_,_,_)
0197: ***after visiting loop body, the stack depth is 5
0199: [->2<-|[1, 2, 3]|1|[2, 3]|true] (_,_,_,_,_,_,_,_)
0199: store
0200: [->2<-|[1, 2, 3]|1|[2, 3]|_] (true,_,_,_,_,_,_,_)
0200: pop
0201: [->2<-|[1, 2, 3]|1|[2, 3]] (true,_,_,_,_,_,_,_)
0201: pop
0202: [->2<-|[1, 2, 3]|1] (true,_,_,_,_,_,_,_)
0202: pop
0203: [->2<-|[1, 2, 3]] (true,_,_,_,_,_,_,_)
0203: jump 00001
0207: [->2<-|[1, 2, 3]] (true,_,_,_,_,_,_,_)
0207: load
0208: [->2<-|[1, 2, 3]|true] (_,_,_,_,_,_,_,_)
0208: store
0209: [->2<-|[1, 2, 3]|_] (true,_,_,_,_,_,_,_)
0209: pop_n 002
0211: [->2<-] (true,_,_,_,_,_,_,_)
0211: load
0212: [->2<-] (_,_,_,_,_,_,_,_)
true
**********
**********

291
scratch/second.txt Normal file
View File

@ -0,0 +1,291 @@
=== vm run: test ===
0000: [] (_,_,_,_,_,_,_,_)
0000: reset_match
0001: [] (_,_,_,_,_,_,_,_)
0001: constant 00000: 4
0004: [->4<-] (_,_,_,_,_,_,_,_)
0004: match
0005: [->4<-] (_,_,_,_,_,_,_,_)
0005: panic_if_no_match
0006: [->4<-] (_,_,_,_,_,_,_,_)
0006: push_list
0007: [->4<-|[]] (_,_,_,_,_,_,_,_)
0007: constant 00001: 1
0010: [->4<-|[]|1] (_,_,_,_,_,_,_,_)
0010: append_list
0011: [->4<-|[1]] (_,_,_,_,_,_,_,_)
0011: constant 00002: 2
0014: [->4<-|[1]|2] (_,_,_,_,_,_,_,_)
0014: append_list
0015: [->4<-|[1, 2]] (_,_,_,_,_,_,_,_)
0015: constant 00003: 3
0018: [->4<-|[1, 2]|3] (_,_,_,_,_,_,_,_)
0018: append_list
0019: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0019: ***entering loop with stack depth of 2
0021: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0021: store_n 001
0023: [->4<-] ([1, 2, 3],_,_,_,_,_,_,_)
0023: ***after store, stack depth is now 2
0025: [->4<-] ([1, 2, 3],_,_,_,_,_,_,_)
0025: load
0026: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0026: ***after load, stack depth is now 2
0028: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0028: reset_match
0029: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0029: match_depth 000
0031: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0031: match_list 000
0033: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0033: jump_if_no_match 00006
0042: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0042: jump_if_no_match 00010
0055: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0055: reset_match
0056: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0056: match_depth 000
0058: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0058: match_list 001
0060: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0060: jump_if_no_match 00012
0075: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0075: jump_if_no_match 00030
0108: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0108: reset_match
0109: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0109: match_depth 000
0111: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0111: match_splatted_list 002
0113: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0113: jump_if_no_match 00019
0116: [->4<-|[1, 2, 3]] (_,_,_,_,_,_,_,_)
0116: load_splatted_list 002
0118: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0118: match_depth 001
0120: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0120: match
0121: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0121: jump_if_no_match 00010
0124: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0124: match_depth 000
0126: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0126: match
0127: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0127: jump_if_no_match 00004
0130: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0130: jump 00002
0135: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0135: jump_if_no_match 00068
0138: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0138: ***before visiting body, the stack depth is 4
0140: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0140: ***calling function eq? stack depth: 4
0142: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0142: ***calling function first stack depth: 4
0144: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0144: resolving binding `xs` in test
0146: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0146: push_binding 003
0148: [->4<-|[1, 2, 3]|1|[2, 3]|[2, 3]] (_,_,_,_,_,_,_,_)
0148: resolving binding `first` in test
0150: [->4<-|[1, 2, 3]|1|[2, 3]|[2, 3]] (_,_,_,_,_,_,_,_)
0150: constant 00005: :first
0153: [->4<-|[1, 2, 3]|1|[2, 3]|[2, 3]|:first] (_,_,_,_,_,_,_,_)
0153: push_global
0154: [->4<-|[1, 2, 3]|1|[2, 3]|[2, 3]|fn first] (_,_,_,_,_,_,_,_)
0154: ***after 1 args stack depth: 6
0156: [->4<-|[1, 2, 3]|1|[2, 3]|[2, 3]|fn first] (_,_,_,_,_,_,_,_)
0156: call 001
=== calling into fn first/1 ===
0000: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0000: reset_match
0001: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0001: match_depth 000
0003: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0003: match_list 000
0005: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0005: jump_if_no_match 00006
0014: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0014: jump_if_no_match 00003
0020: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0020: jump_if_no_match 00005
0028: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0028: match_depth 000
0030: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0030: constant 00000: :list
0033: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|:list] (_,_,_,_,_,_,_,_)
0033: match_type
0034: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0034: jump_if_no_match 00003
0037: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0037: jump 00000
0040: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0040: jump_if_no_match 00024
0043: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0043: ***accessing keyword: base :first stack depth: 1
0045: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0045: resolving binding `base` in first
0047: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (_,_,_,_,_,_,_,_)
0047: get_upvalue 000
0049: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|#{:append fn append/...] (_,_,_,_,_,_,_,_)
0049: constant 00001: :first
0052: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|#{:append fn append/...|:first] (_,_,_,_,_,_,_,_)
0052: get_key?
0053: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|fn first/base] (_,_,_,_,_,_,_,_)
0053: ***after keyword access stack depth: 2
0055: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|fn first/base] (_,_,_,_,_,_,_,_)
0055: stash
0056: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|fn first/base] (fn first/base,_,_,_,_,_,_,_)
0056: pop
0057: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (fn first/base,_,_,_,_,_,_,_)
0057: resolving binding `xs` in first
0059: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-] (fn first/base,_,_,_,_,_,_,_)
0059: push_binding 000
0061: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|[2, 3]] (fn first/base,_,_,_,_,_,_,_)
0061: load
0062: [4|[1, 2, 3]|1|[2, 3]|->[2, 3]<-|[2, 3]|fn first/base] (_,_,_,_,_,_,_,_)
0062: tail_call 001
=== tail call into fn first/base/1 from first ===
0158: [->4<-|[1, 2, 3]|1|[2, 3]|2] (_,_,_,_,_,_,_,_)
0158: resolving binding `test` in test
0160: [->4<-|[1, 2, 3]|1|[2, 3]|2] (_,_,_,_,_,_,_,_)
0160: push_binding 000
0162: [->4<-|[1, 2, 3]|1|[2, 3]|2|4] (_,_,_,_,_,_,_,_)
0162: resolving binding `eq?` in test
0164: [->4<-|[1, 2, 3]|1|[2, 3]|2|4] (_,_,_,_,_,_,_,_)
0164: constant 00004: :eq?
0167: [->4<-|[1, 2, 3]|1|[2, 3]|2|4|:eq?] (_,_,_,_,_,_,_,_)
0167: push_global
0168: [->4<-|[1, 2, 3]|1|[2, 3]|2|4|fn eq?] (_,_,_,_,_,_,_,_)
0168: ***after 2 args stack depth: 7
0170: [->4<-|[1, 2, 3]|1|[2, 3]|2|4|fn eq?] (_,_,_,_,_,_,_,_)
0170: call 002
=== calling into fn eq?/2 ===
0000: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0000: reset_match
0001: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0001: match_depth 001
0003: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0003: match
0004: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0004: jump_if_no_match 00009
0007: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0007: match_depth 000
0009: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0009: match
0010: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0010: jump_if_no_match 00003
0013: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0013: jump 00000
0016: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0016: jump_if_no_match 00029
0019: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0019: ***accessing keyword: base :eq? stack depth: 2
0021: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0021: resolving binding `base` in eq?
0023: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (_,_,_,_,_,_,_,_)
0023: get_upvalue 000
0025: [4|[1, 2, 3]|1|[2, 3]|->2<-|4|#{:append fn append/...] (_,_,_,_,_,_,_,_)
0025: constant 00000: :eq?
0028: [4|[1, 2, 3]|1|[2, 3]|->2<-|4|#{:append fn append/...|:eq?] (_,_,_,_,_,_,_,_)
0028: get_key
0029: [4|[1, 2, 3]|1|[2, 3]|->2<-|4|fn eq?/base] (_,_,_,_,_,_,_,_)
0029: ***after keyword access stack depth: 3
0031: [4|[1, 2, 3]|1|[2, 3]|->2<-|4|fn eq?/base] (_,_,_,_,_,_,_,_)
0031: stash
0032: [4|[1, 2, 3]|1|[2, 3]|->2<-|4|fn eq?/base] (fn eq?/base,_,_,_,_,_,_,_)
0032: pop
0033: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (fn eq?/base,_,_,_,_,_,_,_)
0033: resolving binding `x` in eq?
0035: [4|[1, 2, 3]|1|[2, 3]|->2<-|4] (fn eq?/base,_,_,_,_,_,_,_)
0035: push_binding 000
0037: [4|[1, 2, 3]|1|[2, 3]|->2<-|4|2] (fn eq?/base,_,_,_,_,_,_,_)
0037: resolving binding `y` in eq?
0039: [4|[1, 2, 3]|1|[2, 3]|->2<-|4|2] (fn eq?/base,_,_,_,_,_,_,_)
0039: push_binding 001
0041: [4|[1, 2, 3]|1|[2, 3]|->2<-|4|2|4] (fn eq?/base,_,_,_,_,_,_,_)
0041: load
0042: [4|[1, 2, 3]|1|[2, 3]|->2<-|4|2|4|fn eq?/base] (_,_,_,_,_,_,_,_)
0042: tail_call 002
=== tail call into fn eq?/base/2 from eq? ===
0172: [->4<-|[1, 2, 3]|1|[2, 3]|false] (_,_,_,_,_,_,_,_)
0172: jump_if_false 00004
0179: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0179: before visiting recur args the compiler thinks the stack depth is 5
0181: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0181: recur arg: 0
0183: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0183: resolving binding `xs` in test
0185: [->4<-|[1, 2, 3]|1|[2, 3]] (_,_,_,_,_,_,_,_)
0185: push_binding 003
0187: [->4<-|[1, 2, 3]|1|[2, 3]|[2, 3]] (_,_,_,_,_,_,_,_)
0187: after visiting recur args the compiler thinks the stack depth is 6
0189: [->4<-|[1, 2, 3]|1|[2, 3]|[2, 3]] (_,_,_,_,_,_,_,_)
0189: store_n 001
0191: [->4<-|[1, 2, 3]|1|[2, 3]] ([2, 3],_,_,_,_,_,_,_)
0191: pop_n 004
0193: [] ([2, 3],_,_,_,_,_,_,_)
0193: load
0194: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0194: jump_back 00168
0026: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0026: ***after load, stack depth is now 2
0028: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0028: reset_match
0029: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0029: match_depth 000
0031: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0031: match_list 000
0033: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0033: jump_if_no_match 00006
0042: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0042: jump_if_no_match 00010
0055: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0055: reset_match
0056: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0056: match_depth 000
0058: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0058: match_list 001
0060: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0060: jump_if_no_match 00012
0075: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0075: jump_if_no_match 00030
0108: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0108: reset_match
0109: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0109: match_depth 000
0111: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0111: match_splatted_list 002
0113: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0113: jump_if_no_match 00019
0116: [->[2, 3]<-] (_,_,_,_,_,_,_,_)
0116: load_splatted_list 002
0118: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0118: match_depth 001
0120: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0120: match
0121: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0121: jump_if_no_match 00010
0124: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0124: match_depth 000
0126: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0126: match
0127: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0127: jump_if_no_match 00004
0130: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0130: jump 00002
0135: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0135: jump_if_no_match 00068
0138: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0138: ***before visiting body, the stack depth is 4
0140: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0140: ***calling function eq? stack depth: 4
0142: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0142: ***calling function first stack depth: 4
0144: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0144: resolving binding `xs` in test
0146: [->[2, 3]<-|2|[3]] (_,_,_,_,_,_,_,_)
0146: push_binding 003
thread 'main' panicked at src/vm.rs:313:51:
index out of bounds: the len is 3 but the index is 3

470
src/ast.rs Normal file
View File

@ -0,0 +1,470 @@
use crate::spans::*;
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StringPart {
Data(String),
Word(&'static str),
Inline(String),
}
impl fmt::Display for StringPart {
fn fmt(self: &StringPart, f: &mut fmt::Formatter) -> fmt::Result {
let rep = match self {
StringPart::Word(s) => format!("{{{s}}}"),
StringPart::Data(s) => s.to_string(),
StringPart::Inline(s) => s.to_string(),
};
write!(f, "{}", rep)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Ast {
// a special Error node
// may come in handy?
Error,
And,
Or,
// expression nodes
Placeholder,
Nil,
Boolean(bool),
Number(f64),
Keyword(&'static str),
Method(&'static str, Box<Spanned<Self>>),
Word(&'static str),
String(&'static str),
Interpolated(Vec<Spanned<StringPart>>),
Block(Vec<Spanned<Self>>),
If(Box<Spanned<Self>>, Box<Spanned<Self>>, Box<Spanned<Self>>),
Tuple(Vec<Spanned<Self>>),
Arguments(Vec<Spanned<Self>>),
List(Vec<Spanned<Self>>),
Dict(Vec<Spanned<Self>>),
Let(Box<Spanned<Self>>, Box<Spanned<Self>>),
LBox(&'static str, Box<Spanned<Self>>),
Synthetic(Box<Spanned<Self>>, Box<Spanned<Self>>, Vec<Spanned<Self>>),
When(Vec<Spanned<Self>>),
WhenClause(Box<Spanned<Self>>, Box<Spanned<Self>>),
Match(Box<Spanned<Self>>, Vec<Spanned<Self>>),
Receive(Vec<Spanned<Self>>),
MatchClause(
Box<Spanned<Self>>,
Box<Option<Spanned<Self>>>,
Box<Spanned<Self>>,
),
Fn(&'static str, Box<Spanned<Ast>>, Option<&'static str>),
FnBody(Vec<Spanned<Ast>>),
FnDeclaration(&'static str),
Panic(Box<Spanned<Self>>),
Do(Vec<Spanned<Self>>),
Repeat(Box<Spanned<Self>>, Box<Spanned<Self>>),
Splat(&'static str),
StringPair(&'static str, Box<Spanned<Self>>),
KeywordPair(&'static str, Box<Spanned<Self>>),
Loop(Box<Spanned<Self>>, Vec<Spanned<Self>>),
Recur(Vec<Spanned<Self>>),
// pattern nodes
NilPattern,
BooleanPattern(bool),
NumberPattern(f64),
StringPattern(&'static str),
InterpolatedPattern(Vec<Spanned<StringPart>>),
KeywordPattern(&'static str),
WordPattern(&'static str),
AsPattern(&'static str, &'static str),
Splattern(Box<Spanned<Self>>),
PlaceholderPattern,
TuplePattern(Vec<Spanned<Self>>),
ListPattern(Vec<Spanned<Self>>),
StrPairPattern(&'static str, Box<Spanned<Self>>),
KeyPairPattern(&'static str, Box<Spanned<Self>>),
DictPattern(Vec<Spanned<Self>>),
}
impl Ast {
pub fn show(&self) -> String {
use Ast::*;
match self {
And => "and".to_string(),
Or => "or".to_string(),
Error => unreachable!(),
Nil | NilPattern => "nil".to_string(),
String(s) | StringPattern(s) => format!("\"{s}\""),
Interpolated(strs) | InterpolatedPattern(strs) => {
let mut out = "".to_string();
out = format!("\"{out}");
for (part, _) in strs {
out = format!("{out}{part}");
}
format!("{out}\"")
}
Boolean(b) | BooleanPattern(b) => b.to_string(),
Number(n) | NumberPattern(n) => n.to_string(),
Keyword(k) | KeywordPattern(k) => format!(":{k}"),
Method(m, args) => format!("::{m} {}", args.0),
Word(w) | WordPattern(w) => w.to_string(),
Block(lines) => {
let mut out = "{\n".to_string();
for (line, _) in lines {
out = format!("{out}\n {}", line.show());
}
format!("{out}\n}}")
}
If(cond, then, r#else) => format!(
"if {}\n then {}\n else {}",
cond.0.show(),
then.0.show(),
r#else.0.show()
),
Let(pattern, expression) => {
format!("let {} = {}", pattern.0.show(), expression.0.show())
}
Dict(entries) | DictPattern(entries) => {
format!(
"#{{{}}}",
entries
.iter()
.map(|(pair, _)| pair.show())
.collect::<Vec<_>>()
.join(", ")
)
}
List(members) | ListPattern(members) => format!(
"[{}]",
members
.iter()
.map(|(member, _)| member.show())
.collect::<Vec<_>>()
.join(", ")
),
Arguments(members) => format!(
"({})",
members
.iter()
.map(|(member, _)| member.show())
.collect::<Vec<_>>()
.join(", ")
),
Tuple(members) | TuplePattern(members) => format!(
"({})",
members
.iter()
.map(|(member, _)| member.show())
.collect::<Vec<_>>()
.join(", ")
),
Synthetic(root, first, rest) => format!(
"{} {} {}",
root.0.show(),
first.0.show(),
rest.iter()
.map(|(term, _)| term.show())
.collect::<Vec<_>>()
.join(" ")
),
When(clauses) | Receive(clauses) => format!(
"when {{\n {}\n}}",
clauses
.iter()
.map(|(clause, _)| clause.show())
.collect::<Vec<_>>()
.join("\n ")
),
Placeholder | PlaceholderPattern => "_".to_string(),
LBox(name, rhs) => format!("box {name} = {}", rhs.0.show()),
Match(scrutinee, clauses) => format!(
"match {} with {{\n {}\n}}",
scrutinee.0.show(),
clauses
.iter()
.map(|(clause, _)| clause.show())
.collect::<Vec<_>>()
.join("\n ")
),
FnBody(clauses) => clauses
.iter()
.map(|(clause, _)| clause.show())
.collect::<Vec<_>>()
.join("\n "),
Fn(name, body, doc) => {
let mut out = format!("fn {name} {{\n");
if let Some(doc) = doc {
out = format!("{out} {doc}\n");
}
format!("{out} {}\n}}", body.0.show())
}
FnDeclaration(name) => format!("fn {name}"),
Panic(expr) => format!("panic! {}", expr.0.show()),
Do(terms) => {
format!(
"do {}",
terms
.iter()
.map(|(term, _)| term.show())
.collect::<Vec<_>>()
.join(" > ")
)
}
Repeat(times, body) => format!("repeat {} {{\n{}\n}}", times.0.show(), body.0.show()),
Splat(word) => format!("...{}", word),
Splattern(pattern) => format!("...{}", pattern.0.show()),
AsPattern(word, type_keyword) => format!("{word} as :{type_keyword}"),
KeywordPair(key, value) | KeyPairPattern(key, value) => {
format!(":{key} {}", value.0.show())
}
StringPair(key, value) | StrPairPattern(key, value) => {
format!("\"{key}\" {}", value.0.show())
}
Loop(init, body) => format!(
"loop {} with {{\n {}\n}}",
init.0.show(),
body.iter()
.map(|(clause, _)| clause.show())
.collect::<Vec<_>>()
.join("\n ")
),
Recur(args) => format!(
"recur ({})",
args.iter()
.map(|(arg, _)| arg.show())
.collect::<Vec<_>>()
.join(", ")
),
MatchClause(pattern, guard, body) => {
let mut out = pattern.0.show();
if let Some(guard) = guard.as_ref() {
out = format!("{out} if {}", guard.0.show());
}
format!("{out} -> {}", body.0.show())
}
WhenClause(cond, body) => format!("{} -> {}", cond.0.show(), body.0.show()),
}
}
}
impl fmt::Display for Ast {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use Ast::*;
match self {
And => write!(f, "And"),
Or => write!(f, "Or"),
Error => write!(f, "Error"),
Nil => write!(f, "nil"),
String(s) => write!(f, "String: \"{}\"", s),
Interpolated(strs) => {
write!(
f,
"Interpolated: \"{}\"",
strs.iter()
.map(|(s, _)| s.to_string())
.collect::<Vec<_>>()
.join("")
)
}
Boolean(b) => write!(f, "Boolean: {}", b),
Number(n) => write!(f, "Number: {}", n),
Keyword(k) => write!(f, "Keyword: :{}", k),
Method(m, args) => write!(f, "Method: ::{m} ({})", args.0),
Word(w) => write!(f, "Word: {}", w),
Block(b) => write!(
f,
"Block: <{}>",
b.iter()
.map(|(line, _)| line.to_string())
.collect::<Vec<_>>()
.join("\n")
),
If(cond, then_branch, else_branch) => write!(
f,
"If: {} Then: {} Else: {}",
cond.0, then_branch.0, else_branch.0
),
Let(pattern, expression) => {
write!(f, "Let: {} = {}", pattern.0, expression.0)
}
Dict(entries) => write!(
f,
"#{{{}}}",
entries
.iter()
.map(|pair| pair.0.to_string())
.collect::<Vec<_>>()
.join(", ")
),
List(l) => write!(
f,
"List: [{}]",
l.iter()
.map(|(line, _)| line.to_string())
.collect::<Vec<_>>()
.join("\n")
),
Arguments(a) => write!(
f,
"Arguments: ({})",
a.iter()
.map(|(line, _)| line.to_string())
.collect::<Vec<_>>()
.join("\n")
),
Tuple(t) => write!(
f,
"Tuple: ({})",
t.iter()
.map(|(line, _)| line.to_string())
.collect::<Vec<_>>()
.join("\n")
),
Synthetic(root, first, rest) => write!(
f,
"Synth: [{}, {}, {}]",
root.0,
first.0,
rest.iter()
.map(|(term, _)| term.to_string())
.collect::<Vec<_>>()
.join("\n")
),
When(clauses) | Receive(clauses) => write!(
f,
"When: [{}]",
clauses
.iter()
.map(|clause| clause.0.to_string())
.collect::<Vec<_>>()
.join("\n")
),
Placeholder => write!(f, "Placeholder"),
LBox(_name, _rhs) => todo!(),
Match(value, clauses) => {
write!(
f,
"match: {} with {}",
&value.0.to_string(),
clauses
.iter()
.map(|clause| clause.0.to_string())
.collect::<Vec<_>>()
.join("\n")
)
}
FnBody(clauses) => {
write!(
f,
"{}",
clauses
.iter()
.map(|clause| clause.0.to_string())
.collect::<Vec<_>>()
.join("\n")
)
}
Fn(name, body, ..) => {
write!(f, "fn: {name}\n{}", body.0)
}
FnDeclaration(_name) => todo!(),
Panic(_expr) => todo!(),
Do(terms) => {
write!(
f,
"do: {}",
terms
.iter()
.map(|(term, _)| term.to_string())
.collect::<Vec<_>>()
.join(" > ")
)
}
Repeat(_times, _body) => todo!(),
Splat(word) => {
write!(f, "splat: {}", word)
}
KeywordPair(k, v) | KeyPairPattern(k, v) => {
write!(f, "key_pair: {} {}", k, v.0)
}
StringPair(k, v) | StrPairPattern(k, v) => {
write!(f, "str_pair: {k} {}", v.0)
}
Loop(init, body) => {
write!(
f,
"loop: {} with {}",
init.0,
body.iter()
.map(|clause| clause.0.to_string())
.collect::<Vec<_>>()
.join("\n")
)
}
Recur(args) => {
write!(
f,
"recur: {}",
args.iter()
.map(|(arg, _)| arg.to_string())
.collect::<Vec<_>>()
.join(", ")
)
}
MatchClause(pattern, guard, body) => {
write!(
f,
"match clause: {} if {:?} -> {}",
pattern.0, guard, body.0
)
}
WhenClause(cond, body) => {
write!(f, "when clause: {} -> {}", cond.0, body.0)
}
NilPattern => write!(f, "nil"),
BooleanPattern(b) => write!(f, "{}", b),
NumberPattern(n) => write!(f, "{}", n),
StringPattern(s) => write!(f, "{}", s),
KeywordPattern(k) => write!(f, ":{}", k),
WordPattern(w) => write!(f, "{}", w),
AsPattern(w, t) => write!(f, "{} as :{}", w, t),
Splattern(p) => write!(f, "...{}", p.0),
PlaceholderPattern => write!(f, "_"),
TuplePattern(t) => write!(
f,
"({})",
t.iter()
.map(|x| x.0.to_string())
.collect::<Vec<_>>()
.join(", ")
),
ListPattern(l) => write!(
f,
"({})",
l.iter()
.map(|x| x.0.to_string())
.collect::<Vec<_>>()
.join(", ")
),
DictPattern(entries) => write!(
f,
"#{{{}}}",
entries
.iter()
.map(|(pair, _)| pair.to_string())
.collect::<Vec<_>>()
.join(", ")
),
InterpolatedPattern(strprts) => write!(
f,
"interpolated: \"{}\"",
strprts
.iter()
.map(|part| part.0.to_string())
.collect::<Vec<_>>()
.join("")
),
}
}
}

736
src/base.rs Normal file
View File

@ -0,0 +1,736 @@
use crate::js::*;
use crate::value::*;
use imbl::*;
use std::rc::Rc;
#[derive(Clone, Debug)]
pub enum BaseFn {
Nullary(&'static str, fn() -> Value),
Unary(&'static str, fn(&Value) -> Value),
Binary(&'static str, fn(&Value, &Value) -> Value),
Ternary(&'static str, fn(&Value, &Value, &Value) -> Value),
}
pub fn eq(x: &Value, y: &Value) -> Value {
if x == y {
Value::True
} else {
Value::False
}
}
pub fn add(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Number(x), Value::Number(y)) => Value::Number(x + y),
_ => unreachable!("internal Ludus error: wrong arguments to base add: {x}, {y}"),
}
}
pub fn sub(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Number(x), Value::Number(y)) => Value::Number(x - y),
_ => unreachable!("internal Ludus error"),
}
}
pub fn unbox(x: &Value) -> Value {
match x {
Value::Box(cell) => cell.as_ref().borrow().clone(),
_ => unreachable!("internal Ludus error"),
}
}
pub fn store(b: &Value, val: &Value) -> Value {
if let Value::Box(cell) = b {
cell.replace(val.clone());
val.clone()
} else {
unreachable!("internal Ludus error")
}
}
// TODO: do better than returning just the docstr
// name, patterns, AND docstring
pub fn doc(f: &Value) -> Value {
match f {
Value::Fn(f) => f.as_ref().doc(),
_ => Value::Interned("no documentation found"),
}
}
pub fn assoc(dict: &Value, key: &Value, value: &Value) -> Value {
match (dict, key) {
(Value::Dict(d), Value::Keyword(k)) => {
Value::Dict(Box::new(d.update(Key::Keyword(k), value.clone())))
}
(Value::Dict(d), Value::Interned(k)) => {
Value::Dict(Box::new(d.update(Key::Interned(k), value.clone())))
}
(Value::Dict(d), Value::String(s)) => {
Value::Dict(Box::new(d.update(Key::String(s.clone()), value.clone())))
}
_ => unreachable!("internal Ludus error calling assoc with ({dict}, {key}, {value})"),
}
}
pub fn r#bool(x: &Value) -> Value {
match x {
Value::Nil | Value::False => Value::False,
_ => Value::True,
}
}
pub fn chars(x: &Value) -> Value {
match x {
Value::Interned(s) => {
let chars = s.chars();
let mut charlist = vector![];
for char in chars {
if char.is_ascii() {
charlist.push_back(Value::String(Rc::new(char.to_string())))
} else {
return Value::Tuple(Rc::new(vec![
Value::Keyword("err"),
Value::String(Rc::new(format!("{char} is not an ascii character"))),
]));
}
}
Value::Tuple(Rc::new(vec![
Value::Keyword("ok"),
Value::List(Box::new(charlist)),
]))
}
Value::String(s) => {
let chars = s.chars();
let mut charlist = vector![];
for char in chars {
if char.is_ascii() {
charlist.push_back(Value::String(Rc::new(char.to_string())))
} else {
return Value::Tuple(Rc::new(vec![
Value::Keyword("err"),
Value::String(Rc::new(format!("{char} is not an ascii character"))),
]));
}
}
Value::Tuple(Rc::new(vec![
Value::Keyword("ok"),
Value::List(Box::new(charlist)),
]))
}
_ => unreachable!("internal Ludus error"),
}
}
// TODO: figure out how to get to opportunistic mutation here
pub fn concat(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Interned(x), Value::Interned(y)) => Value::String(Rc::new(format!("{x}{y}"))),
(Value::String(x), Value::String(y)) => Value::String(Rc::new(format!("{x}{y}"))),
(Value::String(x), Value::Interned(y)) => Value::String(Rc::new(format!("{x}{y}"))),
(Value::Interned(x), Value::String(y)) => Value::String(Rc::new(format!("{x}{y}"))),
(Value::List(x), Value::List(y)) => {
let mut newlist = *x.clone();
newlist.append(*y.clone());
Value::List(Box::new(newlist))
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn append(x: &Value, y: &Value) -> Value {
match x {
Value::List(list) => {
let mut newlist = list.clone();
newlist.push_back(y.clone());
Value::List(newlist)
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn dec(x: &Value) -> Value {
match x {
Value::Number(n) => Value::Number(n - 1.0),
_ => unreachable!("internal Ludus error"),
}
}
pub fn inc(x: &Value) -> Value {
match x {
Value::Number(n) => Value::Number(n + 1.0),
_ => unreachable!("internal Ludus error"),
}
}
pub fn div(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Number(x), Value::Number(y)) => Value::Number(x / y),
_ => unreachable!("internal Ludus error"),
}
}
pub fn mult(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Number(x), Value::Number(y)) => Value::Number(x * y),
_ => unreachable!("internal Ludus error"),
}
}
pub fn dissoc(dict: &Value, key: &Value) -> Value {
match (dict, key) {
(Value::Dict(dict), Value::Keyword(key)) => {
let mut new = dict.clone();
new.remove(&Key::Keyword(key));
Value::Dict(new)
}
(Value::Dict(dict), Value::Interned(key)) => {
let mut new = dict.clone();
new.remove(&Key::Interned(key));
Value::Dict(new)
}
(Value::Dict(dict), Value::String(key)) => {
let mut new = dict.clone();
new.remove(&Key::String(key.clone()));
Value::Dict(new)
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn first(ordered: &Value) -> Value {
match ordered {
Value::List(list) => match list.front() {
Some(n) => n.clone(),
None => Value::Nil,
},
Value::Tuple(tuple) => match tuple.first() {
Some(n) => n.clone(),
None => Value::Nil,
},
_ => unreachable!("internal Ludus error"),
}
}
// TODO: figure out how to handle negative numbers
// the cast from f64 to usize discards sign info
pub fn at(ordered: &Value, i: &Value) -> Value {
match (ordered, i) {
(Value::List(list), Value::Number(n)) => {
let i = *n as usize;
match list.get(i) {
Some(n) => n.clone(),
None => Value::Nil,
}
}
(Value::Tuple(tuple), Value::Number(n)) => {
let i = *n as usize;
match tuple.get(i) {
Some(n) => n.clone(),
None => Value::Nil,
}
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn get(dict: &Value, key: &Value) -> Value {
match (dict, key) {
(Value::Dict(dict), Value::Keyword(key)) => match dict.get(&Key::Keyword(key)) {
Some(x) => x.clone(),
None => Value::Nil,
},
(Value::Dict(dict), Value::Interned(key)) => match dict.get(&Key::Interned(key)) {
Some(x) => x.clone(),
None => Value::Nil,
},
(Value::Dict(dict), Value::String(key)) => match dict.get(&Key::String(key.clone())) {
Some(x) => x.clone(),
None => Value::Nil,
},
_ => unreachable!("internal Ludus error"),
}
}
pub fn last(ordered: &Value) -> Value {
match ordered {
Value::List(list) => match list.last() {
Some(x) => x.clone(),
None => Value::Nil,
},
Value::Tuple(tuple) => match tuple.last() {
Some(x) => x.clone(),
None => Value::Nil,
},
_ => unreachable!("internal Ludus error"),
}
}
pub fn print(x: &Value) -> Value {
let Value::List(args) = x else {
unreachable!("internal Ludus error")
};
let out = args
.iter()
.map(|val| format!("{val}"))
.collect::<Vec<_>>()
.join(" ");
// println!("{out}");
console_log!("{out}");
Value::Keyword("ok")
}
pub fn show(x: &Value) -> Value {
Value::String(Rc::new(format!("{x}")))
}
pub fn rest(ordered: &Value) -> Value {
match ordered {
Value::List(list) => Value::List(Box::new(list.clone().split_at(1).1)),
Value::Tuple(tuple) => {
Value::List(Box::new(Vector::from_iter(tuple.iter().next().cloned())))
}
Value::Interned(str) => Value::String(Rc::new(str.get(1..).unwrap_or("").to_string())),
Value::String(str) => Value::String(Rc::new(
str.clone().as_str().get(1..).unwrap_or("").to_string(),
)),
_ => unreachable!("internal Ludus error"),
}
}
pub fn count(coll: &Value) -> Value {
match coll {
Value::Dict(d) => Value::Number(d.len() as f64),
Value::List(l) => Value::Number(l.len() as f64),
Value::Tuple(t) => Value::Number(t.len() as f64),
Value::String(s) => Value::Number(s.len() as f64),
Value::Interned(s) => Value::Number(s.len() as f64),
_ => unreachable!("internal Ludus error"),
}
}
pub fn range(start: &Value, end: &Value) -> Value {
match (start, end) {
(Value::Number(start), Value::Number(end)) => {
let start = *start as isize;
let end = *end as isize;
let mut range = Vector::new();
for n in start..end {
range.push_back(Value::Number(n as f64))
}
Value::List(Box::new(range))
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn slice(ordered: &Value, start: &Value, end: &Value) -> Value {
match (ordered, start, end) {
(Value::List(list), Value::Number(start), Value::Number(end)) => {
let mut newlist = list.clone();
let start = std::cmp::max(*start as usize, 0);
let end = std::cmp::min(*end as usize, list.len());
Value::List(Box::new(newlist.slice(start..end)))
}
// TODO: figure out something better to do than return an empty string on a bad slice
(Value::String(string), Value::Number(start), Value::Number(end)) => {
let start = std::cmp::max(*start as usize, 0);
let end = std::cmp::min(*end as usize, string.len());
Value::String(Rc::new(
string
.clone()
.as_str()
.get(start..end)
.unwrap_or("")
.to_string(),
))
}
(Value::Interned(string), Value::Number(start), Value::Number(end)) => {
let start = std::cmp::max(*start as usize, 0);
let end = std::cmp::min(*end as usize, string.len());
Value::String(Rc::new(string.get(start..end).unwrap_or("").to_string()))
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn list(x: &Value) -> Value {
match x {
Value::List(_) => x.clone(),
Value::Tuple(t) => Value::List(Box::new(Vector::from_iter(t.iter().cloned()))),
Value::Dict(d) => {
let kvs = d.iter();
let mut list = vector![];
for (key, value) in kvs {
let kv = Value::Tuple(Rc::new(vec![key.to_value(), value.clone()]));
list.push_back(kv);
}
Value::List(Box::new(list))
}
_ => Value::List(Box::new(vector![x.clone()])),
}
}
pub fn number(x: &Value) -> Value {
match x {
Value::Interned(string) => match string.parse::<f64>() {
Ok(n) => Value::Tuple(Rc::new(vec![Value::Keyword("ok"), Value::Number(n)])),
Err(_) => Value::Tuple(Rc::new(vec![
Value::Keyword("err"),
Value::String(Rc::new(format!("could not parse `{string}` as a number"))),
])),
},
Value::String(string) => match string.parse::<f64>() {
Ok(n) => Value::Tuple(Rc::new(vec![Value::Keyword("ok"), Value::Number(n)])),
Err(_) => Value::Tuple(Rc::new(vec![
Value::Keyword("err"),
Value::String(Rc::new(format!("could not parse `{string}` as a number"))),
])),
},
_ => unreachable!("internal Ludus error"),
}
}
pub fn r#type(x: &Value) -> Value {
match x {
Value::Nil => Value::Keyword("nil"),
Value::Number(_) => Value::Keyword("number"),
Value::True | Value::False => Value::Keyword("bool"),
Value::Keyword(_) => Value::Keyword("keyword"),
Value::Tuple(_) => Value::Keyword("tuple"),
Value::Interned(_) => Value::Keyword("string"),
Value::String(_) => Value::Keyword("string"),
Value::List(_) => Value::Keyword("list"),
Value::Dict(_) => Value::Keyword("dict"),
Value::Fn(_) => Value::Keyword("fn"),
Value::Box(_) => Value::Keyword("box"),
Value::BaseFn(_) => Value::Keyword("fn"),
Value::Partial(_) => Value::Keyword("fn"),
Value::Process => Value::Keyword("process"),
Value::Nothing => unreachable!(),
}
}
pub fn split(source: &Value, splitter: &Value) -> Value {
match (source, splitter) {
(Value::String(source), Value::String(splitter)) => {
println!("splitting {source} with {splitter}");
let parts = source.split_terminator(splitter.as_str());
let mut list = vector![];
for part in parts {
list.push_back(Value::String(Rc::new(part.to_string())));
}
Value::List(Box::new(list))
}
(Value::String(_), Value::Interned(splitter)) => {
split(source, &Value::String(Rc::new(splitter.to_string())))
}
(Value::Interned(source), Value::String(_)) => {
split(&Value::String(Rc::new(source.to_string())), splitter)
}
(Value::Interned(source), Value::Interned(splitter)) => {
let source = Value::String(Rc::new(source.to_string()));
let splitter = Value::String(Rc::new(splitter.to_string()));
split(&source, &splitter)
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn upcase(string: &Value) -> Value {
match string {
Value::String(string) => Value::String(Rc::new(string.to_uppercase())),
Value::Interned(string) => Value::String(Rc::new(string.to_uppercase())),
_ => unreachable!("internal Ludus error"),
}
}
pub fn downcase(string: &Value) -> Value {
match string {
Value::String(string) => Value::String(Rc::new(string.to_lowercase())),
Value::Interned(string) => Value::String(Rc::new(string.to_lowercase())),
_ => unreachable!("internal Ludus error"),
}
}
pub fn trim(string: &Value) -> Value {
match string {
Value::String(string) => Value::String(Rc::new(string.trim().to_string())),
Value::Interned(string) => Value::String(Rc::new(string.trim().to_string())),
_ => unreachable!("internal Ludus error"),
}
}
pub fn triml(string: &Value) -> Value {
match string {
Value::String(string) => Value::String(Rc::new(string.trim_start().to_string())),
Value::Interned(string) => Value::String(Rc::new(string.trim_start().to_string())),
_ => unreachable!("internal Ludus error"),
}
}
pub fn trimr(string: &Value) -> Value {
match string {
Value::String(string) => Value::String(Rc::new(string.trim_end().to_string())),
Value::Interned(string) => Value::String(Rc::new(string.trim_end().to_string())),
_ => unreachable!("internal Ludus error"),
}
}
pub fn atan_2(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Number(x), Value::Number(y)) => Value::Number(x.atan2(*y)),
_ => unreachable!("internal Ludus error"),
}
}
pub fn ceil(x: &Value) -> Value {
match x {
Value::Number(x) => Value::Number(x.ceil()),
_ => unreachable!("internal Ludus error"),
}
}
pub fn cos(x: &Value) -> Value {
match x {
Value::Number(x) => Value::Number(x.cos()),
_ => unreachable!("internal Ludus error"),
}
}
pub fn floor(x: &Value) -> Value {
match x {
Value::Number(x) => Value::Number(x.floor()),
_ => unreachable!("internal Ludus error"),
}
}
pub fn base_random() -> Value {
Value::Number(random())
}
pub fn round(x: &Value) -> Value {
match x {
Value::Number(x) => Value::Number(x.round()),
_ => unreachable!("internal Ludus error"),
}
}
pub fn sin(x: &Value) -> Value {
match x {
Value::Number(x) => Value::Number(x.sin()),
_ => unreachable!("internal Ludus error"),
}
}
pub fn sqrt(x: &Value) -> Value {
match x {
Value::Number(x) => Value::Number(x.sqrt()),
_ => unreachable!("internal Ludus error"),
}
}
pub fn tan(x: &Value) -> Value {
match x {
Value::Number(x) => Value::Number(x.tan()),
_ => unreachable!("internal Ludus error"),
}
}
pub fn gt(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Number(x), Value::Number(y)) => {
if x > y {
Value::True
} else {
Value::False
}
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn gte(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Number(x), Value::Number(y)) => {
if x >= y {
Value::True
} else {
Value::False
}
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn lt(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Number(x), Value::Number(y)) => {
if x < y {
Value::True
} else {
Value::False
}
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn lte(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Number(x), Value::Number(y)) => {
if x <= y {
Value::True
} else {
Value::False
}
}
_ => unreachable!("internal Ludus error"),
}
}
pub fn r#mod(x: &Value, y: &Value) -> Value {
match (x, y) {
(Value::Number(x), Value::Number(y)) => Value::Number(x % y),
_ => unreachable!("internal Ludus error"),
}
}
pub fn make_base() -> Value {
let members = vec![
("add", Value::BaseFn(Box::new(BaseFn::Binary("add", add)))),
(
"append",
Value::BaseFn(Box::new(BaseFn::Binary("append", append))),
),
(
"assoc",
Value::BaseFn(Box::new(BaseFn::Ternary("assoc", assoc))),
),
("at", Value::BaseFn(Box::new(BaseFn::Binary("at", at)))),
(
"atan_2",
Value::BaseFn(Box::new(BaseFn::Binary("atan_2", atan_2))),
),
(
"bool",
Value::BaseFn(Box::new(BaseFn::Unary("bool", r#bool))),
),
("ceil", Value::BaseFn(Box::new(BaseFn::Unary("ceil", ceil)))),
(
"chars",
Value::BaseFn(Box::new(BaseFn::Unary("chars", chars))),
),
(
"concat",
Value::BaseFn(Box::new(BaseFn::Binary("concat", concat))),
),
("cos", Value::BaseFn(Box::new(BaseFn::Unary("cos", cos)))),
(
"count",
Value::BaseFn(Box::new(BaseFn::Unary("count", count))),
),
("dec", Value::BaseFn(Box::new(BaseFn::Unary("dec", dec)))),
(
"dissoc",
Value::BaseFn(Box::new(BaseFn::Binary("dissoc", dissoc))),
),
("div", Value::BaseFn(Box::new(BaseFn::Binary("div", div)))),
("doc!", Value::BaseFn(Box::new(BaseFn::Unary("doc!", doc)))),
(
"downcase",
Value::BaseFn(Box::new(BaseFn::Unary("downcase", downcase))),
),
("eq?", Value::BaseFn(Box::new(BaseFn::Binary("eq?", eq)))),
(
"first",
Value::BaseFn(Box::new(BaseFn::Unary("first", first))),
),
(
"floor",
Value::BaseFn(Box::new(BaseFn::Unary("floor", floor))),
),
("get", Value::BaseFn(Box::new(BaseFn::Binary("get", get)))),
("gt?", Value::BaseFn(Box::new(BaseFn::Binary("gt?", gt)))),
("gte?", Value::BaseFn(Box::new(BaseFn::Binary("gte?", gte)))),
("inc", Value::BaseFn(Box::new(BaseFn::Unary("inc", inc)))),
("last", Value::BaseFn(Box::new(BaseFn::Unary("last", last)))),
("list", Value::BaseFn(Box::new(BaseFn::Unary("list", list)))),
("lt?", Value::BaseFn(Box::new(BaseFn::Binary("lt?", lt)))),
("lte?", Value::BaseFn(Box::new(BaseFn::Binary("lte?", lte)))),
("mod", Value::BaseFn(Box::new(BaseFn::Binary("mod", r#mod)))),
(
"mult",
Value::BaseFn(Box::new(BaseFn::Binary("mult", mult))),
),
(
"number",
Value::BaseFn(Box::new(BaseFn::Unary("number", number))),
),
("pi", Value::Number(std::f64::consts::PI)),
(
"print!",
Value::BaseFn(Box::new(BaseFn::Unary("print!", print))),
),
("process", Value::Process),
(
"random",
Value::BaseFn(Box::new(BaseFn::Nullary("random", base_random))),
),
(
"range",
Value::BaseFn(Box::new(BaseFn::Binary("range", range))),
),
("rest", Value::BaseFn(Box::new(BaseFn::Unary("rest", rest)))),
(
"round",
Value::BaseFn(Box::new(BaseFn::Unary("round", round))),
),
("show", Value::BaseFn(Box::new(BaseFn::Unary("show", show)))),
("sin", Value::BaseFn(Box::new(BaseFn::Unary("sin", sin)))),
(
"slice",
Value::BaseFn(Box::new(BaseFn::Ternary("slice", slice))),
),
(
"split",
Value::BaseFn(Box::new(BaseFn::Binary("split", split))),
),
("sqrt", Value::BaseFn(Box::new(BaseFn::Unary("sqrt", sqrt)))),
("sqrt_2", Value::Number(std::f64::consts::SQRT_2)),
(
"store!",
Value::BaseFn(Box::new(BaseFn::Binary("store!", store))),
),
("sub", Value::BaseFn(Box::new(BaseFn::Binary("sub", sub)))),
("tan", Value::BaseFn(Box::new(BaseFn::Unary("tan", tan)))),
("trim", Value::BaseFn(Box::new(BaseFn::Unary("trim", trim)))),
(
"triml",
Value::BaseFn(Box::new(BaseFn::Unary("triml", triml))),
),
(
"trimr",
Value::BaseFn(Box::new(BaseFn::Unary("trimr", trimr))),
),
(
"type",
Value::BaseFn(Box::new(BaseFn::Unary("type", r#type))),
),
(
"unbox",
Value::BaseFn(Box::new(BaseFn::Unary("unbox", unbox))),
),
(
"upcase",
Value::BaseFn(Box::new(BaseFn::Unary("upcase", upcase))),
),
];
let members = members
.iter()
.map(|(name, bfn)| (Key::Keyword(name), bfn.clone()))
.collect::<Vec<_>>();
Value::Dict(Box::new(HashMap::from(members)))
}

90
src/chunk.rs Normal file
View File

@ -0,0 +1,90 @@
use crate::js::*;
use crate::op::Op;
use crate::value::{Key, Value};
use chumsky::prelude::SimpleSpan;
use imbl::HashMap;
use num_traits::FromPrimitive;
use regex::Regex;
#[derive(Clone, Debug)]
pub struct StrPattern {
pub words: Vec<&'static str>,
pub re: Regex,
}
#[derive(Clone, Debug)]
pub struct Chunk {
pub constants: Vec<Value>,
pub bytecode: Vec<u8>,
pub keywords: Vec<&'static str>,
pub string_patterns: Vec<StrPattern>,
pub env: HashMap<Key, Value>,
pub msgs: Vec<String>,
pub spans: Vec<SimpleSpan>,
pub src: &'static str,
pub input: &'static str,
}
impl std::fmt::Display for Chunk {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Chunk.")
}
}
impl Chunk {
pub fn dissasemble_instr(&self, i: &mut usize) {
let op = Op::from_u8(self.bytecode[*i]).unwrap();
use Op::*;
match op {
Pop | Store | Stash | Load | Nil | True | False | MatchNil | MatchTrue | MatchFalse
| ResetMatch | GetKey | PanicWhenFallthrough | PanicNoMatch | PanicNoFnMatch
| PanicNoLetMatch | TypeOf | Duplicate | Decrement | ToInt | Noop | LoadTuple
| LoadList | Eq | Add | Sub | Mult | Div | Unbox | BoxStore | Assert | Get | At
| Not | Panic | EmptyString | ConcatStrings | Stringify | MatchType | Return
| UnconditionalMatch | Print | AppendList | ConcatList | PushList | PushDict
| AppendDict | ConcatDict | Nothing | PushGlobal | SetUpvalue | LoadMessage
| NextMessage | MatchMessage | ClearMessage | SendMethod | LoadScrutinee => {
console_log!("{i:04}: {op}")
}
Constant | MatchConstant => {
let high = self.bytecode[*i + 1];
let low = self.bytecode[*i + 2];
let idx = ((high as usize) << 8) + low as usize;
let value = &self.constants[idx].show();
console_log!("{i:04}: {:16} {idx:05}: {value}", op.to_string());
*i += 2;
}
Msg => {
let msg_idx = self.bytecode[*i + 1];
let msg = &self.msgs[msg_idx as usize];
console_log!("{i:04}: {msg}");
*i += 1;
}
PushBinding | MatchTuple | MatchSplattedTuple | LoadSplattedTuple | MatchList
| MatchSplattedList | LoadSplattedList | MatchDict | MatchSplattedDict
| DropDictEntry | LoadDictValue | PushTuple | PushBox | MatchDepth | PopN | StoreN
| Call | GetUpvalue | Partial | MatchString | PushStringMatches | TailCall | LoadN => {
let next = self.bytecode[*i + 1];
console_log!("{i:04}: {:16} {next:03}", op.to_string());
*i += 1;
}
Jump | JumpIfFalse | JumpIfTrue | JumpIfNoMatch | JumpIfMatch | JumpBack
| JumpIfZero => {
let high = self.bytecode[*i + 1];
let low = self.bytecode[*i + 2];
let len = ((high as u16) << 8) + low as u16;
console_log!("{i:04}: {:16} {len:05}", op.to_string());
*i += 2;
}
}
}
pub fn dissasemble(&self) {
console_log!("IDX | CODE | INFO");
let mut i = 0;
while i < self.bytecode.len() {
self.dissasemble_instr(&mut i);
i += 1;
}
}
}

1507
src/compiler.rs Normal file

File diff suppressed because it is too large Load Diff

143
src/errors.rs Normal file
View File

@ -0,0 +1,143 @@
use crate::js::*;
use crate::lexer::Token;
use crate::panic::{Panic, PanicMsg};
use crate::validator::VErr;
use crate::vm::CallFrame;
use chumsky::error::RichPattern;
use chumsky::prelude::*;
const SEPARATOR: &str = "\n\n";
fn line_number(src: &'static str, span: SimpleSpan) -> usize {
src.chars().take(span.start).filter(|c| *c == '\n').count()
}
fn get_line(src: &'static str, line: usize) -> String {
src.split("\n").nth(line).unwrap().to_string()
}
pub fn lexing(errs: Vec<Rich<'static, char>>, src: &'static str, input: &'static str) -> String {
let mut msgs = vec!["Ludus found some errors.".to_string()];
for err in errs {
let mut msg = vec![];
let line_number = line_number(src, *err.span());
let line = get_line(src, line_number);
let char = src.chars().nth(err.span().start).unwrap();
msg.push(format!("Syntax error: unexpected {char}"));
msg.push(format!(" on line {} in {}", line_number + 1, input));
msg.push(format!(" >>> {line}"));
msgs.push(msg.join("\n"));
}
msgs.join(SEPARATOR)
}
pub fn validation(errs: Vec<VErr>) -> String {
let mut msgs = vec!["Ludus found some errors.".to_string()];
for err in errs {
let mut msg = vec![];
let line_number = line_number(err.src, *err.span);
let line = get_line(err.src, line_number);
msg.push(format!("Validation error: {}", err.msg));
msg.push(format!(" on line {} in {}", line_number + 1, err.input));
msg.push(format!(" >>> {line}"));
msgs.push(msg.join("\n"));
}
msgs.join(SEPARATOR)
}
pub fn parsing(errs: Vec<Rich<'static, Token>>, src: &'static str, input: &'static str) -> String {
let mut msgs = vec!["Ludus found some errors.".to_string()];
for err in errs {
let mut msg = vec![];
let line_number = line_number(src, *err.span());
let line = get_line(src, line_number);
let details = parsing_message(err);
msg.push(format!("Syntax error: {}", details));
msg.push(format!(" on line {} in {}", line_number + 1, input));
msg.push(format!(" >>> {line}"));
msgs.push(msg.join("\n"))
}
msgs.join(SEPARATOR)
}
fn parsing_message(err: Rich<'static, Token>) -> String {
let found = match err.found() {
Some(token) => token.show(),
None => "end of input".to_string(),
};
let expected = err.expected();
let mut expecteds = vec![];
for pattern in expected {
let shown = match pattern {
RichPattern::Token(t) => t.show(),
RichPattern::Label(s) => s.to_string(),
RichPattern::Identifier(s) => s.clone(),
RichPattern::Any => "any".to_string(),
RichPattern::SomethingElse => "something else".to_string(),
RichPattern::EndOfInput => "eof".to_string(),
};
expecteds.push(shown);
}
let expecteds = if expecteds.iter().any(|e| e == &"else".to_string()) {
vec!["else".to_string()]
} else {
expecteds
};
let expecteds = if expecteds.iter().any(|e| e == &"then".to_string()) {
vec!["then".to_string()]
} else {
expecteds
};
let expecteds = expecteds.join(" | ");
format!("Ludus did not expect to see: {found}\n expected: {expecteds}")
}
pub fn panic(panic: Panic) -> String {
// console_log!("Ludus panicked!: {panic}");
// panic.call_stack.last().unwrap().chunk().dissasemble();
// console_log!("{:?}", panic.call_stack.last().unwrap().chunk().spans);
let mut msgs = vec!["Ludus panicked!".to_string()];
let msg = match panic.msg {
PanicMsg::Generic(ref s) => s,
_ => &"no match".to_string(),
};
msgs.push(msg.clone());
msgs.push(traceback(&panic));
msgs.join("\n")
}
fn traceback(panic: &Panic) -> String {
let mut traceback = vec![];
for frame in panic.call_stack.iter().rev() {
traceback.push(frame_info(frame));
}
traceback.join("\n")
}
fn frame_info(frame: &CallFrame) -> String {
let span = frame.chunk().spans[if frame.ip == 0 {
frame.ip
} else {
frame.ip - 1
}];
let line_number = line_number(frame.chunk().src, span);
let line = get_line(frame.chunk().src, line_number);
let line = line.trim_start();
let name = frame.function.as_fn().name();
let input = frame.chunk().input;
format!(
" in {name} on line {} in {input}\n >>> {line}",
line_number + 1
)
}
/////// Some thoughts
// We're putting the information we need on the function and the chunk.
// In the compiler, on functions, build up a vec of strings that are the patterns the function can match against
// The pattern asts have a `show` method.
// And with the additional members on Chunk, we should have everything we need for a pretty fn no match message
// Let no match is no problem, either. We should have no concerns pulling the line with the span start and string
// We don't need to reproduce the pattern, since it will be right there in the code
// As for match forms, we'll just use "no match" and print the value

100
src/io.rs Normal file
View File

@ -0,0 +1,100 @@
use wasm_bindgen::prelude::*;
use serde::{Serialize, Deserialize};
use crate::value::Value;
use crate::js::*;
use imbl::Vector;
use std::rc::Rc;
const OK: Value = Value::Keyword("ok");
const ERR: Value = Value::Keyword("err");
#[wasm_bindgen(module = "/pkg/worker.js")]
extern "C" {
#[wasm_bindgen(catch)]
async fn io (output: String) -> Result<JsValue, JsValue>;
}
type Url = Value; // expect a string
type Commands = Value; // expect a list of command tuples
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "verb", content = "data")]
pub enum MsgOut {
Console(Value),
Commands(Commands),
Fetch(Url),
Complete(Value),
Error(String),
Ready
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "verb", content = "data")]
pub enum MsgIn {
Input(String),
Fetch(String, f64, String),
Kill,
Keyboard(Vec<String>),
}
impl std::fmt::Display for MsgIn {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
MsgIn::Input(str) => write!(f, "Input: {str}"),
MsgIn::Kill => write!(f, "Kill"),
MsgIn::Fetch(url, code, text) => write!(f, "Fetch: {url} :: {code} ::\n{text}"),
_ => todo!()
}
}
}
impl MsgIn {
pub fn into_value(self) -> Value {
match self {
MsgIn::Input(str) => Value::string(str),
MsgIn::Fetch(url, status_f64, string) => {
let url = Value::string(url);
let status = Value::Number(status_f64);
let text = Value::string(string);
let result_tuple = if status_f64 == 200.0 {
Value::tuple(vec![OK, text])
} else {
Value::tuple(vec![ERR, status])
};
Value::tuple(vec![url, result_tuple])
}
MsgIn::Kill => Value::Nothing,
MsgIn::Keyboard(downkeys) => {
let mut vector = Vector::new();
for key in downkeys {
vector.push_back(Value::String(Rc::new(key)));
}
Value::List(Box::new(vector))
}
}
}
}
pub async fn send_err_to_ludus_console(msg: String) {
console_log!("{msg}");
do_io(vec![MsgOut::Ready, MsgOut::Error(msg)]).await;
}
pub async fn do_io (msgs: Vec<MsgOut>) -> Vec<MsgIn> {
let json = serde_json::to_string(&msgs).unwrap();
let inbox = io (json).await;
let inbox = match inbox {
Ok(msgs) => msgs,
Err(_) => return vec![]
};
let inbox = inbox.as_string().expect("response should be a string");
let inbox: Vec<MsgIn> = serde_json::from_str(inbox.as_str()).expect("response from js should be valid");
if !inbox.is_empty() {
console_log!("ludus received messages");
for msg in inbox.iter() {
console_log!("{}", msg);
}
}
inbox
}

19
src/js.rs Normal file
View File

@ -0,0 +1,19 @@
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
pub fn log(a: &str);
#[wasm_bindgen(js_namespace = Math)]
pub fn random() -> f64;
#[wasm_bindgen(js_namespace = Date)]
pub fn now() -> f64;
}
macro_rules! console_log {
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
}
pub(crate) use console_log;

170
src/lexer.rs Normal file
View File

@ -0,0 +1,170 @@
use crate::spans::*;
use chumsky::prelude::*;
use std::fmt;
#[derive(Clone, PartialEq, Debug)]
pub enum Token {
Nil,
Number(f64),
Word(&'static str),
Boolean(bool),
Keyword(&'static str),
String(&'static str),
// todo: hard code these types
Reserved(&'static str),
Punctuation(&'static str),
Method(&'static str),
}
impl fmt::Display for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Token::Number(n) => write!(f, "[Number {}]", n),
Token::Word(w) => write!(f, "[Word {}]", w),
Token::Boolean(b) => write!(f, "[Boolean {}]", b),
Token::Keyword(k) => write!(f, "[Keyword :{}]", k),
Token::String(s) => write!(f, "[String {}]", s),
Token::Reserved(r) => write!(f, "[Reserved {}]", r),
Token::Nil => write!(f, "[nil]"),
Token::Punctuation(p) => write!(f, "[Punctuation {}]", p),
Token::Method(m) => write!(f, "[Method {m}]"),
}
}
}
impl Token {
pub fn show(&self) -> String {
match self {
Token::Number(n) => format!("{n}"),
Token::Boolean(b) => format!("{b}"),
Token::Keyword(k) => format!(":{k}"),
Token::Method(m) => format!("::{m}"),
Token::Nil => "nil".to_string(),
Token::String(s) => format!("\"{s}\""),
Token::Reserved(s) | Token::Word(s) => s.to_string(),
Token::Punctuation(s) => {
let out = if *s == "\n" { "newline" } else { s };
out.to_string()
}
}
}
}
pub fn lexer(
) -> impl Parser<'static, &'static str, Vec<(Token, Span)>, extra::Err<Rich<'static, char, Span>>> {
let number = just('-')
.or_not()
.then(text::int(10).then(just('.').then(text::digits(10)).or_not()))
.to_slice()
.from_str()
.unwrapped()
.map(Token::Number);
let word = any()
.filter(char::is_ascii_lowercase)
.then(
any()
.filter(char::is_ascii_alphanumeric)
.or(one_of("*/?!_"))
.repeated(),
)
.to_slice();
let reserved_or_word = word.map(|word: &str| match word {
"true" => Token::Boolean(true),
"false" => Token::Boolean(false),
"nil" => Token::Nil,
// todo: hard code these as type constructors
"as" | "box" | "do" | "else" | "fn" | "if" | "let" | "loop" | "match" | "panic!"
| "recur" | "repeat" | "then" | "when" | "with" | "or" | "and" | "receive" => {
Token::Reserved(word)
}
_ => Token::Word(word),
});
let method = just("::").ignore_then(word).map(Token::Method);
let keyword = just(':').ignore_then(word).map(Token::Keyword);
let escape = just('\\')
.then(choice((
just('\\').to('\\'),
just('n').to('\n'),
just('t').to('\t'),
just('r').to('\r'),
just('"').to('"'), // TODO: figure out why this isn't working
)))
.ignored();
let string = none_of('"')
.ignored()
.or(escape)
.repeated()
.to_slice()
.map(Token::String)
.delimited_by(just('"'), just('"'));
// todo: hard code these as type constructors
let punctuation = one_of(",=[]{}()>;\n_")
.to_slice()
.or(just("->"))
.or(just("..."))
.or(just("#{"))
.or(just("${"))
.map(Token::Punctuation);
let token = number
.or(reserved_or_word)
.or(keyword)
.or(method)
.or(string)
.or(punctuation);
let comment = just('&')
.ignore_then(any().and_is(just('\n').not()).repeated())
.repeated();
let ludus_ws = just(' ').or(just('\t')).repeated();
token
.map_with(|tok, e| (tok, e.span()))
.padded_by(ludus_ws)
.padded_by(comment)
.recover_with(skip_then_retry_until(any().ignored(), end()))
.repeated()
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_lexes_nil() {
let spanned_toks = lexer().parse("nil").into_output_errors().0.unwrap();
let (token, _) = spanned_toks[0].clone();
assert_eq!(token, Token::Nil);
}
#[test]
fn it_lexes_strings() {
let spanned_toks = lexer()
.parse("\"foo bar baz\"")
.into_output_errors()
.0
.unwrap();
let (token, _) = spanned_toks[0].clone();
assert_eq!(token, Token::String("foo bar baz"));
}
#[test]
fn it_lexes_strings_w_escaped_quotes() {
let spanned_toks = lexer()
.parse("\"foo \\\"bar baz\"")
.into_output_errors()
.0
.unwrap();
let (token, _) = spanned_toks[0].clone();
assert_eq!(token, Token::String("foo \"bar baz"));
}
}

191
src/lib.rs Normal file
View File

@ -0,0 +1,191 @@
use chumsky::{input::Stream, prelude::*};
use imbl::HashMap;
use wasm_bindgen::prelude::*;
use std::rc::Rc;
use std::cell::RefCell;
const DEBUG_SCRIPT_COMPILE: bool = false;
const DEBUG_SCRIPT_RUN: bool = false;
const DEBUG_PRELUDE_COMPILE: bool = false;
const DEBUG_PRELUDE_RUN: bool = false;
// #[cfg(target_family = "wasm")]
// #[global_allocator]
// static ALLOCATOR: talc::TalckWasm = unsafe { talc::TalckWasm::new_global() };
mod io;
use io::send_err_to_ludus_console;
mod ast;
use crate::ast::Ast;
mod base;
mod world;
use crate::world::{World, Zoo};
mod spans;
use crate::spans::Spanned;
mod lexer;
use crate::lexer::lexer;
mod parser;
use crate::parser::parser;
mod validator;
use crate::validator::Validator;
mod errors;
use crate::errors::{lexing, parsing, validation};
mod panic;
mod js;
use crate::js::*;
mod chunk;
mod op;
mod compiler;
use crate::compiler::Compiler;
pub mod value;
use value::{Value, Key};
mod vm;
use vm::Creature;
const PRELUDE: &str = include_str!("../assets/test_prelude.ld");
fn prelude() -> HashMap<Key, Value> {
let tokens = lexer().parse(PRELUDE).into_output_errors().0.unwrap();
let (parsed, parse_errors) = parser()
.parse(Stream::from_iter(tokens).map((0..PRELUDE.len()).into(), |(t, s)| (t, s)))
.into_output_errors();
if !parse_errors.is_empty() {
console_log!("ERROR PARSING PRELUDE:");
console_log!("{:?}", parse_errors);
panic!("parsing errors in prelude");
}
let parsed = parsed.unwrap();
let (ast, span) = &parsed;
let base = base::make_base();
let mut base_env = imbl::HashMap::new();
base_env.insert(Key::Keyword("base"), base.clone());
let mut validator = Validator::new(ast, span, "prelude", PRELUDE, base_env);
validator.validate();
if !validator.errors.is_empty() {
console_log!("VALIDATION ERRORS IN PRLUDE:");
// report_invalidation(validator.errors);
console_log!("{:?}", validator.errors);
panic!("validator errors in prelude");
}
let parsed: &'static Spanned<Ast> = Box::leak(Box::new(parsed));
let mut compiler = Compiler::new(
parsed,
"prelude",
PRELUDE,
0,
HashMap::new(),
DEBUG_PRELUDE_COMPILE,
);
compiler.emit_constant(base);
compiler.bind("base");
compiler.compile();
let chunk = compiler.chunk;
let stub_zoo = Rc::new(RefCell::new(Zoo::new()));
let mut prld_sync = Creature::new(chunk, stub_zoo, DEBUG_PRELUDE_RUN);
prld_sync.interpret();
let prelude = prld_sync.result.unwrap().unwrap();
match prelude {
Value::Dict(hashmap) => *hashmap,
_ => unreachable!(),
}
}
#[wasm_bindgen]
pub async fn ludus(src: String) {
// instrument wasm to report rust panics
console_error_panic_hook::set_once();
// leak the source so it lives FOREVER
let src = src.to_string().leak();
// lex the source
let (tokens, lex_errs) = lexer().parse(src).into_output_errors();
if !lex_errs.is_empty() {
send_err_to_ludus_console(lexing(lex_errs, src, "user script")).await;
return;
}
let tokens = tokens.unwrap();
let (parse_result, parse_errors) = parser()
.parse(Stream::from_iter(tokens).map((0..src.len()).into(), |(t, s)| (t, s)))
.into_output_errors();
if !parse_errors.is_empty() {
send_err_to_ludus_console(parsing(parse_errors, src, "user script")).await;
return;
}
let parsed: &'static Spanned<Ast> = Box::leak(Box::new(parse_result.unwrap()));
let prelude = prelude();
// let prelude = imbl::HashMap::new();
let mut validator = Validator::new(&parsed.0, &parsed.1, "user input", src, prelude.clone());
validator.validate();
// TODO: validator should generate a string, not print to the console
if !validator.errors.is_empty() {
send_err_to_ludus_console(validation(validator.errors)).await;
return;
}
let mut compiler = Compiler::new(
parsed,
"user script",
src,
0,
prelude.clone(),
DEBUG_SCRIPT_COMPILE,
);
compiler.compile();
if DEBUG_SCRIPT_COMPILE {
println!("=== source code ===");
println!("{src}");
compiler.disassemble();
println!("\n\n")
}
if DEBUG_SCRIPT_RUN {
println!("=== vm run ===");
}
let vm_chunk = compiler.chunk;
let mut world = World::new(vm_chunk, prelude.clone(), DEBUG_SCRIPT_RUN);
world.run().await;
// TODO: actually do something useful on a panic
// match result {
// Some(Ok(val)) => val.show(),
// Some(Err(panic)) => format!("Ludus panicked! {panic}"),
// None => "Ludus run terminated by user".to_string()
// };
// if DEBUG_SCRIPT_RUN {
// // vm.print_stack();
// }
}

198
src/lib.rs.old Normal file
View File

@ -0,0 +1,198 @@
// use ariadne::{sources, Color, Label, Report, ReportKind};
use chumsky::prelude::*;
use std::fmt;
pub type Span = SimpleSpan<usize>;
#[derive(Clone, Debug, PartialEq)]
pub enum Token<'src> {
// atomic types
Boolean(bool),
Number(f64),
String(&'src str),
Word(&'src str),
Keyword(&'src str),
Pkgkeyword(&'src str),
Ignored(&'src str),
// reserved words
As,
Box,
Do,
Else,
Fn,
If,
Import,
Let,
Loop,
Match,
Nil,
Ns,
Panic,
Pkg,
Recur,
Repeat,
Test,
Then,
Use,
When,
With,
// punctuation
Arrow,
Comma,
Equals,
Lbrace,
Lbracket,
Lparen,
Newline,
Pipeline,
Placeholder,
Rbrace,
Rbracket,
Rparen,
Semi,
Splat,
Startdict,
Startset,
}
impl<'src> fmt::Display for Token<'src> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Token::Boolean(b) => write!(f, "{}", b),
Token::Number(n) => write!(f, "{}", n),
Token::String(s) => write!(f, "{}", s),
Token::Word(w) => write!(f, "{}", w),
Token::Keyword(k) => write!(f, ":{}", k),
Token::Ignored(i) => write!(f, "_{}", i),
Token::Pkgkeyword(k) => write!(f, ":{}", k),
Token::As => write!(f, "as"),
Token::Box => write!(f, "box"),
Token::Do => write!(f, "do"),
Token::Else => write!(f, "else"),
Token::Fn => write!(f, "fn"),
Token::If => write!(f, "if"),
Token::Import => write!(f, "import"),
Token::Let => write!(f, "let"),
Token::Loop => write!(f, "loop"),
Token::Match => write!(f, "match"),
Token::Nil => write!(f, "nil"),
Token::Ns => write!(f, "ns"),
Token::Panic => write!(f, "panic!"),
Token::Pkg => write!(f, "pkg"),
Token::Recur => write!(f, "recur"),
Token::Repeat => write!(f, "repeat"),
Token::Test => write!(f, "test"),
Token::Then => write!(f, "then"),
Token::Use => write!(f, "use"),
Token::When => write!(f, "when"),
Token::With => write!(f, "with"),
Token::Arrow => write!(f, "->"),
Token::Comma => write!(f, ","),
Token::Equals => write!(f, "="),
Token::Lbrace => write!(f, "{{"),
Token::Lbracket => write!(f, "["),
Token::Lparen => write!(f, "("),
Token::Newline => write!(f, "\\n"),
Token::Pipeline => write!(f, ">"),
Token::Placeholder => write!(f, "_"),
Token::Rbrace => write!(f, "}}"),
Token::Rbracket => write!(f, "]"),
Token::Rparen => write!(f, ")"),
Token::Semi => write!(f, ";"),
Token::Splat => write!(f, "..."),
Token::Startdict => write!(f, "#{{"),
Token::Startset => write!(f, "${{"),
}
}
}
pub fn lexer<'src>(
) -> impl Parser<'src, &'src str, Vec<(Token<'src>, Span)>, extra::Err<Rich<'src, char, Span>>> {
let string = just('"')
.ignore_then(none_of('"').repeated().to_slice())
.then_ignore(just('"'))
.map(Token::String);
let word = any()
.filter(char::is_ascii_lowercase)
.then(
any()
.filter(char::is_ascii_alphanumeric)
.or(one_of("*_/!?")),
)
.repeated()
.to_slice();
let keyword = just(':').ignore_then(word.clone()).map(Token::Keyword);
let number = just('-')
.or_not()
.then(text::int(10).then(just('.').then(text::digits(10)).or_not()))
.to_slice()
.from_str()
.unwrapped()
.map(Token::Number);
let reserved_or_word = word.map(|word: &str| match word {
"as" => Token::As,
"box" => Token::Box,
"do" => Token::Do,
"else" => Token::Else,
"false" => Token::Boolean(false),
"fn" => Token::Fn,
"if" => Token::If,
"import" => Token::Import,
"let" => Token::Let,
"loop" => Token::Loop,
"match" => Token::Match,
"nil" => Token::Nil,
"ns" => Token::Ns,
"panic!" => Token::Panic, // won't match until C-style ident -> Ludus word
"pkg" => Token::Pkg,
"recur" => Token::Recur,
"repeat" => Token::Repeat,
"test" => Token::Test,
"then" => Token::Then,
"true" => Token::Boolean(true),
"use" => Token::Use,
"when" => Token::When,
"with" => Token::With,
_ => Token::Word(word),
});
let arrow = just("->").to(Token::Arrow);
let comma = just(',').to(Token::Comma);
let semicolon = just(';').to(Token::Semi);
let placeholder = just('_').to(Token::Placeholder);
let control = arrow.or(comma).or(semicolon).or(placeholder);
let comment = just('&')
.then(any().and_is(just('\n').not()).repeated())
.padded();
let atom = number.or(string).or(keyword).or(reserved_or_word);
atom.or(control)
.map_with(|tok, e| (tok, e.span()))
.padded_by(comment.repeated())
.padded()
}
#[cfg(test)]
mod tests {
use crate::lexer;
use crate::Token;
use chumsky::{container::Seq, prelude::*};
#[test]
fn it_works() {
let toks = lexer().parse("42").unwrap();
let (tok, _) = toks[0].clone();
assert_eq!(tok, Token::Number(42.0));
}
}

6
src/main.rs Normal file
View File

@ -0,0 +1,6 @@
use std::env;
pub fn main() {
env::set_var("RUST_BACKTRACE", "1");
println!("Hello, world.")
}

58
src/memory_sandbox.rs Normal file
View File

@ -0,0 +1,58 @@
use imbl::{HashMap, Vector};
use index_vec::Idx;
use std::cell::RefCell;
use std::ops::Range;
use std::rc::Rc;
struct Word(&'static str);
struct Keyword(&'static str);
struct Interned(&'static str);
enum StringPart {
Word(&'static str),
Data(&'static str),
Inline(&'static str),
}
#[derive(Clone, Debug, PartialEq)]
struct LBox {
name: usize,
cell: RefCell<Value>,
}
#[derive(Clone, Debug, PartialEq)]
struct Fn {
name: &'static str,
body: Vec<String>,
//...etc
}
#[derive(Clone, Debug, PartialEq)]
enum Value {
Nil,
Placeholder,
Boolean(bool),
Keyword(usize),
Interned(usize),
FnDecl(usize),
String(Rc<String>),
Number(f64),
Tuple(Rc<Vec<Value>>),
List(Box<Vector<Value>>),
Dict(Box<HashMap<&'static str, Value>>),
Box(Rc<LBox>),
Fn(Rc<RefCell<Fn>>),
}
fn futz() {
let foo: &'static str = "foo";
let baz: Vec<u8> = vec![];
let bar: Range<usize> = 1..3;
let quux: Vector<u8> = Vector::new();
let fuzz = Rc::new(quux);
let blah = Box::new(foo);
let val = Value::Number(12.09);
let foo: f64 = 12.0;
}

212
src/old_main.rs Normal file
View File

@ -0,0 +1,212 @@
// an implementation of Ludus
// curently left undone (and not adding for a while yet):
// * sets
// * interpolated strings & string patterns
// * pkgs, namespaces, imports, `use` forms
// * with forms
// * test forms
// * ignored words
// todo:
// * [x] rewrite fn parser to use chumsky::Recursive::declare/define
// - [x] do this to extract/simplify/DRY things like tuple patterns, fn clauses, etc.
// * [x] Work around chumsky::Stream::from_iter().spanned disappearing in most recent version
// * [x] investigate using labels (which is behind a compiler flag, somehow)
// * [ ] write parsing errors
// * [ ] wire up Ariadne parsing errors
// * [x] add stack traces and code locations to panics
// * [x] validation
// * [x] break this out into multiple files
// * [x] write a tree-walk VM
// - [x] learn how to deal with lifetimes
// - [x] with stack mechanics and refcounting
// - [ ] with tail-call optimization (nb: this may not be possible w/ a TW-VM)
// - [ ] with all the necessary forms for current Ludus
// * [x] guards in match clauses
// * [x] `as` patterns
// * [x] splat patterns in tuples, lists, dicts
// * [x] splats in list and dict literals
// * [x] `loop` and `recur`
// * [x] string patterns
// * [x] string interpolation
// * [x] docstrings
// * [x] write `base` in Rust
// * [ ] turn this into a library function
// * [ ] compile this into WASM
// * [ ] perf testing
use chumsky::{input::Stream, prelude::*};
use rust_embed::Embed;
mod spans;
mod lexer;
use crate::lexer::*;
mod value;
use crate::value::*;
mod parser;
use crate::parser::*;
mod base;
use crate::base::*;
mod validator;
use crate::validator::*;
mod process;
use crate::process::*;
mod errors;
use crate::errors::*;
mod byte_values;
mod compiler;
mod memory_sandbox;
#[derive(Embed)]
#[folder = "assets/"]
struct Asset;
pub fn prelude<'src>() -> (
Vec<(String, Value<'src>)>,
std::collections::HashMap<*const Ast, FnInfo>,
) {
let prelude = Asset::get("prelude.ld").unwrap().data.into_owned();
// we know for sure Prelude should live through the whole run of the program
let leaked = Box::leak(Box::new(prelude));
let prelude = std::str::from_utf8(leaked).unwrap();
let (ptoks, perrs) = lexer().parse(prelude).into_output_errors();
if !perrs.is_empty() {
println!("Errors lexing Prelude");
println!("{:?}", perrs);
panic!();
}
let ptoks = ptoks.unwrap();
let (p_ast, perrs) = parser()
.parse(Stream::from_iter(ptoks).map((0..prelude.len()).into(), |(t, s)| (t, s)))
.into_output_errors();
if !perrs.is_empty() {
println!("Errors parsing Prelude");
println!("{:?}", perrs);
panic!();
}
let prelude_parsed = Box::leak(Box::new(p_ast.unwrap()));
let base_pkg = base();
let mut v6or = Validator::new(
&prelude_parsed.0,
prelude_parsed.1,
"prelude",
prelude,
&base_pkg,
);
v6or.validate();
if !v6or.errors.is_empty() {
report_invalidation(v6or.errors);
panic!("interal Ludus error: invalid prelude")
}
let mut base_ctx = Process::<'src> {
input: "prelude",
src: prelude,
locals: base_pkg.clone(),
ast: &prelude_parsed.0,
span: prelude_parsed.1,
prelude: vec![],
fn_info: v6or.fn_info,
};
let prelude = base_ctx.eval();
let mut p_ctx = vec![];
match prelude {
Ok(Value::Dict(p_dict)) => {
for (key, value) in p_dict.iter() {
p_ctx.push((key.to_string(), value.clone()))
}
}
Ok(_) => {
println!("Bad Prelude export");
panic!();
}
Err(LErr { msg, .. }) => {
println!("Error running Prelude");
println!("{:?}", msg);
panic!();
}
};
(p_ctx, base_ctx.fn_info)
}
pub fn run(src: &'static str) {
let (tokens, lex_errs) = lexer().parse(src).into_output_errors();
if !lex_errs.is_empty() {
println!("{:?}", lex_errs);
return;
}
let tokens = tokens.unwrap();
let to_parse = tokens.clone();
let (parse_result, parse_errors) = parser()
.parse(Stream::from_iter(to_parse).map((0..src.len()).into(), |(t, s)| (t, s)))
.into_output_errors();
if !parse_errors.is_empty() {
println!("{:?}", parse_errors);
return;
}
let parsed = parse_result.unwrap();
let (prelude_ctx, mut prelude_fn_info) = prelude();
let mut v6or = Validator::new(&parsed.0, parsed.1, "script", src, &prelude_ctx);
v6or.validate();
if !v6or.errors.is_empty() {
report_invalidation(v6or.errors);
return;
}
prelude_fn_info.extend(&mut v6or.fn_info.into_iter());
let mut proc = Process {
input: "script",
src,
locals: vec![],
prelude: prelude_ctx,
ast: &parsed.0,
span: parsed.1,
fn_info: prelude_fn_info,
};
let result = proc.eval();
match result {
Ok(result) => println!("{}", result),
Err(err) => report_panic(err),
}
}
pub fn main() {
let src = "
loop (100000, 1) with {
(1, acc) -> acc
(n, acc) -> recur (dec (n), add (n, acc))
}
";
run(src);
// struct_scalpel::print_dissection_info::<value::Value>()
// struct_scalpel::print_dissection_info::<parser::Ast>();
// println!("{}", std::mem::size_of::<parser::Ast>())
}

193
src/old_value.rs Normal file
View File

@ -0,0 +1,193 @@
use crate::base::*;
use crate::parser::*;
use crate::spans::*;
use imbl::*;
use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use struct_scalpel::Dissectible;
#[derive(Clone, Debug)]
pub struct Fn<'src> {
pub name: String,
pub body: &'src Vec<Spanned<Ast>>,
pub doc: Option<String>,
pub enclosing: Vec<(String, Value<'src>)>,
pub has_run: bool,
pub input: &'static str,
pub src: &'static str,
}
#[derive(Debug, Dissectible)]
pub enum Value<'src> {
Nil,
Placeholder,
Boolean(bool),
Number(f64),
Keyword(&'static str),
InternedString(&'static str),
AllocatedString(Rc<String>),
// on the heap for now
Tuple(Rc<Vec<Self>>),
Args(Rc<Vec<Self>>),
List(Vector<Self>),
Dict(HashMap<&'static str, Self>),
Box(&'static str, Rc<RefCell<Self>>),
Fn(Rc<RefCell<Fn<'src>>>),
FnDecl(&'static str),
Base(BaseFn<'src>),
Recur(Vec<Self>),
// Set(HashSet<Self>),
// Sets are hard
// Sets require Eq
// Eq is not implemented on f64, because NaNs
// We could use ordered_float::NotNan
// Let's defer that
// We're not really using sets in Ludus
// Other things we're not implementing yet:
// pkgs, nses, tests
}
impl<'src> Clone for Value<'src> {
fn clone(&self) -> Value<'src> {
match self {
Value::Nil => Value::Nil,
Value::Boolean(b) => Value::Boolean(*b),
Value::InternedString(s) => Value::InternedString(s),
Value::AllocatedString(s) => Value::AllocatedString(s.clone()),
Value::Keyword(s) => Value::Keyword(s),
Value::Number(n) => Value::Number(*n),
Value::Tuple(t) => Value::Tuple(t.clone()),
Value::Args(a) => Value::Args(a.clone()),
Value::Fn(f) => Value::Fn(f.clone()),
Value::FnDecl(name) => Value::FnDecl(name),
Value::List(l) => Value::List(l.clone()),
Value::Dict(d) => Value::Dict(d.clone()),
Value::Box(name, b) => Value::Box(name, b.clone()),
Value::Placeholder => Value::Placeholder,
Value::Base(b) => Value::Base(b.clone()),
Value::Recur(..) => unreachable!(),
}
}
}
impl fmt::Display for Value<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Value::Nil => write!(f, "nil"),
Value::Boolean(b) => write!(f, "{b}"),
Value::Number(n) => write!(f, "{n}"),
Value::Keyword(k) => write!(f, ":{k}"),
Value::InternedString(s) => write!(f, "\"{s}\""),
Value::AllocatedString(s) => write!(f, "\"{s}\""),
Value::Fn(fun) => write!(f, "fn {}", fun.borrow().name),
Value::FnDecl(name) => write!(f, "fn {name}"),
Value::Tuple(t) | Value::Args(t) => write!(
f,
"({})",
t.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", ")
),
Value::List(l) => write!(
f,
"[{}]",
l.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", ")
),
Value::Dict(d) => write!(
f,
"#{{{}}}",
d.iter()
.map(|(k, v)| format!(":{k} {v}"))
.collect::<Vec<_>>()
.join(", ")
),
Value::Box(name, value) => {
write!(
f,
"box {}: [{}]",
name,
&value.try_borrow().unwrap().to_string()
)
}
Value::Placeholder => write!(f, "_"),
Value::Base(..) => unreachable!(),
Value::Recur(..) => unreachable!(),
}
}
}
impl Value<'_> {
pub fn bool(&self) -> bool {
!matches!(self, Value::Nil | Value::Boolean(false))
}
}
impl<'src> PartialEq for Value<'src> {
fn eq(&self, other: &Value<'src>) -> bool {
match (self, other) {
// value equality types
(Value::Nil, Value::Nil) => true,
(Value::Boolean(x), Value::Boolean(y)) => x == y,
(Value::Number(x), Value::Number(y)) => x == y,
(Value::InternedString(x), Value::InternedString(y)) => x == y,
(Value::AllocatedString(x), Value::AllocatedString(y)) => x == y,
(Value::InternedString(x), Value::AllocatedString(y)) => *x == **y,
(Value::AllocatedString(x), Value::InternedString(y)) => **x == *y,
(Value::Keyword(x), Value::Keyword(y)) => x == y,
(Value::Tuple(x), Value::Tuple(y)) => x == y,
(Value::List(x), Value::List(y)) => x == y,
(Value::Dict(x), Value::Dict(y)) => x == y,
// reference equality types
(Value::Fn(x), Value::Fn(y)) => {
Rc::<RefCell<Fn<'_>>>::as_ptr(x) == Rc::<RefCell<Fn<'_>>>::as_ptr(y)
}
(Value::Box(_, x), Value::Box(_, y)) => {
Rc::<RefCell<Value<'_>>>::as_ptr(x) == Rc::<RefCell<Value<'_>>>::as_ptr(y)
}
_ => false,
}
}
}
impl Eq for Value<'_> {}
impl Value<'_> {
pub fn interpolate(&self) -> String {
match self {
Value::Nil => String::new(),
Value::Boolean(b) => format!("{b}"),
Value::Number(n) => format!("{n}"),
Value::Keyword(k) => format!(":{k}"),
Value::AllocatedString(s) => format!("{s}"),
Value::InternedString(s) => s.to_string(),
Value::Box(_, x) => x.borrow().interpolate(),
Value::Tuple(xs) => xs
.iter()
.map(|x| x.interpolate())
.collect::<Vec<_>>()
.join(", "),
Value::List(xs) => xs
.iter()
.map(|x| x.interpolate())
.collect::<Vec<_>>()
.join(", "),
Value::Dict(xs) => xs
.iter()
.map(|(k, v)| format!(":{} {}", k, v.interpolate()))
.collect::<Vec<_>>()
.join(", "),
Value::Fn(x) => format!("fn {}", x.borrow().name),
Value::FnDecl(name) => format!("fn {name}"),
Value::Placeholder => unreachable!(),
Value::Args(_) => unreachable!(),
Value::Recur(_) => unreachable!(),
Value::Base(_) => unreachable!(),
}
}
}

533
src/old_vm.rs Normal file
View File

@ -0,0 +1,533 @@
use crate::base::*;
use crate::parser::*;
use crate::value::*;
use imbl::HashMap;
use imbl::Vector;
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone, Debug)]
pub struct LudusError {
pub msg: String,
}
// oy
// lifetimes are a mess
// I need 'src kind of everywhere
// But (maybe) using 'src in eval
// for ctx
// means I can't borrow it mutably
// I guess the question is how to get
// the branches for Ast::Block and Ast::If
// to work with a mutable borrow of ctx
// pub struct Ctx<'src> {
// pub locals: Vec<(&'src str, Value<'src>)>,
// // pub names: Vec<&'src str>,
// // pub values: Vec<Value<'src>>,
// }
// impl<'src> Ctx<'src> {
// pub fn resolve(&self, name: &'src str) -> Value {
// if let Some((_, val)) = self.locals.iter().rev().find(|(bound, _)| *bound == name) {
// val.clone()
// } else {
// unreachable!()
// }
// }
// pub fn store(&mut self, name: &'src str, value: Value<'src>) {
// self.locals.push((name, value));
// }
// }
type Context<'src> = Vec<(String, Value<'src>)>;
pub fn match_eq<T, U>(x: T, y: T, z: U) -> Option<U>
where
T: PartialEq,
{
if x == y {
Some(z)
} else {
None
}
}
pub fn match_pattern<'src, 'a>(
patt: &Pattern,
val: &Value<'src>,
ctx: &'a mut Context<'src>,
) -> Option<&'a mut Context<'src>> {
match (patt, val) {
(Pattern::Nil, Value::Nil) => Some(ctx),
(Pattern::Placeholder, _) => Some(ctx),
(Pattern::Number(x), Value::Number(y)) => match_eq(x, y, ctx),
(Pattern::Boolean(x), Value::Boolean(y)) => match_eq(x, y, ctx),
(Pattern::Keyword(x), Value::Keyword(y)) => match_eq(x, y, ctx),
(Pattern::String(x), Value::InternedString(y)) => match_eq(x, y, ctx),
(Pattern::String(x), Value::AllocatedString(y)) => match_eq(&x.to_string(), y, ctx),
(Pattern::Interpolated(_, StringMatcher(matcher)), Value::InternedString(y)) => {
match matcher(y.to_string()) {
Some(matches) => {
let mut matches = matches
.iter()
.map(|(word, string)| {
(
word.clone(),
Value::AllocatedString(Rc::new(string.clone())),
)
})
.collect::<Vec<_>>();
ctx.append(&mut matches);
Some(ctx)
}
None => None,
}
}
(Pattern::Word(w), val) => {
ctx.push((w.to_string(), val.clone()));
Some(ctx)
}
(Pattern::As(word, type_str), value) => {
let ludus_type = r#type(value);
let type_kw = Value::Keyword(type_str);
if type_kw == ludus_type {
ctx.push((word.to_string(), value.clone()));
Some(ctx)
} else {
None
}
}
// todo: add splats to these match clauses
(Pattern::Tuple(x), Value::Tuple(y)) => {
let has_splat = x
.iter()
.any(|patt| matches!(patt, (Pattern::Splattern(_), _)));
if x.len() > y.len() || (!has_splat && x.len() != y.len()) {
return None;
};
let to = ctx.len();
for i in 0..x.len() {
if let Pattern::Splattern(patt) = &x[i].0 {
let mut list = Vector::new();
for i in i..y.len() {
list.push_back(y[i].clone())
}
let list = Value::List(list);
match_pattern(&patt.0, &list, ctx);
} else if match_pattern(&x[i].0, &y[i], ctx).is_none() {
while ctx.len() > to {
ctx.pop();
}
return None;
}
}
Some(ctx)
}
(Pattern::List(x), Value::List(y)) => {
let has_splat = x
.iter()
.any(|patt| matches!(patt, (Pattern::Splattern(_), _)));
if x.len() > y.len() || (!has_splat && x.len() != y.len()) {
return None;
};
let to = ctx.len();
for (i, (patt, _)) in x.iter().enumerate() {
if let Pattern::Splattern(patt) = &patt {
let list = Value::List(y.skip(i));
match_pattern(&patt.0, &list, ctx);
} else if match_pattern(patt, y.get(i).unwrap(), ctx).is_none() {
while ctx.len() > to {
ctx.pop();
}
return None;
}
}
Some(ctx)
}
// TODO: optimize this on several levels
// - [ ] opportunistic mutation
// - [ ] get rid of all the pointer indirection in word splats
(Pattern::Dict(x), Value::Dict(y)) => {
let has_splat = x
.iter()
.any(|patt| matches!(patt, (Pattern::Splattern(_), _)));
if x.len() > y.len() || (!has_splat && x.len() != y.len()) {
return None;
};
let to = ctx.len();
let mut matched = vec![];
for (pattern, _) in x {
match pattern {
Pattern::Pair(key, patt) => {
if let Some(val) = y.get(key) {
if match_pattern(&patt.0, val, ctx).is_none() {
while ctx.len() > to {
ctx.pop();
}
return None;
} else {
matched.push(key);
}
} else {
return None;
};
}
Pattern::Splattern(pattern) => match pattern.0 {
Pattern::Word(w) => {
// TODO: find a way to take ownership
// this will ALWAYS make structural changes, because of this clone
// we want opportunistic mutation if possible
let mut unmatched = y.clone();
for key in matched.iter() {
unmatched.remove(*key);
}
ctx.push((w.to_string(), Value::Dict(unmatched)));
}
Pattern::Placeholder => (),
_ => unreachable!(),
},
_ => unreachable!(),
}
}
Some(ctx)
}
_ => None,
}
}
pub fn match_clauses<'src>(
value: &Value<'src>,
clauses: &'src [MatchClause],
ctx: &mut Context<'src>,
) -> Result<Value<'src>, LudusError> {
let to = ctx.len();
for MatchClause { patt, body, guard } in clauses.iter() {
if let Some(ctx) = match_pattern(&patt.0, value, ctx) {
let pass_guard = match guard {
None => true,
Some((ast, _)) => {
let guard_res = eval(ast, ctx);
match &guard_res {
Err(_) => return guard_res,
Ok(val) => val.bool(),
}
}
};
if !pass_guard {
while ctx.len() > to {
ctx.pop();
}
continue;
}
let res = eval(&body.0, ctx);
while ctx.len() > to {
ctx.pop();
}
return res;
}
}
Err(LudusError {
msg: "no match".to_string(),
})
}
pub fn apply<'src>(
callee: Value<'src>,
caller: Value<'src>,
ctx: &mut Context,
) -> Result<Value<'src>, LudusError> {
match (callee, caller) {
(Value::Keyword(kw), Value::Dict(dict)) => {
if let Some(val) = dict.get(kw) {
Ok(val.clone())
} else {
Ok(Value::Nil)
}
}
(Value::Dict(dict), Value::Keyword(kw)) => {
if let Some(val) = dict.get(kw) {
Ok(val.clone())
} else {
Ok(Value::Nil)
}
}
(Value::Fn(f), Value::Tuple(args)) => {
let args = Value::Tuple(args);
match_clauses(&args, f.body, ctx)
}
(Value::Fn(_f), Value::Args(_args)) => todo!(),
(_, Value::Keyword(_)) => Ok(Value::Nil),
(_, Value::Args(_)) => Err(LudusError {
msg: "you may only call a function".to_string(),
}),
(Value::Base(f), Value::Tuple(args)) => match f {
Base::Nullary(f) => {
if args.len() != 0 {
Err(LudusError {
msg: "wrong arity: expected 0 arguments".to_string(),
})
} else {
Ok(f())
}
}
Base::Unary(f) => {
if args.len() != 1 {
Err(LudusError {
msg: "wrong arity: expected 1 argument".to_string(),
})
} else {
Ok(f(&args[0]))
}
}
Base::Binary(r#fn) => {
if args.len() != 2 {
Err(LudusError {
msg: "wrong arity: expected 2 arguments".to_string(),
})
} else {
Ok(r#fn(&args[0], &args[1]))
}
}
Base::Ternary(f) => {
if args.len() != 3 {
Err(LudusError {
msg: "wrong arity: expected 3 arguments".to_string(),
})
} else {
Ok(f(&args[0], &args[1], &args[2]))
}
}
},
_ => unreachable!(),
}
}
pub fn eval<'src, 'a>(
ast: &'src Ast,
ctx: &'a mut Vec<(String, Value<'src>)>,
) -> Result<Value<'src>, LudusError> {
match ast {
Ast::Nil => Ok(Value::Nil),
Ast::Boolean(b) => Ok(Value::Boolean(*b)),
Ast::Number(n) => Ok(Value::Number(*n)),
Ast::Keyword(k) => Ok(Value::Keyword(k)),
Ast::String(s) => Ok(Value::InternedString(s)),
Ast::Interpolated(parts) => {
let mut interpolated = String::new();
for part in parts {
match &part.0 {
StringPart::Data(s) => interpolated.push_str(s.as_str()),
StringPart::Word(w) => {
let val = if let Some((_, value)) =
ctx.iter().rev().find(|(name, _)| w == name)
{
value.clone()
} else {
return Err(LudusError {
msg: format!("unbound name {w}"),
});
};
interpolated.push_str(val.interpolate().as_str())
}
StringPart::Inline(_) => unreachable!(),
}
}
Ok(Value::AllocatedString(Rc::new(interpolated)))
}
Ast::Block(exprs) => {
let to = ctx.len();
let mut result = Value::Nil;
for (expr, _) in exprs {
result = eval(expr, ctx)?;
}
while ctx.len() > to {
ctx.pop();
}
Ok(result)
}
Ast::If(cond, if_true, if_false) => {
let truthy = eval(&cond.0, ctx)?.bool();
if truthy {
eval(&if_true.0, ctx)
} else {
eval(&if_false.0, ctx)
}
}
Ast::List(members) => {
let mut vect = Vector::new();
for member in members {
if let Ast::Splat(_) = member.0 {
let to_splat = eval(&member.0, ctx)?;
match to_splat {
Value::List(list) => vect.append(list),
_ => {
return Err(LudusError {
msg: "only lists may be splatted into lists".to_string(),
})
}
}
} else {
vect.push_back(eval(&member.0, ctx)?)
}
}
Ok(Value::List(vect))
}
Ast::Tuple(members) => {
let mut vect = Vec::new();
for member in members {
vect.push(eval(&member.0, ctx)?);
}
Ok(Value::Tuple(Rc::new(vect)))
}
Ast::Word(w) | Ast::Splat(w) => {
let val = if let Some((_, value)) = ctx.iter().rev().find(|(name, _)| w == name) {
value.clone()
} else {
return Err(LudusError {
msg: format!("unbound name {w}"),
});
};
Ok(val)
}
Ast::Let(patt, expr) => {
let val = eval(&expr.0, ctx)?;
match match_pattern(&patt.0, &val, ctx) {
Some(_) => Ok(val),
None => Err(LudusError {
msg: "No match".to_string(),
}),
}
}
Ast::Placeholder => Ok(Value::Placeholder),
Ast::Error => unreachable!(),
Ast::Arguments(a) => {
let mut args = vec![];
for (arg, _) in a.iter() {
let arg = eval(arg, ctx)?;
args.push(arg);
}
if args.iter().any(|arg| matches!(arg, Value::Placeholder)) {
Ok(Value::Args(Rc::new(args)))
} else {
Ok(Value::Tuple(Rc::new(args)))
}
}
Ast::Dict(terms) => {
let mut dict = HashMap::new();
for term in terms {
let (term, _) = term;
match term {
Ast::Pair(key, value) => {
let value = eval(&value.0, ctx)?;
dict.insert(*key, value);
}
Ast::Splat(_) => {
let resolved = eval(term, ctx)?;
let Value::Dict(to_splat) = resolved else {
return Err(LudusError {
msg: "cannot splat non-dict into dict".to_string(),
});
};
dict = to_splat.union(dict);
}
_ => unreachable!(),
}
}
Ok(Value::Dict(dict))
}
Ast::Box(name, expr) => {
let val = eval(&expr.0, ctx)?;
let boxed = Value::Box(name, Rc::new(RefCell::new(val)));
ctx.push((name.to_string(), boxed.clone()));
Ok(boxed)
}
Ast::Synthetic(root, first, rest) => {
let root = eval(&root.0, ctx)?;
let first = eval(&first.0, ctx)?;
let mut curr = apply(root, first, ctx)?;
for term in rest.iter() {
let next = eval(&term.0, ctx)?;
curr = apply(curr, next, ctx)?;
}
Ok(curr)
}
Ast::When(clauses) => {
for clause in clauses.iter() {
let WhenClause { cond, body } = &clause.0;
if eval(&cond.0, ctx)?.bool() {
return eval(&body.0, ctx);
};
}
Err(LudusError {
msg: "no match".to_string(),
})
}
Ast::Match(value, clauses) => {
let value = eval(&value.0, ctx)?;
match_clauses(&value, clauses, ctx)
}
Ast::Fn(name, clauses, doc) => {
let doc = doc.map(|s| s.to_string());
let the_fn = Value::Fn::<'src>(Rc::new(Fn::<'src> {
name: name.to_string(),
body: clauses,
doc,
}));
ctx.push((name.to_string(), the_fn.clone()));
Ok(the_fn)
}
Ast::FnDeclaration(_name) => todo!(),
Ast::Panic(msg) => {
let msg = eval(&msg.0, ctx)?;
Err(LudusError {
msg: msg.to_string(),
})
}
Ast::Repeat(times, body) => {
let times_num = match eval(&times.0, ctx) {
Ok(Value::Number(n)) => n as usize,
_ => {
return Err(LudusError {
msg: "repeat may only take numbers".to_string(),
})
}
};
for _ in 0..times_num {
eval(&body.0, ctx)?;
}
Ok(Value::Nil)
}
Ast::Do(terms) => {
let mut result = eval(&terms[0].0, ctx)?;
for (term, _) in terms.iter().skip(1) {
let next = eval(term, ctx)?;
let arg = Value::Tuple(Rc::new(vec![result]));
result = apply(next, arg, ctx)?;
}
Ok(result)
}
Ast::Pair(..) => {
unreachable!()
}
Ast::Loop(init, clauses) => {
let mut args = eval(&init.0, ctx)?;
loop {
let result = match_clauses(&args, clauses, ctx)?;
if let Value::Recur(recur_args) = result {
args = Value::Tuple(Rc::new(recur_args));
} else {
return Ok(result);
}
}
}
Ast::Recur(args) => {
let mut vect = Vec::new();
for arg in args {
vect.push(eval(&arg.0, ctx)?);
}
Ok(Value::Recur(vect))
}
}
}

216
src/op.rs Normal file
View File

@ -0,0 +1,216 @@
use num_derive::{FromPrimitive, ToPrimitive};
#[derive(Copy, Clone, Debug, PartialEq, Eq, FromPrimitive, ToPrimitive)]
pub enum Op {
Noop,
Nothing,
Nil,
True,
False,
Constant,
Jump,
JumpIfFalse,
JumpIfTrue,
Pop,
PopN,
PushBinding,
PushGlobal,
Store,
StoreN,
Stash,
Load,
LoadN,
ResetMatch,
UnconditionalMatch,
MatchNil,
MatchTrue,
MatchFalse,
MatchConstant,
MatchString,
PushStringMatches,
MatchType,
MatchTuple,
MatchSplattedTuple,
PushTuple,
LoadTuple,
LoadSplattedTuple,
MatchList,
MatchSplattedList,
LoadList,
LoadSplattedList,
PushList,
AppendList,
ConcatList,
PushDict,
AppendDict,
ConcatDict,
LoadDictValue,
MatchDict,
MatchSplattedDict,
DropDictEntry,
PushBox,
GetKey,
PanicWhenFallthrough,
JumpIfNoMatch,
JumpIfMatch,
PanicNoMatch,
PanicNoLetMatch,
PanicNoFnMatch,
TypeOf,
JumpBack,
JumpIfZero,
Duplicate,
Decrement,
ToInt,
MatchDepth,
Panic,
EmptyString,
ConcatStrings,
Stringify,
Call,
TailCall,
Return,
Partial,
Eq,
Add,
Sub,
Mult,
Div,
Unbox,
BoxStore,
Assert,
Get,
At,
// Inc,
// Dec,
// Gt,
// Gte,
// Lt,
// Lte,
// Mod,
// First,
// Rest
// Sqrt,
// Append,
Not,
Print,
SetUpvalue,
GetUpvalue,
Msg,
LoadMessage,
NextMessage,
MatchMessage,
ClearMessage,
SendMethod,
LoadScrutinee,
}
impl std::fmt::Display for Op {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use Op::*;
let rep = match self {
Msg => "msg",
Noop => "noop",
Nothing => "nothing",
Nil => "nil",
True => "true",
False => "false",
Constant => "constant",
Jump => "jump",
JumpIfFalse => "jump_if_false",
JumpIfTrue => "jump_if_true",
Pop => "pop",
PopN => "pop_n",
PushBinding => "push_binding",
PushGlobal => "push_global",
Store => "store",
StoreN => "store_n",
Stash => "stash",
Load => "load",
LoadN => "load_n",
UnconditionalMatch => "match",
MatchNil => "match_nil",
MatchTrue => "match_true",
MatchFalse => "match_false",
ResetMatch => "reset_match",
MatchConstant => "match_constant",
MatchString => "match_string",
PushStringMatches => "push_string_matches",
MatchType => "match_type",
MatchTuple => "match_tuple",
MatchSplattedTuple => "match_splatted_tuple",
PushTuple => "push_tuple",
LoadTuple => "load_tuple",
LoadSplattedTuple => "load_splatted_tuple",
MatchList => "match_list",
MatchSplattedList => "match_splatted_list",
LoadList => "load_list",
LoadSplattedList => "load_splatted_list",
PushList => "push_list",
AppendList => "append_list",
ConcatList => "concat_list",
PushDict => "push_dict",
AppendDict => "append_dict",
ConcatDict => "concat_dict",
LoadDictValue => "load_dict_value",
MatchDict => "match_dict",
MatchSplattedDict => "match_splatted_dict",
DropDictEntry => "drop_dict_entry",
PushBox => "push_box",
GetKey => "get_key",
PanicWhenFallthrough => "panic_no_when",
JumpIfNoMatch => "jump_if_no_match",
JumpIfMatch => "jump_if_match",
PanicNoMatch => "panic_no_match",
PanicNoFnMatch => "panic_no_fn_match",
PanicNoLetMatch => "panic_no_let_match",
TypeOf => "type_of",
JumpBack => "jump_back",
JumpIfZero => "jump_if_zero",
Decrement => "decrement",
ToInt => "truncate",
Duplicate => "duplicate",
MatchDepth => "match_depth",
Panic => "panic",
EmptyString => "empty_string",
ConcatStrings => "concat_strings",
Stringify => "stringify",
Print => "print",
Eq => "eq",
Add => "add",
Sub => "sub",
Mult => "mult",
Div => "div",
Unbox => "unbox",
BoxStore => "box_store",
Assert => "assert",
Get => "get",
At => "at",
Not => "not",
Call => "call",
Return => "return",
Partial => "partial",
TailCall => "tail_call",
SetUpvalue => "set_upvalue",
GetUpvalue => "get_upvalue",
LoadMessage => "load_message",
NextMessage => "next_message",
MatchMessage => "match_message",
ClearMessage => "clear_message",
SendMethod => "send_method",
LoadScrutinee => "load_scrutinee",
};
write!(f, "{rep}")
}
}

47
src/panic.rs Normal file
View File

@ -0,0 +1,47 @@
use crate::errors::panic;
use crate::value::Value;
use crate::vm::CallFrame;
#[derive(Debug, Clone, PartialEq)]
pub enum PanicMsg {
NoLetMatch,
NoFnMatch,
NoMatch,
Generic(String),
}
impl std::fmt::Display for PanicMsg {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use PanicMsg::*;
match self {
NoLetMatch => write!(f, "no match in `let`"),
NoFnMatch => write!(f, "no match calling fn"),
NoMatch => write!(f, "no match in `match` form"),
Generic(s) => write!(f, "{s}"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Panic {
pub msg: PanicMsg,
pub scrutinee: Option<Value>,
pub call_stack: Vec<CallFrame>,
}
fn frame_dump(frame: &CallFrame) -> String {
let dump = format!("stack name: {}\nspans: {:?}", frame, frame.chunk().spans);
dump
}
impl std::fmt::Display for Panic {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let stub_trace = self
.call_stack
.iter()
.map(frame_dump)
.collect::<Vec<_>>()
.join("\n");
write!(f, "Panic: {}\n{stub_trace}", self.msg)
}
}

683
src/parser.rs Normal file
View File

@ -0,0 +1,683 @@
// TODO: move AST to its own module
// TODO: remove StringMatcher cruft
// TODO: good error messages?
use crate::ast::{Ast, StringPart};
use crate::lexer::*;
use crate::spans::*;
use chumsky::{input::ValueInput, prelude::*, recursive::Recursive};
use std::fmt;
pub struct StringMatcher();
impl PartialEq for StringMatcher {
fn eq(&self, _other: &StringMatcher) -> bool {
true
}
}
impl Clone for StringMatcher {
fn clone(&self) -> StringMatcher {
unreachable!()
}
}
impl fmt::Display for StringMatcher {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "string matcher")
}
}
impl fmt::Debug for StringMatcher {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "string matcher")
}
}
fn is_word_char(c: char) -> bool {
if c.is_ascii_alphanumeric() {
return true;
};
matches!(c, '_' | '/' | '?' | '!')
}
fn parse_string(s: &'static str, span: SimpleSpan) -> Result<Vec<Spanned<StringPart>>, String> {
// println!("parsing string pattern: {s}");
let mut parts = vec![];
let mut current_part = String::new();
let mut start = span.start;
let mut is_word = false;
let mut chars = s.char_indices();
while let Some((i, char)) = chars.next() {
match char {
'{' => {
if is_word {
return Err("interpolations must only contain words".to_string());
};
match chars.next() {
None => return Err("unclosed brace".to_string()),
Some((_, '{')) => current_part.push('{'),
Some((i, c)) => {
if !current_part.is_empty() {
parts.push((
StringPart::Data(current_part),
SimpleSpan::new(span.context(), start..start + i),
));
};
current_part = String::new();
start = i;
is_word = true;
if c.is_ascii_lowercase() {
current_part.push(c);
} else {
return Err("interpolations must only contain words".to_string());
}
}
}
}
'}' => {
if is_word {
parts.push((
StringPart::Word(current_part.leak()),
SimpleSpan::new(span.context(), start..start + i),
));
current_part = String::new();
start = i;
is_word = false;
} else {
match chars.next() {
None => return Err("unclosed brace".to_string()),
Some((_, c)) => current_part.push(c),
}
}
}
_ => {
if is_word {
if is_word_char(char) {
current_part.push(char)
} else {
return Err("interpolations must only contain words".to_string());
}
} else {
current_part.push(char)
}
}
}
}
if current_part == s {
parts.push((
StringPart::Inline(current_part),
SimpleSpan::new(span.context(), start..span.end),
))
} else if !current_part.is_empty() {
let part_len = current_part.len();
parts.push((
StringPart::Data(current_part),
SimpleSpan::new(span.context(), start..part_len),
))
}
Ok(parts)
}
pub fn parser<I>(
) -> impl Parser<'static, I, Spanned<Ast>, extra::Err<Rich<'static, Token, Span>>> + Clone
where
I: ValueInput<'static, Token = Token, Span = Span>,
{
use Ast::*;
let mut expr = Recursive::declare();
let mut pattern = Recursive::declare();
let mut simple = Recursive::declare();
let mut nonbinding = Recursive::declare();
let separators = recursive(|separators| {
just(Token::Punctuation(","))
.or(just(Token::Punctuation("\n")))
.then(separators.clone().repeated())
})
.labelled("separator");
let terminators = recursive(|terminators| {
just(Token::Punctuation(";"))
.or(just(Token::Punctuation("\n")))
.then(terminators.clone().repeated())
})
.labelled("terminator");
let placeholder_pattern =
select! {Token::Punctuation("_") => PlaceholderPattern}.map_with(|p, e| (p, e.span()));
let word_pattern = select! { Token::Word(w) => WordPattern(w) }.map_with(|w, e| (w, e.span()));
let atom_pattern = select! {
Token::Nil => NilPattern,
Token::Boolean(b) => BooleanPattern(b),
Token::Number(n) => NumberPattern(n),
Token::Keyword(k) => KeywordPattern(k),
}
.map_with(|a, e| (a, e.span()));
let string_pattern = select! {Token::String(s) => s}.try_map_with(|s, e| {
let parsed = parse_string(s, e.span());
match parsed {
Ok(parts) => match parts[0] {
(StringPart::Inline(_), _) => Ok((StringPattern(s), e.span())),
_ => Ok((InterpolatedPattern(parts.clone()), e.span())),
},
Err(msg) => Err(Rich::custom(e.span(), msg)),
}
});
let bare_splat = just(Token::Punctuation("...")).map_with(|_, e| {
(
Splattern(Box::new((PlaceholderPattern, e.span()))),
e.span(),
)
});
let splattable = word_pattern.or(placeholder_pattern);
let patt_splat = just(Token::Punctuation("..."))
.ignore_then(splattable)
.map_with(|x, e| (Splattern(Box::new(x)), e.span()));
let splattern = patt_splat.or(bare_splat);
let tuple_pattern = pattern
.clone()
.or(splattern.clone())
.separated_by(separators.clone())
.allow_leading()
.allow_trailing()
.collect()
.delimited_by(just(Token::Punctuation("(")), just(Token::Punctuation(")")))
.map_with(|tuple, e| (TuplePattern(tuple), e.span()))
.labelled("tuple pattern");
let list_pattern = pattern
.clone()
.or(splattern.clone())
.separated_by(separators.clone())
.allow_leading()
.allow_trailing()
.collect()
.delimited_by(just(Token::Punctuation("[")), just(Token::Punctuation("]")))
.map_with(|list, e| (ListPattern(list), e.span()))
.labelled("list pattern");
let key_pair_pattern = select! {Token::Keyword(k) => k}
.then(pattern.clone())
.map_with(|(key, patt), e| (KeyPairPattern(key, Box::new(patt)), e.span()));
let shorthand_pattern = select! {Token::Word(w) => w}.map_with(|w, e| {
(
KeyPairPattern(w, Box::new((WordPattern(w), e.span()))),
e.span(),
)
});
let str_pair_pattern = select! {Token::String(s) => s}
.then(pattern.clone())
.map_with(|(key, patt), e| (StrPairPattern(key, Box::new(patt)), e.span()));
let dict_pattern = key_pair_pattern
.or(shorthand_pattern)
.or(str_pair_pattern)
.or(splattern.clone())
.labelled("pair pattern")
.separated_by(separators.clone())
.allow_leading()
.allow_trailing()
.collect()
.delimited_by(
just(Token::Punctuation("#{")),
just(Token::Punctuation("}")),
)
.map_with(|dict, e| (DictPattern(dict), e.span()));
let keyword = select! {Token::Keyword(k) => Keyword(k)}
.map_with(|k, e| (k, e.span()))
.labelled("keyword");
let as_pattern = select! {Token::Word(w) => w}
.then_ignore(just(Token::Reserved("as")))
.then(select! {Token::Keyword(k) => k})
.labelled("keyword")
.map_with(|(w, t), e| (AsPattern(w, t), e.span()));
pattern.define(
atom_pattern
.or(string_pattern)
.or(as_pattern)
.or(word_pattern)
.or(placeholder_pattern)
.or(tuple_pattern.clone())
.or(list_pattern)
.or(dict_pattern)
.labelled("pattern"),
);
let placeholder =
select! {Token::Punctuation("_") => Placeholder}.map_with(|p, e| (p, e.span()));
let word = select! { Token::Word(w) => Word(w) }
.map_with(|w, e| (w, e.span()))
.labelled("word");
let value = select! {
Token::Nil => Nil,
Token::Boolean(b) => Boolean(b),
Token::Number(n) => Number(n),
}
.map_with(|v, e| (v, e.span()));
let string = select! {Token::String(s) => s}.try_map_with(|s, e| {
let parsed = parse_string(s, e.span());
match parsed {
Ok(parts) => match parts[0] {
(StringPart::Inline(_), _) => Ok((String(s), e.span())),
_ => Ok((Interpolated(parts), e.span())),
},
Err(msg) => Err(Rich::custom(e.span(), msg)),
}
});
let tuple = simple
.clone()
.separated_by(separators.clone())
.allow_leading()
.allow_trailing()
.collect()
.delimited_by(just(Token::Punctuation("(")), just(Token::Punctuation(")")))
.map_with(|tuple, e| (Tuple(tuple), e.span()))
.labelled("tuple");
let args = simple
.clone()
.or(placeholder)
.separated_by(separators.clone())
.allow_leading()
.allow_trailing()
.collect()
.delimited_by(just(Token::Punctuation("(")), just(Token::Punctuation(")")))
.map_with(|args, e| (Arguments(args), e.span()))
.labelled("args");
let or = just(Token::Reserved("or")).map_with(|_, e| (Or, e.span()));
let and = just(Token::Reserved("and")).map_with(|_, e| (And, e.span()));
let method = select!(Token::Method(m) => m)
.then(tuple.clone())
.map_with(|(m, t), e| (Ast::Method(m, Box::new(t)), e.span()))
.labelled("method");
let synth_root = or.or(and).or(word).or(keyword);
let synth_term = keyword.or(args).or(method);
let synthetic = synth_root
.then(synth_term.clone())
.then(synth_term.clone().repeated().collect())
.map_with(|((root, first), rest), e| {
(Synthetic(Box::new(root), Box::new(first), rest), e.span())
});
let splat = just(Token::Punctuation("..."))
.ignore_then(word)
.map_with(|(w, _), e| {
(
Splat(if let Word(w) = w { w } else { unreachable!() }),
e.span(),
)
})
.labelled("...");
let list = simple
.clone()
.or(splat.clone())
.separated_by(separators.clone())
.allow_leading()
.allow_trailing()
.collect()
.delimited_by(just(Token::Punctuation("[")), just(Token::Punctuation("]")))
.map_with(|list, e| (List(list), e.span()));
let key_pair = select! {Token::Keyword(k) => k}
.then(simple.clone())
.map_with(|(key, value), e| (KeywordPair(key, Box::new(value)), e.span()));
let shorthand = select! {Token::Word(w) => w}
.map_with(|w, e| (KeywordPair(w, Box::new((Word(w), e.span()))), e.span()));
let str_pair = select! {Token::String(s) => s}
.then(simple.clone())
.map_with(|(key, value), e| (StringPair(key, Box::new(value)), e.span()));
let dict = key_pair
.or(shorthand)
.or(str_pair)
.or(splat.clone())
.separated_by(separators.clone())
.allow_leading()
.allow_trailing()
.collect()
.delimited_by(
just(Token::Punctuation("#{")),
just(Token::Punctuation("}")),
)
.map_with(|dict, e| (Dict(dict), e.span()));
let recur = just(Token::Reserved("recur"))
.ignore_then(tuple.clone())
.map_with(|args, e| {
let (Tuple(args), _) = args else {
unreachable!()
};
(Recur(args), e.span())
});
let block = expr
.clone()
.separated_by(terminators.clone())
.allow_leading()
.allow_trailing()
.collect()
.delimited_by(just(Token::Punctuation("{")), just(Token::Punctuation("}")))
.map_with(|block, e| (Block(block), e.span()))
.recover_with(via_parser(nested_delimiters(
Token::Punctuation("{"),
Token::Punctuation("}"),
[
(Token::Punctuation("("), Token::Punctuation(")")),
(Token::Punctuation("["), Token::Punctuation("]")),
],
|span| (Error, span),
)));
let r#if = just(Token::Reserved("if"))
.ignore_then(simple.clone())
.then_ignore(terminators.clone().or_not())
.then_ignore(just(Token::Reserved("then")))
.then(expr.clone())
.then_ignore(terminators.clone().or_not())
.then_ignore(just(Token::Reserved("else")))
.then(expr.clone())
.map_with(|((condition, then_branch), else_branch), e| {
(
If(
Box::new(condition),
Box::new(then_branch),
Box::new(else_branch),
),
e.span(),
)
});
let when_clause = simple
.clone()
.then_ignore(just(Token::Punctuation("->")))
.then(expr.clone())
.map_with(|(cond, body), e| (WhenClause(Box::new(cond), Box::new(body)), e.span()));
let when = just(Token::Reserved("when"))
.ignore_then(
when_clause
.separated_by(terminators.clone())
.allow_trailing()
.allow_leading()
.collect()
.delimited_by(just(Token::Punctuation("{")), just(Token::Punctuation("}"))),
)
.map_with(|clauses, e| (When(clauses), e.span()));
let guarded_clause = pattern
.clone()
.then_ignore(just(Token::Reserved("if")))
.then(simple.clone())
.then_ignore(just(Token::Punctuation("->")))
.then(expr.clone())
.map_with(|((patt, guard), body), e| {
(
MatchClause(Box::new(patt), Box::new(Some(guard)), Box::new(body)),
e.span(),
)
});
let match_clause = pattern
.clone()
.then_ignore(just(Token::Punctuation("->")))
.then(expr.clone())
.map_with(|(patt, body), e| {
(
MatchClause(Box::new(patt), Box::new(None), Box::new(body)),
e.span(),
)
});
let r#match = just(Token::Reserved("match"))
.ignore_then(simple.clone())
.then_ignore(just(Token::Reserved("with")))
.then(
match_clause
.clone()
.or(guarded_clause.clone())
.separated_by(terminators.clone())
.allow_leading()
.allow_trailing()
.collect()
.delimited_by(just(Token::Punctuation("{")), just(Token::Punctuation("}"))),
)
.map_with(|(expr, clauses), e| (Match(Box::new(expr), clauses), e.span()));
let receive = just(Token::Reserved("receive"))
.ignore_then(
match_clause
.clone()
.or(guarded_clause)
.separated_by(terminators.clone())
.allow_leading()
.allow_trailing()
.collect()
.delimited_by(just(Token::Punctuation("{")), just(Token::Punctuation("}"))),
)
.map_with(|clauses, e| (Receive(clauses), e.span()));
let conditional = when.or(r#if).or(r#match).or(receive);
let panic = just(Token::Reserved("panic!"))
.ignore_then(nonbinding.clone())
.map_with(|expr, e| (Panic(Box::new(expr)), e.span()));
let r#do = just(Token::Reserved("do"))
.ignore_then(
simple
.clone()
.separated_by(
just(Token::Punctuation(">")).then(just(Token::Punctuation("\n")).repeated()),
)
.collect(),
)
.map_with(|exprs, e| (Do(exprs), e.span()));
let repeat = just(Token::Reserved("repeat"))
.ignore_then(simple.clone())
.then(block.clone())
.map_with(|(count, body), e| (Repeat(Box::new(count), Box::new(body)), e.span()));
let fn_guarded = tuple_pattern
.clone()
.then_ignore(just(Token::Reserved("if")))
.then(simple.clone())
.then_ignore(just(Token::Punctuation("->")))
.then(nonbinding.clone())
.map_with(|((patt, guard), body), e| {
(
MatchClause(Box::new(patt), Box::new(Some(guard)), Box::new(body)),
e.span(),
)
})
.labelled("function clause");
let fn_unguarded = tuple_pattern
.clone()
.then_ignore(just(Token::Punctuation("->")))
.then(nonbinding.clone())
.map_with(|(patt, body), e| {
(
MatchClause(Box::new(patt), Box::new(None), Box::new(body)),
e.span(),
)
})
.labelled("function clause");
let fn_clause = fn_guarded.clone().or(fn_unguarded.clone());
let lambda = just(Token::Reserved("fn"))
.ignore_then(fn_unguarded.clone())
.map_with(|clause, e| {
(
Fn("", Box::new((Ast::FnBody(vec![clause]), e.span())), None),
e.span(),
)
});
let fn_clauses = fn_clause
.clone()
.separated_by(terminators.clone())
.allow_leading()
.allow_trailing()
.collect();
let loop_multiclause = fn_clauses
.clone()
.delimited_by(just(Token::Punctuation("{")), just(Token::Punctuation("}")));
let fn_single_clause = fn_clause.clone().map_with(|c, _| vec![c]);
let r#loop = just(Token::Reserved("loop"))
.ignore_then(tuple.clone())
.then_ignore(just(Token::Reserved("with")))
.then(loop_multiclause.clone().or(fn_single_clause.clone()))
.map_with(|(init, body), e| (Loop(Box::new(init), body), e.span()));
simple.define(
synthetic
.or(recur)
.or(word)
.or(keyword)
.or(value)
.or(tuple.clone())
.or(list)
.or(dict)
.or(panic)
.or(string)
.or(r#do)
.or(lambda.clone())
.labelled("simple expression"),
);
nonbinding.define(
simple
.clone()
.or(conditional)
.or(block)
.or(repeat)
.or(r#loop)
.labelled("nonbinding expression"),
);
let let_ = just(Token::Reserved("let"))
.ignore_then(pattern.clone())
.then_ignore(just(Token::Punctuation("=")))
.then(nonbinding.clone())
.map_with(|(pattern, expression), e| {
(Let(Box::new(pattern), Box::new(expression)), e.span())
});
let box_ = just(Token::Reserved("box"))
.ignore_then(word)
.then_ignore(just(Token::Punctuation("=")))
.then(nonbinding.clone())
.map_with(|(word, expr), e| {
let name = if let Word(w) = word.0 {
w
} else {
unreachable!()
};
(LBox(name, Box::new(expr)), e.span())
});
let fn_decl = just(Token::Reserved("fn"))
.ignore_then(word)
.map_with(|(word, _), e| {
let name = if let Word(w) = word {
w
} else {
unreachable!()
};
(FnDeclaration(name), e.span())
});
let fn_named = just(Token::Reserved("fn"))
.ignore_then(word)
.then(fn_unguarded.clone())
.map_with(|(word, clause), e| {
let name = if let Word(word) = word.0 {
word
} else {
unreachable!()
};
(
Fn(name, Box::new((Ast::FnBody(vec![clause]), e.span())), None),
e.span(),
)
});
let docstr = select! {Token::String(s) => s};
let fn_multiclause = separators
.clone()
.or_not()
.ignore_then(docstr.or_not())
.then(fn_clauses.clone())
.delimited_by(just(Token::Punctuation("{")), just(Token::Punctuation("}")))
.map_with(|(docstr, clauses), e| (docstr, clauses, e.span()));
let fn_compound = just(Token::Reserved("fn"))
.ignore_then(word)
.then(fn_multiclause)
.map_with(|(word, (docstr, clauses, _)), e| {
let name = if let Word(word) = word.0 {
word
} else {
unreachable!()
};
(
Fn(name, Box::new((Ast::FnBody(clauses), e.span())), docstr),
e.span(),
)
});
let fn_ = fn_named.or(fn_compound).or(fn_decl);
let binding = let_.or(box_).or(fn_);
expr.define(binding.or(nonbinding));
let script = expr
.separated_by(terminators.clone())
.allow_trailing()
.allow_leading()
.collect()
.map_with(|exprs, e| (Block(exprs), e.span()));
script
}

4
src/spans.rs Normal file
View File

@ -0,0 +1,4 @@
use chumsky::prelude::*;
pub type Span = SimpleSpan<usize>;
pub type Spanned<T> = (T, Span);

607
src/validator.rs Normal file
View File

@ -0,0 +1,607 @@
// TODO:
// * [ ] ensure `or` and `and` never get passed by reference
// * [ ] ensure no placeholder in `or` and `and` args
// * [ ] ensure loops have fixed arity (no splats)
// * [ ] ensure fn pattern splats are always highest (and same) arity
use crate::ast::{Ast, StringPart};
use crate::spans::{Span, Spanned};
use crate::value::{Key, Value};
use std::collections::{HashMap, HashSet};
#[derive(Clone, Debug, PartialEq)]
pub struct VErr<'a> {
pub msg: String,
pub span: &'a Span,
pub input: &'static str,
pub src: &'static str,
}
impl<'a> VErr<'a> {
pub fn new(msg: String, span: &'a Span, input: &'static str, src: &'static str) -> VErr<'a> {
VErr {
msg,
span,
input,
src,
}
}
}
#[derive(Clone, Debug, PartialEq)]
struct VStatus {
tail_position: bool,
in_loop: bool,
loop_arity: u8,
last_term: bool,
has_placeholder: bool,
used_bindings: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Arity {
Fixed(u8),
Splat(u8),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FnInfo {
Declared,
Defined(String, HashSet<Arity>, HashSet<String>),
Unknown,
}
fn match_arities(arities: &HashSet<Arity>, num_args: u8) -> bool {
arities.iter().any(|arity| match arity {
Arity::Fixed(n) => *n == num_args,
Arity::Splat(n) => *n <= num_args,
})
}
#[derive(Debug, PartialEq)]
pub struct Validator<'a> {
pub locals: Vec<(String, &'a Span, FnInfo)>,
pub prelude: imbl::HashMap<Key, Value>,
pub input: &'static str,
pub src: &'static str,
pub ast: &'a Ast,
pub span: &'a Span,
pub errors: Vec<VErr<'a>>,
pub fn_info: HashMap<*const Ast, FnInfo>,
status: VStatus,
}
impl<'a> Validator<'a> {
pub fn new(
ast: &'a Ast,
span: &'a Span,
input: &'static str,
src: &'static str,
prelude: imbl::HashMap<Key, Value>,
) -> Validator<'a> {
Validator {
input,
src,
locals: vec![],
prelude,
ast,
span,
fn_info: std::collections::HashMap::new(),
errors: vec![],
status: VStatus {
tail_position: false,
in_loop: false,
loop_arity: 0,
last_term: false,
has_placeholder: false,
used_bindings: vec![],
},
}
}
fn bind(&mut self, name: String) {
self.locals.push((name, self.span, FnInfo::Unknown));
}
fn declare_fn(&mut self, name: String) {
self.locals.push((name, self.span, FnInfo::Declared));
}
fn define_fn(&mut self, name: String, info: FnInfo) {
let i = self.locals.iter().position(|(n, ..)| *n == name).unwrap();
let new_binding = (name, self.locals[i].1, info);
self.locals[i] = new_binding;
}
fn resolved(&self, name: &'static str) -> bool {
self.locals.iter().any(|(bound, ..)| name == bound.as_str())
|| self
.prelude
.iter()
.any(|(bound, _)| Key::Keyword(name) == *bound)
}
fn bound(&self, name: &str) -> Option<&(String, &Span, FnInfo)> {
match self.locals.iter().rev().find(|(bound, ..)| name == bound) {
Some(binding) => Some(binding),
None => None,
}
}
fn err(&mut self, msg: String) {
self.errors
.push(VErr::new(msg, self.span, self.input, self.src))
}
fn use_name(&mut self, name: String) {
self.status.used_bindings.push(name);
}
fn arity(&mut self) -> Arity {
let Ast::MatchClause(pattern, ..) = self.ast else {
unreachable!("internal Ludus error")
};
let (Ast::TuplePattern(members), _) = pattern.as_ref() else {
unreachable!("internal Ludus error");
};
let last_member = members.last();
match last_member {
None => Arity::Fixed(0),
Some((Ast::Splattern(..), _)) => Arity::Splat(members.len() as u8),
Some(_) => Arity::Fixed(members.len() as u8),
}
}
fn visit(&mut self, node: &'a Spanned<Ast>) {
let (expr, span) = node;
self.ast = expr;
self.span = span;
self.validate();
}
pub fn validate(&mut self) {
use Ast::*;
let root = self.ast;
match root {
Error => unreachable!(),
Word(name) | Splat(name) => {
if !self.resolved(name) {
self.err(format!("unbound name `{name}`"))
} else {
self.use_name(name.to_string())
}
}
Interpolated(parts) => {
for part in parts {
if let (StringPart::Word(name), span) = part {
self.span = span;
if !self.resolved(name) {
self.err(format!("unbound name `{name}`"));
} else {
self.use_name(name.to_string());
}
}
}
}
// validate each line
// ensure it's not empty
// pass through tail position validation
// check if there are any declared but undefined functions
// pop all the bindings off the local stack
Block(block) => {
if block.is_empty() {
self.err("blocks must have at least one expression".to_string());
return;
}
let to = self.locals.len();
let tailpos = self.status.tail_position;
for line in block.iter().take(block.len() - 1) {
self.status.tail_position = false;
self.visit(line);
}
self.status.tail_position = tailpos;
self.visit(block.last().unwrap());
let block_bindings = self.locals.split_off(to);
for binding in block_bindings {
let (name, _, fn_info) = binding;
if matches!(fn_info, FnInfo::Declared) {
self.err(format!("fn `{name}` is declared but not defined"))
}
}
}
// if in tail position, pass through tail position validation
// no unbound names
If(cond, then, r#else) => {
let tailpos = self.status.tail_position;
self.status.tail_position = false;
self.visit(cond.as_ref());
// pass through tailpos only to then/else
self.status.tail_position = tailpos;
self.visit(then.as_ref());
self.visit(r#else.as_ref());
}
Tuple(members) => {
if members.is_empty() {
return;
}
let tailpos = self.status.tail_position;
self.status.tail_position = false;
for member in members {
self.visit(member);
}
self.status.tail_position = tailpos;
}
// no more than one placeholder
Arguments(args) => {
if args.is_empty() {
return;
}
let tailpos = self.status.tail_position;
self.status.tail_position = false;
for arg in args {
self.visit(arg);
}
self.status.has_placeholder = false;
self.status.tail_position = tailpos;
}
Placeholder => {
if self.status.has_placeholder {
self.err(
"you may only use one placeholder when partially applying functions"
.to_string(),
);
}
self.status.has_placeholder = true;
}
List(list) => {
if list.is_empty() {
return;
}
let tailpos = self.status.tail_position;
self.status.tail_position = false;
for member in list {
self.visit(member);
}
self.status.tail_position = tailpos;
}
KeywordPair(_, value) | StringPair(_, value) => self.visit(value.as_ref()),
Dict(dict) => {
if dict.is_empty() {
return;
}
let tailpos = self.status.tail_position;
self.status.tail_position = false;
for pair in dict {
self.visit(pair)
}
self.status.tail_position = tailpos;
}
// TODO!
// check arity against fn info if first term is word and second term is args
Synthetic(first, second, rest) => {
match (&first.0, &second.0) {
(Ast::Word(_), Ast::Method(_, args)) => {
self.visit(first.as_ref());
self.visit(args);
}
(Ast::Keyword(_), Ast::Method(_, args)) => {
self.visit(args);
}
(Ast::And, Ast::Arguments(_)) | (Ast::Or, Ast::Arguments(_)) => {
self.visit(second.as_ref())
}
(Ast::Word(_), Ast::Keyword(_)) => self.visit(first.as_ref()),
(Ast::Keyword(_), Ast::Arguments(args)) => {
if args.len() != 1 {
self.err("called keywords may only take one argument".to_string())
}
self.visit(second.as_ref());
}
(Ast::Word(name), Ast::Arguments(args)) => {
self.visit(first.as_ref());
self.visit(second.as_ref());
//TODO: check arities of prelude fns, too
let fn_binding = self.bound(name);
if let Some((_, _, FnInfo::Defined(_, arities, _))) = fn_binding {
let num_args = args.len();
if !match_arities(arities, num_args as u8) {
self.err(format!("arity mismatch: no clause in function `{name}` with {num_args} argument(s)"))
}
}
}
_ => unreachable!(
"malformed synthetic root with\nfirst: {}\nsecond: {}",
first.0, second.0
),
}
for term in rest {
self.visit(term);
}
}
WhenClause(cond, body) => {
let tailpos = self.status.tail_position;
self.status.tail_position = false;
self.visit(cond.as_ref());
//pass through tail position for when bodies
self.status.tail_position = tailpos;
self.visit(body.as_ref());
}
When(clauses) => {
for clause in clauses {
self.visit(clause);
}
}
// binding forms
// TODO: set up errors to include original binding
LBox(name, boxed) => {
if self.bound(name).is_some() {
self.err(format!("box name `{name}` is already bound"));
} else {
self.bind(name.to_string());
}
self.visit(boxed.as_ref());
}
Let(lhs, rhs) => {
self.visit(rhs.as_ref());
self.visit(lhs.as_ref());
}
MatchClause(pattern, guard, body) => {
let to = self.locals.len();
self.visit(pattern.as_ref());
if let Some(guard) = guard.as_ref() {
self.visit(guard);
}
self.visit(body.as_ref());
self.locals.truncate(to);
}
Match(scrutinee, clauses) => {
self.visit(scrutinee.as_ref());
for clause in clauses {
self.visit(clause);
}
}
Receive(clauses) => {
for clause in clauses {
self.visit(clause);
}
}
FnDeclaration(name) => {
let tailpos = self.status.tail_position;
self.status.tail_position = false;
if self.bound(name).is_some() {
self.err(format!("fn name `{name}` is already bound"));
return;
}
self.declare_fn(name.to_string());
self.status.tail_position = tailpos;
}
FnBody(..) => unreachable!(),
Fn(name, body, ..) => {
let mut is_declared = false;
match self.bound(name) {
Some((_, _, FnInfo::Declared)) => is_declared = true,
None => (),
_ => {
self.err(format!("name `{name}` is already bound"));
}
}
// TODO: devise a placeholder binding for recursive functions
if !is_declared {
self.declare_fn(name.to_string());
}
let from = self.status.used_bindings.len();
let mut arities = HashSet::new();
let (Ast::FnBody(clauses), _) = body.as_ref() else {
unreachable!()
};
for clause in clauses {
// we have to do this explicitly here because of arity checking
let (expr, span) = clause;
self.ast = expr;
self.span = span;
// add clause arity to arities
arities.insert(self.arity());
self.validate();
}
// collect info about what the function closes over
let mut closed_over = HashSet::new();
for binding in self.status.used_bindings.iter().skip(from) {
if self.bound(binding.as_str()).is_some() {
// println!("{name} closing over {binding}");
closed_over.insert(binding.clone());
}
}
let info = FnInfo::Defined(name.to_string(), arities, closed_over);
let root_ptr: *const Ast = root;
self.fn_info.insert(root_ptr, info.clone());
self.define_fn(name.to_string(), info);
}
Panic(msg) => {
let tailpos = self.status.tail_position;
self.status.tail_position = false;
self.visit(msg.as_ref());
self.status.tail_position = tailpos;
}
// TODO: fix the tail call here?
Do(terms) => {
if terms.len() < 2 {
return self.err("do expressions must have at least two terms".to_string());
}
for term in terms.iter().take(terms.len() - 1) {
self.visit(term);
}
let last = terms.last().unwrap();
self.visit(last);
if matches!(last.0, Ast::Recur(_)) {
self.err("`recur` may not be used in `do` forms".to_string());
}
}
Repeat(times, body) => {
self.status.tail_position = false;
self.visit(times.as_ref());
self.visit(body.as_ref());
}
Loop(with, body) => {
self.visit(with.as_ref());
let Ast::Tuple(input) = &with.0 else {
unreachable!()
};
// dbg!(&input);
let tailpos = self.status.tail_position;
self.status.tail_position = true;
let in_loop = self.status.in_loop;
let outer_arity = self.status.loop_arity;
self.status.in_loop = true;
let loop_arity = input.len() as u8;
self.status.loop_arity = loop_arity;
for clause in body {
let (expr, span) = clause;
self.ast = expr;
self.span = span;
let arity = self.arity();
// dbg!(&arity);
match arity {
Arity::Fixed(clause_arity) => {
if clause_arity != loop_arity {
self.err(format!("mismatched arity: expected {loop_arity} arguments in `loop` clause; got {clause_arity}"))
}
}
Arity::Splat(clause_arity) => {
if clause_arity > loop_arity {
self.err(format!("mismathced arity: expected {loop_arity} arguments in `loop` clause; this clause takes {clause_arity} or more"))
}
}
};
self.validate();
}
self.status.tail_position = tailpos;
self.status.in_loop = in_loop;
self.status.loop_arity = outer_arity;
}
Recur(args) => {
if !self.status.in_loop {
self.err("you may only use `recur` in a `loop` form".to_string());
return;
}
if !self.status.tail_position {
self.err("you may only use `recur` in tail position".to_string());
}
let num_args = args.len() as u8;
let loop_arity = self.status.loop_arity;
if num_args != loop_arity {
self.err(format!("loop arity mismatch: loop has arity of {loop_arity}; `recur` called with {num_args} arguments"))
}
self.status.tail_position = false;
for arg in args {
self.visit(arg);
}
}
WordPattern(name) => match self.bound(name) {
Some((name, _span, _)) => {
self.err(format!("name `{name}` is already bound"));
}
None => {
self.bind(name.to_string());
}
},
InterpolatedPattern(parts) => {
for (part, span) in parts {
if let StringPart::Word(name) = part {
self.span = span;
match self.bound(name) {
Some(_) => self.err(format!("name `{name}` is already bound")),
None => self.bind(name.to_string()),
}
}
}
}
AsPattern(name, r#type) => {
match self.bound(name) {
Some((name, _span, _)) => {
self.err(format!("name `{name}` is already bound"));
}
None => {
self.bind(name.to_string());
}
}
let as_type = *r#type;
match as_type {
"nil" | "bool" | "number" | "keyword" | "string" | "tuple" | "dict"
| "list" | "fn" | "box" => (),
_ => self.err(format!("unknown type `:{as_type}`")),
}
}
Splattern(splatted) => {
if !self.status.last_term {
self.err("splats in patterns must come last".to_string());
}
match splatted.as_ref() {
(PlaceholderPattern, _) => (),
(WordPattern(name), span) => match self.bound(name) {
Some(_) => {
self.span = span;
self.err(format!("name `{name}` is already bound"))
}
None => self.bind(name.to_string()),
},
_ => {
println!("internal Ludus error: unexpected splat pattern");
// dbg!(splatted);
unreachable!()
}
}
}
TuplePattern(terms) | ListPattern(terms) | DictPattern(terms) => {
if terms.is_empty() {
return;
}
for term in terms.iter().take(terms.len() - 1) {
self.visit(term);
}
self.status.last_term = true;
let last = terms.last().unwrap();
self.visit(last);
self.status.last_term = false;
}
KeyPairPattern(_, patt) | StrPairPattern(_, patt) => self.visit(patt.as_ref()),
// terminals can never be invalid
Nil | Boolean(_) | Number(_) | Keyword(_) | String(_) | And | Or | Method(..) => (),
// terminal patterns can never be invalid
NilPattern | BooleanPattern(..) | NumberPattern(..) | StringPattern(..)
| KeywordPattern(..) | PlaceholderPattern => (),
};
self.ast = root;
}
}

552
src/value.rs Normal file
View File

@ -0,0 +1,552 @@
use crate::base::BaseFn;
use crate::chunk::Chunk;
use imbl::{HashMap, Vector};
use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer};
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone, Debug)]
pub enum LFn {
Declared {
name: &'static str,
},
Defined {
name: &'static str,
doc: Option<&'static str>,
arities: Vec<u8>,
chunks: Vec<Chunk>,
splat: u8,
closed: RefCell<Vec<Value>>,
},
}
impl LFn {
pub fn close(&self, value: Value) {
match self {
LFn::Declared { .. } => unreachable!(),
LFn::Defined { closed, .. } => {
let shown = value.show();
closed.borrow_mut().push(value);
let pos = closed.borrow().len();
if crate::DEBUG_SCRIPT_RUN {
println!("closing over in {} at {pos}: {shown}", self.name(),);
}
}
}
}
pub fn doc(&self) -> Value {
match self {
LFn::Declared { name } => {
Value::String(Rc::new(format!("fn {name}: undefined function")))
}
LFn::Defined {
name,
doc: Some(doc),
..
} => Value::String(Rc::new(format!("fn {name}\n{doc}"))),
LFn::Defined { name, .. } => {
Value::String(Rc::new(format!("fn {name}: no documentation")))
}
}
}
pub fn accepts(&self, arity: u8) -> bool {
match self {
LFn::Defined { arities, splat, .. } => {
if arities.contains(&arity) {
return true;
}
if *splat == 0 {
return false;
}
let max_arity = arities.iter().fold(0, |a, b| a.max(*b));
arity > max_arity
}
LFn::Declared { .. } => unreachable!(),
}
}
pub fn splat_arity(&self) -> u8 {
match self {
LFn::Defined { splat, .. } => *splat,
LFn::Declared { .. } => unreachable!(),
}
}
pub fn name(&self) -> &'static str {
match self {
LFn::Declared { name } | LFn::Defined { name, .. } => name,
}
}
pub fn chunk(&self, arity: u8) -> &Chunk {
match self {
LFn::Declared { .. } => unreachable!(),
LFn::Defined {
arities,
splat,
chunks,
..
} => {
let chunk_pos = arities.iter().position(|a| arity == *a);
match chunk_pos {
Some(pos) => &chunks[pos],
None => &chunks[*splat as usize],
}
}
}
}
pub fn upvalue(&self, idx: u8) -> Value {
match self {
LFn::Declared { .. } => unreachable!(),
LFn::Defined { closed, .. } => closed.borrow()[idx as usize].clone(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Partial {
pub args: Vec<Value>,
pub name: &'static str,
pub function: Value,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Key {
Keyword(&'static str),
Interned(&'static str),
String(Rc<String>),
}
impl std::fmt::Display for Key {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Key::Keyword(s) => write!(f, ":{s}"),
Key::Interned(s) => write!(f, "\"{s}\""),
Key::String(s) => write!(f, "\"{s}\""),
}
}
}
impl Serialize for Key {
fn serialize<S>(&self, srlzr: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Key::Keyword(s) => srlzr.serialize_str(s),
Key::Interned(s) => srlzr.serialize_str(s),
Key::String(s) => srlzr.serialize_str(s.as_str()),
}
}
}
impl Key {
pub fn to_value(&self) -> Value {
match self {
Key::Keyword(s) => Value::Keyword(s),
Key::Interned(s) => Value::Interned(s),
Key::String(s) => Value::String(s.clone()),
}
}
pub fn from_value(value: Value) -> Key {
match value {
Value::Keyword(s) => Key::Keyword(s),
Value::Interned(s) => Key::Interned(s),
Value::String(s) => Key::String(s.clone()),
_ => unreachable!("dict keys must be keywords or strings"),
}
}
}
#[derive(Clone, Debug)]
pub enum Value {
Nothing,
Nil,
True,
False,
Keyword(&'static str),
Interned(&'static str),
String(Rc<String>),
Number(f64),
Tuple(Rc<Vec<Value>>),
List(Box<Vector<Value>>),
Dict(Box<HashMap<Key, Value>>),
Box(Rc<RefCell<Value>>),
Fn(Rc<LFn>),
BaseFn(Box<BaseFn>),
Partial(Rc<Partial>),
Process,
}
impl PartialEq for Value {
fn eq(&self, other: &Value) -> bool {
use Value::*;
match (self, other) {
(Nothing, Nothing) | (Nil, Nil) | (True, True) | (False, False) => true,
(Keyword(str1), Keyword(str2)) | (Interned(str1), Interned(str2)) => str1 == str2,
(String(x), String(y)) => x == y,
(String(x), Interned(y)) => x.as_ref() == y,
(Interned(x), String(y)) => x == y.as_ref(),
(Number(x), Number(y)) => x == y,
(Tuple(x), Tuple(y)) => x == y,
(List(x), List(y)) => x == y,
(Dict(x), Dict(y)) => x == y,
(Box(x), Box(y)) => std::ptr::eq(x.as_ref().as_ptr(), y.as_ref().as_ptr()),
(Fn(x), Fn(y)) => std::ptr::eq(x, y),
(BaseFn(x), BaseFn(y)) => std::ptr::eq(x, y),
(Partial(x), Partial(y)) => x == y,
_ => false,
}
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use Value::*;
match self {
Nothing => write!(f, "_"),
Nil => write!(f, "nil"),
True => write!(f, "true"),
False => write!(f, "false"),
Keyword(str) => write!(f, ":{str}"),
Interned(str) => write!(f, "\"{str}\""),
String(str) => write!(f, "\"{str}\""),
Number(n) => write!(f, "{n}"),
Process => write!(f, "Process"),
Tuple(members) => write!(
f,
"({})",
members
.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", ")
),
List(members) => write!(
f,
"[{}]",
members
.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", ")
),
Dict(members) => write!(
f,
"#{{{}}}",
members
.iter()
.map(|(k, v)| format!("{k} {v}"))
.collect::<Vec<_>>()
.join(", ")
),
Box(value) => write!(f, "box {{ {} }}", value.as_ref().borrow()),
Fn(lfn) => write!(f, "fn {}", lfn.name()),
BaseFn(inner) => {
let name = match **inner {
crate::base::BaseFn::Nullary(name, _)
| crate::base::BaseFn::Unary(name, _)
| crate::base::BaseFn::Binary(name, _)
| crate::base::BaseFn::Ternary(name, _) => name,
};
write!(f, "fn {name}/base")
}
Partial(partial) => write!(f, "fn {}/partial", partial.name),
}
}
}
impl Serialize for Value {
fn serialize<S>(&self, srlzr: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use Value::*;
match self {
Nil => srlzr.serialize_none(),
True => srlzr.serialize_bool(true),
False => srlzr.serialize_bool(false),
Number(n) => srlzr.serialize_f64(*n),
Interned(s) => srlzr.serialize_str(s),
Keyword(k) => srlzr.serialize_str(k),
String(s) => srlzr.serialize_str(s.as_str()),
Tuple(t) => {
let mut seq = srlzr.serialize_seq(Some(t.len()))?;
for e in t.iter() {
seq.serialize_element(e)?;
}
seq.end()
}
List(l) => {
let mut seq = srlzr.serialize_seq(Some(l.len()))?;
for e in l.iter() {
seq.serialize_element(e)?;
}
seq.end()
}
Dict(d) => {
let mut map = srlzr.serialize_map(Some(d.len()))?;
for (k, v) in d.iter() {
map.serialize_entry(k, v)?;
}
map.end()
}
Box(b) => {
let boxed = b.borrow();
(*boxed).serialize(srlzr)
}
Fn(..) | BaseFn(..) | Partial(..) => unreachable!(),
Process | Nothing => unreachable!(),
}
}
}
impl Value {
pub fn show(&self) -> String {
use Value::*;
let mut out = match &self {
Process => "Process".to_string(),
Nil => "nil".to_string(),
True => "true".to_string(),
False => "false".to_string(),
Number(n) => format!("{n}"),
Interned(str) => format!("\"{str}\""),
String(str) => format!("\"{str}\""),
Keyword(str) => format!(":{str}"),
Tuple(t) => {
let members = t.iter().map(|e| e.show()).collect::<Vec<_>>().join(", ");
format!("({members})")
}
List(l) => {
let members = l.iter().map(|e| e.show()).collect::<Vec<_>>().join(", ");
format!("[{members}]")
}
Dict(d) => {
let members = d
.iter()
.map(|(k, v)| {
let value_show = v.show();
format!("{k} {value_show}")
})
.collect::<Vec<_>>()
.join(", ");
format!("#{{{members}}}")
}
Box(x) => format!("box {{ {} }}", x.as_ref().borrow().show()),
Fn(lfn) => format!("fn {}", lfn.name()),
Partial(partial) => format!("fn {}/partial", partial.name),
BaseFn(_) => format!("{self}"),
Nothing => "_".to_string(),
};
if out.len() > 80 {
out.truncate(77);
format!("{out}...")
} else {
out
}
}
// pub fn to_js(&self) -> JsValue {
// use Value::*;
// match self {
// Nil => JsValue::NULL,
// True => JsValue::TRUE,
// False => JsValue::FALSE,
// Number(n) => JsValue::from_f64(*n),
// Interned(s) => JsValue::from_str(s),
// String(s) => JsValue::from_str(s.as_str()),
// Keyword(k) => JsValue::from_str(k),
// _ => todo!(),
// }
// }
// pub fn to_json(&self) -> Option<String> {
// use Value::*;
// match self {
// True | False | Number(..) => Some(self.show()),
// String(string) => Some(string.escape_default().to_string()),
// Interned(str) => Some(str.escape_default().to_string()),
// Keyword(str) => Some(format!("\"{str}\"")),
// List(members) => {
// let mut joined = "".to_string();
// let mut members = members.iter();
// if let Some(member) = members.next() {
// joined = member.to_json()?;
// }
// for member in members {
// let json = member.to_json()?;
// joined = format!("{joined},{json}");
// }
// Some(format!("[{joined}]"))
// }
// Tuple(members) => {
// let mut joined = "".to_string();
// let mut members = members.iter();
// if let Some(member) = members.next() {
// joined = member.to_json()?;
// }
// for member in members {
// let json = member.to_json()?;
// joined = format!("{joined},{json}");
// }
// Some(format!("[{joined}]"))
// }
// Dict(members) => {
// let mut joined = "".to_string();
// let mut members = members.iter();
// if let Some((key, value)) = members.next() {
// let json = value.to_json()?;
// joined = format!("\"{key}\":{json}")
// }
// for (key, value) in members {
// let json = value.to_json()?;
// joined = format!("{joined},\"{key}\": {json}");
// }
// Some(format!("{{{joined}}}"))
// }
// not_serializable => {
// println!("Cannot convert to json:");
// dbg!(not_serializable);
// None
// }
// }
// }
pub fn stringify(&self) -> String {
use Value::*;
match &self {
Process => "process".to_string(),
Nil => "nil".to_string(),
True => "true".to_string(),
False => "false".to_string(),
Number(n) => format!("{n}"),
Interned(str) => str.to_string(),
Keyword(str) => format!(":{str}"),
Tuple(t) => {
let members = t
.iter()
.map(|e| e.stringify())
.collect::<Vec<_>>()
.join(", ");
format!("({members})")
}
List(l) => {
let members = l
.iter()
.map(|e| e.stringify())
.collect::<Vec<_>>()
.join(", ");
format!("[{members}]")
}
Dict(d) => {
let members = d
.iter()
.map(|(k, v)| {
let value_show = v.stringify();
format!("{k} {value_show}")
})
.collect::<Vec<_>>()
.join(", ");
format!("#{{{members}}}")
}
String(s) => s.as_ref().clone(),
Box(x) => x.as_ref().borrow().stringify(),
Fn(lfn) => format!("fn {}", lfn.name()),
Partial(partial) => format!("fn {}/partial", partial.name),
BaseFn(_) => format!("{self}"),
Nothing => unreachable!(),
}
}
pub fn type_of(&self) -> &'static str {
use Value::*;
match self {
Nothing => unreachable!(),
Nil => "nil",
True => "bool",
False => "bool",
Keyword(..) => "keyword",
Interned(..) => "string",
String(..) => "string",
Number(..) => "number",
Tuple(..) => "tuple",
List(..) => "list",
Dict(..) => "dict",
Box(..) => "box",
Fn(..) => "fn",
BaseFn(..) => "fn",
Partial(..) => "fn",
Process => "process",
}
}
pub fn as_fn(&self) -> &LFn {
match self {
Value::Fn(ref inner) => inner,
_ => unreachable!("expected value to be fn"),
}
}
pub fn as_list(&self) -> &Vector<Value> {
match self {
Value::List(ref inner) => inner,
_ => unreachable!("expected value to be list"),
}
}
pub fn as_box(&self) -> Rc<RefCell<Value>> {
match self {
Value::Box(inner) => inner.clone(),
_ => unreachable!("expected value to be a box"),
}
}
pub fn as_string(&self) -> Rc<String> {
match self {
Value::String(str) => str.clone(),
Value::Interned(str) => Rc::new(str.to_string()),
_ => unreachable!("expected value to be a string"),
}
}
pub fn as_tuple(&self) -> Rc<Vec<Value>> {
match self {
Value::Tuple(members) => members.clone(),
_ => unreachable!("expected value to be a tuple"),
}
}
pub fn string(str: String) -> Value {
Value::String(Rc::new(str))
}
pub fn list(list: Vector<Value>) -> Value {
Value::List(Box::new(list))
}
pub fn new_list() -> Value {
Value::list(Vector::new())
}
pub fn r#box(value: Value) -> Value {
Value::Box(Rc::new(RefCell::new(value)))
}
pub fn tuple(vec: Vec<Value>) -> Value {
Value::Tuple(Rc::new(vec))
}
// pub fn get_shared_box(&self, name: &'static str) -> Value {
// match self {
// Value::Dict(dict) => dict
// .get(name)
// .expect("expected dict to have requested value")
// .clone(),
// _ => unreachable!("expected dict"),
// }
// }
}

1266
src/vm.rs Normal file

File diff suppressed because it is too large Load Diff

485
src/world.rs Normal file
View File

@ -0,0 +1,485 @@
use crate::chunk::Chunk;
use crate::value::{Value, Key};
use crate::vm::Creature;
use crate::panic::Panic;
use crate::errors::panic;
use crate::js::{random, now};
use crate::io::{MsgOut, MsgIn, do_io};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::mem::swap;
use std::rc::Rc;
const ANIMALS: [&str; 32] = [
"tortoise",
"hare",
"squirrel",
"hawk",
"woodpecker",
"cardinal",
"coyote",
"raccoon",
"rat",
"axolotl",
"cormorant",
"duck",
"orca",
"humbpack",
"tern",
"quokka",
"koala",
"kangaroo",
"zebra",
"hyena",
"giraffe",
"hippopotamus",
"capybara",
"python",
"gopher",
"crab",
"trout",
"osprey",
"lemur",
"wobbegong",
"walrus",
"opossum",
];
#[derive(Debug, Clone, PartialEq)]
enum Status {
Empty,
Borrowed,
Nested(Creature),
}
impl std::fmt::Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Status::Empty => write!(f, "empty"),
Status::Borrowed => write!(f, "borrowed"),
Status::Nested(creature) => write!(f, "nested {creature}"),
}
}
}
impl Status {
pub fn receive(&mut self, msg: Value) {
match self {
Status::Nested(creature) => creature.receive(msg),
Status::Borrowed => println!("sending a message to a borrowed process"),
Status::Empty => println!("sending a message to a dead process"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Zoo {
procs: Vec<Status>,
empty: Vec<usize>,
ids: HashMap<&'static str, usize>,
dead: HashSet<&'static str>,
kill_list: Vec<&'static str>,
sleeping: HashMap<&'static str, f64>,
active_idx: usize,
active_id: &'static str,
}
impl Zoo {
pub fn new() -> Zoo {
Zoo {
procs: vec![],
empty: vec![],
ids: HashMap::new(),
kill_list: vec![],
dead: HashSet::new(),
sleeping: HashMap::new(),
active_idx: 0,
active_id: "",
}
}
fn random_id(&self) -> String {
let rand_idx = (random() * 32.0) as usize;
let idx = self.procs.len();
format!("{}_{idx}", ANIMALS[rand_idx])
}
fn new_id(&self) -> &'static str {
let mut new = self.random_id();
while self.dead.iter().any(|old| *old == new) {
new = self.random_id();
}
new.leak()
}
pub fn put(&mut self, mut proc: Creature) -> &'static str {
if self.empty.is_empty() {
let id = self.new_id();
let idx = self.procs.len();
proc.pid = id;
self.procs.push(Status::Nested(proc));
self.ids.insert(id, idx);
id
} else {
let idx = self.empty.pop().unwrap();
let rand = (random() * 32.0) as usize;
let id = format!("{}_{idx}", ANIMALS[rand]).leak();
proc.pid = id;
self.ids.insert(id, idx);
self.procs[idx] = Status::Nested(proc);
id
}
}
pub fn kill(&mut self, id: &'static str) {
self.kill_list.push(id);
}
pub fn sleep(&mut self, id: &'static str, ms: f64) {
self.sleeping
.insert(id, now() + ms);
}
pub fn is_alive(&self, id: &'static str) -> bool {
if self.kill_list.contains(&id) {
return false;
}
let idx = self.ids.get(id);
match idx {
Some(idx) => match self.procs.get(*idx) {
Some(proc) => match proc {
Status::Empty => false,
Status::Borrowed => true,
Status::Nested(_) => true,
},
None => false,
},
None => false,
}
}
pub fn clean_up(&mut self) {
while let Some(id) = self.kill_list.pop() {
if let Some(idx) = self.ids.get(id) {
println!("buried process {id}");
self.procs[*idx] = Status::Empty;
self.empty.push(*idx);
self.ids.remove(id);
self.dead.insert(id);
}
}
self.sleeping
.retain(|_, wakeup_time| now() < *wakeup_time);
println!(
"currently sleeping processes: {}",
self.sleeping
.keys()
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join(" | ")
);
}
pub fn catch(&mut self, id: &'static str) -> Creature {
if let Some(idx) = self.ids.get(id) {
let mut proc = Status::Borrowed;
swap(&mut proc, &mut self.procs[*idx]);
let Status::Nested(proc) = proc else {
unreachable!("tried to borrow an empty or already-borrowed process {id}");
};
proc
} else {
unreachable!("tried to borrow a non-existent process {id}");
}
}
pub fn release(&mut self, proc: Creature) {
let id = proc.pid;
if let Some(idx) = self.ids.get(id) {
let mut proc = Status::Nested(proc);
swap(&mut proc, &mut self.procs[*idx]);
}
}
pub fn is_available(&self) -> bool {
match &self.procs[self.active_idx] {
Status::Empty => false,
Status::Borrowed => false,
Status::Nested(proc) => !self.sleeping.contains_key(proc.pid),
}
}
pub fn next(&mut self) -> &'static str {
self.clean_up();
let starting_idx = self.active_idx;
self.active_idx = (self.active_idx + 1) % self.procs.len();
while !self.is_available() {
// we've gone round the process queue already
// that means no process is active
// but we may have processes that are alive and asleep
// if nothing is active, yield back to the world's event loop
if self.active_idx == starting_idx {
return ""
}
self.active_idx = (self.active_idx + 1) % self.procs.len();
}
match &self.procs[self.active_idx] {
Status::Empty | Status::Borrowed => unreachable!(),
Status::Nested(proc) => proc.pid,
}
}
pub fn send_msg(&mut self, id: &'static str, msg: Value) {
let Some(idx) = self.ids.get(id) else {
return;
};
self.procs[*idx].receive(msg);
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Buffers {
console: Value,
commands: Value,
fetch_out: Value,
fetch_in: Value,
input: Value,
}
impl Buffers {
pub fn new (prelude: imbl::HashMap<Key, Value>) -> Buffers {
Buffers {
console: prelude.get(&Key::Keyword("console")).unwrap().clone(),
commands: prelude.get(&Key::Keyword("turtle_commands")).unwrap().clone(),
fetch_out: prelude.get(&Key::Keyword("fetch_outbox")).unwrap().clone(),
fetch_in: prelude.get(&Key::Keyword("fetch_inbox")).unwrap().clone(),
input: prelude.get(&Key::Keyword("input")).unwrap().clone(),
}
}
pub fn console (&self) -> Rc<RefCell<Value>> {
self.console.as_box()
}
pub fn input (&self) -> Rc<RefCell<Value>> {
self.input.as_box()
}
pub fn commands (&self) -> Rc<RefCell<Value>> {
self.commands.as_box()
}
pub fn fetch_out (&self) -> Rc<RefCell<Value>> {
self.fetch_out.as_box()
}
pub fn fetch_in (&self) -> Rc<RefCell<Value>> {
self.fetch_in.as_box()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct World {
zoo: Rc<RefCell<Zoo>>,
active: Option<Creature>,
main: &'static str,
pub result: Option<Result<Value, Panic>>,
buffers: Buffers,
last_io: f64,
kill_signal: bool,
}
impl World {
pub fn new(chunk: Chunk, prelude: imbl::HashMap<Key, Value>, debug: bool) -> World {
let zoo = Rc::new(RefCell::new(Zoo::new()));
let main = Creature::new(chunk, zoo.clone(), debug);
let id = zoo.borrow_mut().put(main);
let buffers = Buffers::new(prelude);
World {
zoo,
active: None,
main: id,
result: None,
buffers,
last_io: 0.0,
kill_signal: false,
}
}
fn next(&mut self) {
let mut active = None;
swap(&mut active, &mut self.active);
let mut zoo = self.zoo.borrow_mut();
if let Some(active) = active {
zoo.release(active);
}
let new_active_id = zoo.next();
if new_active_id.is_empty() {
self.active = None;
return;
}
let mut new_active_proc = zoo.catch(new_active_id);
new_active_proc.reset_reductions();
let mut new_active_opt = Some(new_active_proc);
swap(&mut new_active_opt, &mut self.active);
}
fn activate_main(&mut self) {
let main = self.zoo.borrow_mut().catch(self.main);
self.active = Some(main);
}
fn active_id(&mut self) -> Option<&'static str> {
match &self.active {
Some(creature) => Some(creature.pid),
None => None,
}
}
fn kill_active(&mut self) {
if let Some(pid) = self.active_id() {
self.zoo.borrow_mut().kill(pid);
}
}
fn active_result(&mut self) -> &Option<Result<Value, Panic>> {
if self.active.is_none() { return &None; }
&self.active.as_ref().unwrap().result
}
fn flush_buffers(&mut self) -> Vec<MsgOut> {
let mut outbox = vec![];
if let Some(console) = self.flush_console() {
outbox.push(console);
}
if let Some(commands) = self.flush_commands() {
outbox.push(commands);
}
if let Some(fetch) = self.make_fetch_happen() {
outbox.push(fetch);
}
outbox
}
fn make_fetch_happen(&self) -> Option<MsgOut> {
let out = self.buffers.fetch_out();
let working = RefCell::new(Value::Interned(""));
out.swap(&working);
let working = working.borrow();
if working.as_string().is_empty() {
None
} else {
Some(MsgOut::Fetch(working.clone()))
}
}
fn flush_console(&self) -> Option<MsgOut> {
let console = self.buffers.console();
let working_copy = RefCell::new(Value::new_list());
console.swap(&working_copy);
let working_value = working_copy.borrow();
if working_value.as_list().is_empty() {
None
} else {
Some(MsgOut::Console(working_value.clone()))
}
}
fn flush_commands(&self) -> Option<MsgOut> {
let commands = self.buffers.commands();
let working_copy = RefCell::new(Value::new_list());
commands.swap(&working_copy);
let commands = working_copy.borrow();
if commands.as_list().is_empty() {
None
} else {
Some(MsgOut::Commands(commands.clone()))
}
}
fn complete_main(&mut self) -> Vec<MsgOut> {
let mut outbox = self.flush_buffers();
// TODO: if we have a panic, actually add the panic message to the console
let result = self.active_result().clone().unwrap();
self.result = Some(result.clone());
let result_msg = match result {
Ok(value) => MsgOut::Complete(Value::string(value.show())),
Err(p) => MsgOut::Error(panic(p))
};
outbox.push(result_msg);
outbox
}
fn interpret_active(&mut self) {
self.active.as_mut().unwrap().interpret();
}
async fn maybe_do_io(&mut self) {
if self.last_io + 10.0 < now() {
let outbox = self.flush_buffers();
let inbox = do_io(outbox).await;
self.fill_buffers(inbox);
self.last_io = now();
}
}
fn fill_input(&mut self, str: String) {
let value = Value::string(str);
let working = RefCell::new(value);
let input = self.buffers.input();
input.swap(&working);
}
fn fetch_reply(&mut self, reply: Value) {
let inbox_rc = self.buffers.fetch_in();
inbox_rc.replace(reply);
}
fn fill_buffers(&mut self, inbox: Vec<MsgIn>) {
for msg in inbox {
match msg {
MsgIn::Input(str) => self.fill_input(str),
MsgIn::Kill => self.kill_signal = true,
MsgIn::Fetch(..) => self.fetch_reply(msg.into_value()),
_ => todo!()
}
}
}
async fn ready_io(&mut self) {
let inbox = do_io(vec![MsgOut::Ready]).await;
self.fill_buffers(inbox);
self.last_io = now();
}
pub async fn run(&mut self) {
self.activate_main();
self.ready_io().await;
loop {
self.maybe_do_io().await;
if self.kill_signal {
let mut outbox = self.flush_buffers();
outbox.push(MsgOut::Error("Ludus killed by user".to_string()));
do_io(outbox).await;
return;
}
if self.active.is_some() {
self.interpret_active();
}
if self.active_result().is_some() {
if self.active_id().unwrap() == self.main {
let outbox = self.complete_main();
do_io(outbox).await;
return;
}
self.kill_active();
}
self.next();
}
}
}

92
thoughts.md Normal file
View File

@ -0,0 +1,92 @@
# VM thoughts
### Initial thoughts
We want numbers and bools as unboxed as possible.
Nil is a singleton, and should be static.
Strings come in two flavours:
* String literals, which are static/interned.
* Constructed strings, which should be `Rc<String>`
Keywords are static/interned.
Tuples should be refcounted for now.
### Optimization and other thoughts
2024-11-09
* To put tuples on the stack, we need to know both how long they are (number of members) and how big they are (amount of memory), since tuples can contain other tuples.
- All other values must be one stack cell:
* `nil` is its own thing
* numbers are a wrapped `f64` (at least until we get to NaN boxed values)
* booleans are a wrapped `bool`
* keywords are a wrapped `u16` or `u32`, which is an index into a vec of `&str`s, which can be read back into a string when printed
* strings are a `&str` or an `Rc<String>` (with two possible wrappers: `Value::Str` or `Value::String`)
* dicts are `imbl::HashMap<u16, Value>`, with the hash generated on the index of the keyword
* sets are `imbl::HashSet<Value>`, with the caveat that `f64` isn't `Eq`, which means that we can't use it for a hash key. The way around this, I think, is to implement `Eq` for `Value`, with a panic if we try to put NaN in a set
* functions are `Rc<LFn>`
* boxes are `Rc<RefCell>`
* That means everything is either a wrapped `Copy` (`:nil`, `:number`, `:bool`), an interned reference (`:keyword`, `:string`), `Rc` reference types (`:string`, `:box`, `:fn`), or persistent reference types that have their own `clone` (`:list`, `:dict`, `:set`)
* This doesn't cover everything, yet. But other reference types will be `Rc`ed structs: to wit, processes and packages.
- Tuples, meanwhile, have a special representation on the stack.
* They start with a `Value::TupleStart(len: u8, size: u8)`.
* They then have a number of members.
* They end with a `Value::TupleEnd(len: u8, size: u8)`.
* `len` indicates the number of members in the tuple; `size` indicates the size of the tuple on the stack, including the `TupleStart` and `TupleEnd` cells. For `()`, `len` is `0`, and `size` is `2`. Nesting tuples will lead to larger divergences, and will increase `size` but not `len`.
* If sombody tries to stuff more than 255 members in a tuple, nested or not, we get a validation error to tell them to use a list.
- Or promote it to be a reference type? The natural encoding of a list in Ludus is using a `(car, cdr)` encoding (or `(data, next)`). I believe the way to get this out of a scope (block or function) is to expand the tuple fully, which could lead very quickly to very large tuples.
- But we can easily distinguish between argument tuples and value tuples, and promote value tuples with a size larger than 255 to a `Value::BigTuple(Rc<Vec<Value>>)`.
- But in no case should we allow arguments to get bigger than 255.
- Keeping small value tuples on the stack is worthwhile, especially given the importance of result tuples, which should stay on the stack.
* This naturally leads to questions about pattern matching, especially when we get to a stack-based bytecode VM.
- A pattern, like a tuple, is a series of cells.
- The goal is to keep pattern sizes and lengths identical to the tuple data representation.
- That means that, like data representations, a pattern has to include both a set of bytecode instructions and a data representation on the stack.
- In fact, I suspect that the fastest way to encode this will be to push the data representation of the scrutinee on the stack, and then to push the pattern, and to then compare within the stack, at different offsets.
### Let's not reinvent the wheel
#### Or, crates we will use
* `chumsky` for parsing
* `ariadne` for parsing errors
* `imbl` for persistent data structures
* `boxing` for NaN boxing (eventually?)
* ~~`tailcall` for tail recursion~~ This only works for simple recursion, and we need mutual recursion.
We additionally might want crates for:
* processes/actors, although given that Ludus will be single-threaded for the forseeable future, it may be lighter weight to just write my own `process` abstraction
* in that case, we will need a ringbuffer, `ringbuf`
### On string interpolation
#### Which is proving rather harder to handle than I expected
I'm trying to use Chumsky to do this, but it's weirdly much harder to model with Chumsky's parer combinators than I expected.
I suspect the thing to do is to just brute force it in much the same way that I do in the Janet-based scanner: loop through the things and push things onto vectors in the correct ways.
This won't be a one-for-one translation, but I suspect it will be easier to manage than banging my head against, especially, the terrible error messages Chumsky's elaborate types give me.
This makes interpolated strings easy enough to work with.
That said, interpolation patterns are harder.
In particular, I worry whether I'll be able to compile a Chumsky parser with strings that aren't interned/`'static`.
Because the pattern match will actually have to be a little Chumsky parser guy (doo dah), or some equivalent.
(In the Janet-based interpreter, I used Janet's built-in PEGs.)
### On performance
The Rust tree-walk interpreter is something like two orders of magnitude faster than the Janet interpreter.
So in that sense, I think it's a worthwhile middle ground to effectively publish this first, easier-to-develop approach, and then to work on a bytecode VM later.
It's worth noting that my approach to this first tree-walk interpreter still leaves a lot on the table for optimization: the `Value` enum is 64 _bytes_.
This is because `imbl::Vector`s are 64 bytes.
I'm trying to ensure opportunistic mutation throughout, but I have found it hard with dicts.
This sort of thing.
Finally, it's clear that some perf testing will be necessary to determine the final arrangement of things.
Will `box`ing things to get heap pointers help?
Or will the extra indirection cost more speed than even if we squeeze `Value`'s size down to 8 bytes?
Will `box`ing lists, etc., mung up how `imbl` does refcounting and opportunistic mutation?
There are things like `tinyvec` which does some of the dark magic around allocating that might make using tuples easier to manage?
### On parsing in Ludus
I've been thinking about Ludus's built-in parsing capabilities.
Using the interpolition-style string pattern matching parsing for ELIZA makes a lot of sense, but we need something more robust for, say, a Lisp.
Looking at this, I think that Janet's builtin PEG parsing might be a much more interesting solution than just about anything else.
I'm pretty sure I can make a slow, but user-friendly-enough version of that that works in Ludus.
(Famous last words.)