Compare commits

...

10 Commits

Author SHA1 Message Date
TriMill 48a0fc81de radices, remove |\ and |\\ 2022-11-07 17:10:23 -05:00
TriMill 076fe8f60c Relicense under LGPLv3 2022-10-25 10:04:19 -04:00
TriMill fcaa0fe5f9 fix automatic semicolons 2022-10-18 08:42:50 -04:00
TriMill 7be878b97a bitwise operators, hex/bin/seximal literals, changed infix boxing notation, fixed semicolons in repl 2022-10-18 08:35:44 -04:00
TriMill 443262f711 refactoring, stdlib improvements 2022-09-25 19:25:13 -04:00
TriMill 08c0cd9173 Refactored stdlib to its own crate 2022-09-23 15:09:22 -04:00
TriMill 7173c5dda1 refactoring, extensible types, basic file i/o 2022-09-23 14:55:18 -04:00
TriMill 297c060e48 more documentation 2022-09-23 11:10:22 -04:00
TriMill 4ca75cbd38 forgot strings lol 2022-09-22 22:54:39 -04:00
TriMill 185adc6b91 begin README documentation 2022-09-22 22:52:41 -04:00
27 changed files with 1710 additions and 1125 deletions

51
Cargo.lock generated
View File

@ -74,7 +74,6 @@ dependencies = [
"num-complex",
"num-rational",
"num-traits",
"paste",
"strum",
]
@ -84,10 +83,22 @@ version = "0.1.0"
dependencies = [
"backtrace",
"complexpr",
"complexpr-stdlib",
"rustyline",
"rustyline-derive",
]
[[package]]
name = "complexpr-stdlib"
version = "0.1.0"
dependencies = [
"complexpr",
"lazy_static",
"num-traits",
"paste",
"try-partialord",
]
[[package]]
name = "dirs-next"
version = "2.0.0"
@ -187,10 +198,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ea37f355c05dde75b84bba2d767906ad522e97cd9e2eef2be7a4ab7fb442c06"
[[package]]
name = "libc"
version = "0.2.132"
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8371e4e5341c3a96db127eb2465ac681ced4c433e01dd0e938adbef26ba93ba5"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.133"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0f80d65747a3e43d1596c7c5492d95d5edddaabd45a7fcdb02b95f644164966"
[[package]]
name = "linux-raw-sys"
@ -310,9 +327,9 @@ checksum = "b1de2e551fb905ac83f73f7aedf2f0cb4a0da7e35efa24a202a936269f1f18e1"
[[package]]
name = "proc-macro2"
version = "1.0.43"
version = "1.0.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab"
checksum = "7bd7356a8122b6c4a24a82b278680c73357984ca2fc79a0f9fa6dea7dced7c58"
dependencies = [
"unicode-ident",
]
@ -364,9 +381,9 @@ checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342"
[[package]]
name = "rustix"
version = "0.35.9"
version = "0.35.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72c825b8aa8010eb9ee99b75f05e10180b9278d161583034d7574c9d617aeada"
checksum = "af895b90e5c071badc3136fc10ff0bcfc98747eadbaf43ed8f214e07ba8f8477"
dependencies = [
"bitflags",
"errno",
@ -458,9 +475,9 @@ dependencies = [
[[package]]
name = "syn"
version = "1.0.99"
version = "1.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13"
checksum = "52205623b1b0f064a4e71182c3b18ae902267282930c6d5462c91b859668426e"
dependencies = [
"proc-macro2",
"quote",
@ -469,24 +486,30 @@ dependencies = [
[[package]]
name = "thiserror"
version = "1.0.35"
version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c53f98874615aea268107765aa1ed8f6116782501d18e53d08b471733bea6c85"
checksum = "0a99cb8c4b9a8ef0e7907cd3b617cc8dc04d571c4e73c8ae403d80ac160bb122"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.35"
version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8b463991b4eab2d801e724172285ec4195c650e8ec79b149e6c2a8e6dd3f783"
checksum = "3a891860d3c8d66fec8e73ddb3765f90082374dbaaa833407b904a94f1a7eb43"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "try-partialord"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "494f2baf446447eb9b49ece9bbc391b8b251ceb4778f7362ef09dd9eadec390f"
[[package]]
name = "unicode-ident"
version = "1.0.4"

View File

@ -1,2 +1,2 @@
[workspace]
members = [ "complexpr-bin", "complexpr" ]
members = [ "complexpr-bin", "complexpr", "complexpr-stdlib" ]

827
LICENSE
View File

@ -1,674 +1,165 @@
GNU GENERAL PUBLIC LICENSE
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

319
README.md
View File

@ -1,3 +1,320 @@
# complexpr
the language of the FUTURE
`complexpr` is a programming language, for a sufficiently inclusive definition of the term. It can be used to accomplish many tasks that the average programmer would wish to accomplish, including:
- Printing "Hello, world!" (and over 3 other strings!)
- Computing factorials
- Finding prime numbers
- Simulating arbitrary Turing machines
- And ∞ more!
To install complexpr, simply clone this repository, `cd complexpr-bin`, and `cargo install --path .`. You can then use the `complexpr` command to start a REPL, or pass a filename as an argument to read from a file.
## License
The core `complexpr` parser and interpreter library, the standard library `complexpr-stdlib`, and the command-line interpreter and REPL `complexpr-bin` are licensed under the [GNU LGPL 3.0](https://www.gnu.org/licenses/lgpl-3.0.html).
## Primitive types
`complexpr` features a wide variety of primitive types, suitable for all your programming needs.
| Type | Description | Example values |
|------------|-----------------------------------------------------------|------------------------|
| `Nil` | Represents nothing (like `null` or `None`) | `nil` |
| `Int` | 64-bit signed integer | `35`, `-1003` |
| `Float` | 64-bit floating-point number | `10.3`, `0.0061` |
| `Complex` | Complex number, represented as a pair of 64-bit floats | `1.5 - 2i` |
| `Rational` | Rational number, represented as a pair of 64-bit integers | `3//5`, `-11//25` |
| `Bool` | Boolean type, either `true` or `false` | `true`, `false` |
| `Char` | A single Unicode character | `'A'`, `'\n'` |
| `String` | A string of Unicode characters | `"example string\n"` |
| `List` | A heterogeneous list | `[1, 2.0, "3"]` |
| `Map` | A heterogeneous hashmap | `{1: "one", "2": 2}` |
| `Func` | A function | `max`, `fn(x,y) (x^y)` |
Complex numbers can be written as the sum of a real component and imaginary component, where the imaginary component is suffixed with an `i`. For example, `5i`, `-1.3+3i`, and `0.5-0.2i` are all valid complex numbers.
Rational numbers are defined using the rational division operator `//`, described below.
### Truthiness
The following values are considered falsy:
- The boolean `false`, of course
- `nil`
- The numbers `0`, `0.0`, `0i`, and `0//1`
- The null character `'\0'`
- Empty lists, strings, and maps
All other values are truthy.
### Escape characters
Character and string literals can use the following escape codes to represent characters:
| Escape | Character |
|-------------|------------------------------------------|
| `\\` | Backslash `\` |
| `\'` | Single quote `'` |
| `\"` | Double quote `"` |
| `\0` | Null byte (0x00) |
| `\t` | Tab (0x09) |
| `\n` | Newline (0x0A) |
| `\r` | Carriage return (0x0D) |
| `\e` | Escape (0x1B) |
| `\x##` | Arbitrary character (one byte codepoint) |
| `\u{##…}` | Arbitrary character (any size codepoint) |
Strings can extend across multiple lines, and will include the newlines by default. To prevent the newlines from being included, escape them using a `\` at the end of the line.
## Arithmetic operators
Data is rather useless if there is no way to operate it. As such, `complexpr` also includes several operators, the most basic of these being arithmetic operators.
| Operator | Description | Example usage |
|----------|------------------------------------------------|-------------------------|
| `+` | Addition, concatenation of strings/chars/lists | `1 + 3.0`, `"ab" + 'c'` |
| `-` | Subtraction | `3 - 2` |
| `*` | Multiplication, repeating a list n times | `5 * 7.3`, `[0] * 10` |
| `/` | Division | `22.3 / 5.1` |
| `%` | Modulo (remainder after division) | `27 % 4` |
| `^` | Exponentiation | `5^2`, `0.2^(-3)` |
| `//` | Rational division (results in a rational type) | `5//3`, `-1//10` |
All of these operators (except `//`) follow the following rule when applied to numeric operands of differing types: the type of the result is the *more generic* of the two operand types. In order of increasing genericness, `Int`, `Rational`, `Float`, `Complex`. As an example, the type of `5.0 + 3//2` is `Float`, since floats are more generic than rationals
Unlike the other operators, `//` is only valid for integer and rational arguments, and always results in a rational value.
`+` can also be used for concatenating chars and strings to each other. The result of this is always a string. `+` can also be used to concatenate lists. `*` can be used for repeating a list or string a certain number of times, for example `[0,1,2] * 3` = `[0,1,2,0,1,2,0,1,2]`.
`^` has the highest precedence and is right-associative (so, `2^3^4` = `2^(3^4)`). `*`, `/`, `%`, and `//` have the next highest precedence, followed by `+` and `-`.
The unary minus operator `-` can be used to negate a variable.
## Comparison operators
In addition to operating on data, it is also desirable to compare it to other data. `complexpr` has the standard set of comparison operators plus a fairly uncommon one.
| Operator | Description | Example usage (all true) |
|----------|--------------------------|--------------------------|
| `==` | Equality | `5 == 5.0` |
| `!=` | Inequality | `3//5 != 0.2` |
| `>` | Greater than | `10 > -10` |
| `<` | Less than | `3 < 4.0` |
| `>=` | Greater than or equal to | `5//12 >= 0.01` |
| `<=` | Less than or equal to | `0.03 <= 3.03` |
| `<=>` | Spaceship (see below) | `(4 <=> 5) == -1` |
Equality and inequality will always succeed, regardless of the types of the arguments. Numeric types which have equal values will compare as equal, even if the types are different.
Comparison operators can be applied to real numbers (not `Complex`), chars, strings, and lists. Characters are compared by their codepoints, and strings and lists are compared [lexicographically](https://en.wikipedia.org/wiki/Lexicographic_order).
The spaceship operator results in 0 if the arguments are equal, 1 if the left-hand side is greater, or -1 if the right-hand side is greater.
## Logical operators
`&&` and `||` are the logical AND and OR operators. `&&` will evaluate to the left-hand argument if it is falsy, otherwise it will evaluate to the right-hand argument. `||` will evaluate to the left-hand argument if it is `truthy`, otherwise it will evaluate to the right-hand one.
`!` is the unary NOT operator.
## Comments
Line comments are preceded by a hash sign (or number sign, or pound sign, or octothorpe, etc.). Block comments are surrounded with `#{ … }#`.
```
# line comment
#{
block
comment
}#
```
## Variables, assignment, and scope
Variables are declared using the keyword `let`. For example, `let number = 12;` declares a variable named `number` with the value of `12`. The variable does not need to be assigned to right away, in which case it defaults to `nil` (for example: `let number;`).
Use a single equals sign (`=`) to reassign a previously declared variable. As with many other programming languages, you can also use compound assignment operators to modify a variable's value. These include `+=`, `-=`, `*=`, `/=`, `%=`, `^=`, and `//=`, and do exactly what you would expect. These cannot be used in `let` statements, for obvious reasons.
Assignment can also be performed to elements of a list or map or to fields of a struct.
`complexpr` uses lexical scoping, so a variable is only valid in the block it was declared in, as well as all inner blocks. When assigning to a variable, if multiple outer scopes contain a declaration for the variable, the innermost one is modified.
```
let x = 5;
{
println(x); # prints 5
x = 3;
let x = 0;
println(x); # prints 0
}
println(x); # prints 3
let y; # y == nil
y = 3;
y += 5;
```
## Control flow
`complexpr` offers three procedural-style methods of control flow: if statements, while loops, and for-each loops. If statements use the keywords `if` for the first condition, `elif` for all subsequent conditions, and `else` for the else clause. Conditions do not need to be parenthesized. The bodies of an if statement should be enclosed in braces (currently this is not required if the body is one statement long, but this may change in the future).
While loops are syntactically very similar, using the keyword `while` and also not requiring parentheses for the condition.
For-each loops use the keyword `for`, followed by the loop variable, a colon, and then the collection to iterate over (see below for information regarding iterators).
```
let value = 5;
if value > 3 {
while value > 4 {
value -= 0.3;
}
} elif value == 2 {
for n: [1,3,5,4] {
value += n;
}
} else {
value -= 1;
}
```
`continue` and `break` may be used inside loops to skip to the next iteration or exit early, respectively.
## Functions
Functions can be defined either with a name or anonymously. Defining a named function is equivalent to creating an anonymous one and immediately declaring a variable and assigning the function to it.
```
# define the function "add1"
fn add1(x, y) {
return x + y;
}
# create an anonymous function and assign it to the variable "add2"
let add2 = fn(x, y) {
return x + y;
};
```
Functions can then be called using the typical syntax:
```
println(add1(3, 4)); # prints 7
```
When a function is declared, it captures the environment it was declared in, including definitions that occur after the function in the source code. This is somewhat counterintuitive.
```
let x = 5;
fn test() {
println(x);
}
test(); # prints 5
x = 7;
test(); # prints 7
```
Functions are first-class, they can be passed around just like any other value.
### Braces vs parentheses
If a function body is one or multiple statements, it must be surrounded by braces `{ }`. If the body consists of a single expression, it can be surrounded with parentheses, and the result of the expression will be returned.
```
fn add3(x, y) (x + y)
println(add3(1, 7)); # prints 8
```
### Partial applications
If a function is called with fewer than its required number of arguments, it will return a *partial function*. Calling this partial function with the remaining arguments will return the value expected had the function been called with all of its arguments at once.
```
fn add(x, y) (x + y)
let add7 = add(7);
println(add7(3)); # prints 10
```
### Boxed infix operators
Some infix operators can be converted to functions by prefixing them with a backslash `\`. For example, `\+` is a function that computes the sum of its two arguments (the same as `fn(x, y) (x + y)`). This can be done for arithmetic, comparison, and bitwise operators only.
## Iterators
An iterator is simply a function with the following properties:
- it takes zero arguments,
- it returns `nil` once it runs out of elements, and
- once it returns `nil` once, it will continue to do so forever
The language only enforces the first point, the second and third must be enforced by the programmer. It is also often the case that an iterator will return a different value each time it is called, however this is not neccesary.
Iterators can be used in most places that lists and strings can be used, for example in a for loop:
```
# print the numbers from 0 to 100 (exclusive)
for x in 0..100 {
println(x);
}
```
### Range syntax
Ranges are a simple built-in type of iterator for producing a range of numbers or characters. Because of floating-point rounding issues, they can only be used with integers and rationals (not floats or complex numbers). The most basic range type is written as `a..b`, where `a` is the initial value and `b` is the limit (which is exclusive, ie. the iterator will stop before reaching this value).
Adding an equals sign before the limit value will make the range inclusive - it will stop only once it exceeds the limit. Replacing the final value with an asterisk `*` will make the range infinite (this is incompatible with the inclusive syntax).
After the limit term, an optional step amount can be specified by appending a colon followed by the step value. If no step value is specified the default is the integer `1`.
For a numeric range, the three terms can be integers or rational numbers in any combination. For character literals (which must be inclusive), the start and limit must be characters while the step, if specified, must be an integer.
```
println(list(0..6)); # [0, 1, 2, 3, 4, 5]
println(list(0..=6)); # [0, 1, 2, 3, 4, 5, 6]
# println(list(0..*)); # Constructing a list from an infinite range is a bad idea
println(list(0..6:2)); # [0, 2, 4]
println(list(0..=6:2)); # [0, 2, 4, 6]
# println(list(0..*:2)); # This is also a bad idea
```
### Pipeline syntax
One of the hallmark features of `complexpr` is its pipeline syntax. Pipelines provide a convenient way to work with data, especially iterators, by allowing the programmer to write functions in the order that they are applied. Pipeline operators all have the same precedence and are applied left-to-right.
The most basic pipeline operator is `|>`. `|>` will call the function on the right side using the value on the left side as an argument.
```
# println("Hello, world!");
"Hello, world!" |> println;
```
`|:` is similar to `map` in other languages; it constructs an iterator that takes each element from the iterator on the left and applies the function on the right to it.
```
# prints the list of squares from 0^2 to 9^2
0..10 |: fn(x) (x^2) |> list |> println;
```
(Note: the iterator must first be converted to a list before printing.)
`|?` filters the iterator on the left using the function to the right. If the function returns `false` the item is skipped; if it returns true, the item is passed through.
```
# [1, 2, 4, 5, 7, 8]
0..10 |? fn(x) (x % 3 != 0) |> list |> println;
```
`|//` folds the iterator on the left over the function on the right. This is commonly used to get the sum, product, minimum, or maximum of an iterator. `|//` starts folding from the beginning of the iterator and goes to the end.
```
# == ((((0+1)+2)+3)+4)
0..5 |// fn(x,y) (x + y) |> println;
```
In some cases (particulary when the function is not commutative) it may be desirable to use an initial value instead of taking the first two values from the list. This can be accomplished with the operator `|/`. This operators are ternary, so the right-hand side must include the initial value and the function, separated by a comma.
```
# == (((((0+2)+3)+4)+5)+6)
2..7 |/ 0, fn(x,y) (x + y) |> println;
```
## Structs (WIP)
`todo!();`

View File

@ -7,6 +7,7 @@ edition = "2021"
[dependencies]
complexpr = { path = "../complexpr" }
complexpr-stdlib = { path = "../complexpr-stdlib" }
backtrace = "0.3.66"
rustyline = { version = "10.0.0", optional = true }
rustyline-derive = { version = "0.7.0", optional = true }

View File

@ -1,7 +1,7 @@
use std::{fs, panic::{self, PanicInfo}, process::ExitCode};
use backtrace::Backtrace;
use complexpr::{interpreter::interpret};
use complexpr::{interpreter::interpret, env::Environment};
mod helper;
mod repl;
@ -22,10 +22,21 @@ fn panic_hook(info: &PanicInfo) {
}
}
fn create_env() -> Environment {
let mut env = Environment::new();
complexpr_stdlib::prelude::load(&mut env);
complexpr_stdlib::io::load(&mut env);
complexpr_stdlib::iter::load(&mut env);
complexpr_stdlib::math::load(&mut env);
env
}
fn main() -> ExitCode {
panic::set_hook(Box::new(panic_hook));
let args: Vec<String> = std::env::args().collect();
if args.len() == 2 {
if args.len() >= 2 {
let fname = &args[1];
let src = match fs::read_to_string(fname) {
Ok(src) => src,
@ -34,7 +45,10 @@ fn main() -> ExitCode {
return ExitCode::from(2);
}
};
let res = interpret(&src, Some(fname.into()), None, false);
let env = create_env().wrap();
let res = interpret(&src, Some(fname.into()), Some(env), false);
if let Err(e) = res {
eprintln!("Error: {}", e);
return ExitCode::from(1);

View File

@ -1,9 +1,10 @@
#![cfg(feature = "repl")]
use rustyline::{self, error::ReadlineError, Config, CompletionType, EditMode, hint::HistoryHinter, validate::MatchingBracketValidator, Editor};
use complexpr::{env::Environment, interpreter::interpret, value::Value, stdlib};
use complexpr::{interpreter::interpret, value::Value};
use crate::helper::CxprHelper;
use crate::{helper::CxprHelper, create_env};
const C_RESET: &str = "\x1b[0m";
const C_BLUE: &str = "\x1b[94m";
@ -17,7 +18,7 @@ pub fn repl() -> Result<(), Box<dyn std::error::Error>> {
.edit_mode(EditMode::Emacs)
.build();
let env = Environment::new().wrap();
let env = create_env().wrap();
let h = CxprHelper {
hinter: HistoryHinter {},
@ -36,16 +37,12 @@ pub fn repl() -> Result<(), Box<dyn std::error::Error>> {
println!("Press {}Ctrl+D{} to exit.", C_BLUE, C_RESET);
stdlib::load(&mut env.borrow_mut());
stdlib::io::load(&mut env.borrow_mut());
stdlib::iter::load(&mut env.borrow_mut());
stdlib::math::load(&mut env.borrow_mut());
loop {
let readline = rl.readline(">> ");
match readline {
Ok(line) => {
Ok(mut line) => {
rl.add_history_entry(&line);
line.push(';');
let result = interpret(&line, None, Some(env.clone()), true);
match result {
Ok(value) => {

View File

@ -0,0 +1,13 @@
[package]
name = "complexpr-stdlib"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
complexpr = { path = "../complexpr"}
num-traits = "0.2.15"
paste = "1.0.9"
lazy_static = "1.4.0"
try-partialord = "0.1.3"

193
complexpr-stdlib/src/io.rs Normal file
View File

@ -0,0 +1,193 @@
use std::{io::{Write, Read}, fs::{OpenOptions, File}, rc::Rc, cell::RefCell, fmt};
use complexpr::{env::Environment, value::{Value, Native, TypeData}, RuntimeError};
use crate::declare_fn;
pub fn load(env: &mut Environment) {
let file_type = FILE_TYPE.with(|x| x.clone());
env.declare(file_type.name.clone(), Value::Type(file_type));
declare_fn!(env, print, 1);
declare_fn!(env, println, 1);
declare_fn!(env, input, 0);
declare_fn!(env, open, 2);
declare_fn!(env, close, 1);
declare_fn!(env, read, 1);
declare_fn!(env, write, 2);
declare_fn!(env, flush, 1);
}
fn fn_print(args: Vec<Value>) -> Result<Value, RuntimeError> {
print!("{}", args[0]);
std::io::stdout().flush().map_err(|e| e.to_string())?;
Ok(Value::Nil)
}
fn fn_println(args: Vec<Value>) -> Result<Value, RuntimeError> {
println!("{}", args[0]);
Ok(Value::Nil)
}
fn fn_input(_: Vec<Value>) -> Result<Value, RuntimeError> {
let mut buffer = String::new();
let stdin = std::io::stdin();
stdin.read_line(&mut buffer).map_err(|e| e.to_string())?;
if buffer.ends_with('\n') {
buffer.pop();
Ok(Value::from(buffer))
} else {
Ok(Value::Nil)
}
}
struct FileBox {
f: Option<File>
}
lazy_static::lazy_static! {
static ref FILE_TYPE_ID: usize = complexpr::value::generate_type_id();
}
thread_local!(static FILE_TYPE_NAME: Rc<str> = Rc::from("File"));
thread_local!(static FILE_TYPE: complexpr::value::Type = complexpr::value::Type { name: FILE_TYPE_NAME.with(Rc::clone), id: *FILE_TYPE_ID, typedata: TypeData::None });
impl Native for FileBox {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn get_type(&self) -> complexpr::value::Type {
FILE_TYPE.with(|x| x.clone())
}
}
impl fmt::Debug for FileBox {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for FileBox {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "<file {:?}>", self.f)
}
}
fn fn_open(args: Vec<Value>) -> Result<Value, RuntimeError> {
let fname = match &args[0] {
Value::String(s) => s,
_ => return Err(format!("Expected filename, got {}", args[0]).into())
};
let opts = match &args[1] {
Value::String(s) => s,
_ => return Err(format!("Expected open options string, got {}", args[0]).into())
};
let mut options = OpenOptions::new();
options.append(false);
for c in opts.chars() {
match c {
'r' => options.read(true),
'w' => options.write(true).append(false).truncate(true),
'a' => options.write(true).append(true).truncate(false),
's' => options.write(true).append(false).truncate(false),
'x' => options.create_new(false).create(true),
'X' => options.create(false).create_new(true),
_ => return Err(format!("Character {} is not valid in an open options string", c).into())
};
}
println!("{:?}", options);
let f = match options.open(fname.as_ref()) {
Ok(f) => f,
Err(e) => return Err(format!("Could not open file '{}': {}", fname, e).into())
};
Ok(Value::Native(Rc::new(RefCell::new(FileBox { f: Some(f) }))))
}
fn fn_close(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Native(s) => {
let mut bs = s.borrow_mut();
let f: &mut FileBox = match bs.as_any_mut().downcast_mut() {
Some(f) => f,
None => return Err(format!("Expected a file, got {}", args[0]).into())
};
match f.f.take() {
Some(x) => drop(x),
None => return Err("File already closed".into())
}
Ok(Value::Nil)
},
_ => Err(format!("Expected a file, got {}", args[0]).into())
}
}
fn fn_read(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Native(s) => {
let mut bs = s.borrow_mut();
let f: &mut FileBox = match bs.as_any_mut().downcast_mut() {
Some(f) => f,
None => return Err(format!("Expected a file, got {}", args[0]).into())
};
if let Some(file) = &mut f.f {
let mut buf = String::new();
match file.read_to_string(&mut buf) {
Ok(_) => Ok(Value::from(buf)),
Err(e) => Err(format!("Error reading file {}: {}", f, e).into())
}
} else {
Err("Attempt to read file that has been closed".into())
}
},
_ => Err(format!("Expected a file, got {}", args[0]).into())
}
}
fn fn_write(args: Vec<Value>) -> Result<Value, RuntimeError> {
let contents = match &args[1] {
Value::String(s) => s,
_ => return Err(format!("Expected string to write as second argument, got {}", args[1]).into())
};
match &args[0] {
Value::Native(s) => {
let mut bs = s.borrow_mut();
let f: &mut FileBox = match bs.as_any_mut().downcast_mut() {
Some(f) => f,
None => return Err(format!("Expected a file as first argument, got {}", args[0]).into())
};
if let Some(file) = &mut f.f {
match file.write(contents.as_bytes()) {
Ok(_) => Ok(Value::Nil),
Err(e) => Err(format!("Error writing to file {}: {}", f, e).into())
}
} else {
Err("Attempt to write to file that has been closed".into())
}
},
_ => Err(format!("Expected a file as first argument, got {}", args[0]).into())
}
}
fn fn_flush(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Native(s) => {
let mut bs = s.borrow_mut();
let f: &mut FileBox = match bs.as_any_mut().downcast_mut() {
Some(f) => f,
None => return Err(format!("Expected a file, got {}", args[0]).into())
};
if let Some(file) = &mut f.f {
match file.flush() {
Ok(_) => Ok(Value::Nil),
Err(e) => Err(format!("Error flushing file {}: {}", f, e).into())
}
} else {
Err("Attempt to flush file that has been closed".into())
}
},
_ => Err(format!("Expected a file, got {}", args[0]).into())
}
}

View File

@ -1,8 +1,12 @@
use std::{rc::Rc, cell::RefCell};
use crate::{value::{Value, func::Func}, RuntimeError, env::Environment, declare_fn};
use complexpr::{value::{Value, func::Func}, RuntimeError, env::Environment};
use crate::declare_fn;
pub fn load(env: &mut Environment) {
declare_fn!(env, iter, 1);
declare_fn!(env, next, 1);
declare_fn!(env, take, 2);
declare_fn!(env, skip, 2);
declare_fn!(env, forall, 2);
@ -10,6 +14,32 @@ pub fn load(env: &mut Environment) {
declare_fn!(env, nth, 2);
declare_fn!(env, last, 1);
declare_fn!(env, void, 1);
declare_fn!(env, rev, 1);
}
fn fn_iter(mut args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Func(f) if f.arg_count() == 0 => Ok(args.pop().unwrap()),
x => {
let it = RefCell::new(x.iter()?);
Ok(Value::Func(Func::BuiltinClosure {
arg_count: 0,
func: Rc::new(move |_| {
match it.borrow_mut().next() {
Some(x) => x,
None => Ok(Value::Nil)
}
})
} ))
}
}
}
fn fn_next(args: Vec<Value>) -> Result<Value, RuntimeError> {
match args[0].iter()?.next() {
Some(x) => x,
None => Ok(Value::Nil)
}
}
fn fn_take(args: Vec<Value>) -> Result<Value, RuntimeError> {
@ -96,3 +126,12 @@ fn fn_void(args: Vec<Value>) -> Result<Value, RuntimeError> {
for _ in args[0].iter()? {}
Ok(Value::Nil)
}
fn fn_rev(args: Vec<Value>) -> Result<Value, RuntimeError> {
let mut lst = vec![];
for item in args[0].iter()? {
lst.push(item?);
}
lst.reverse();
Ok(Value::from(lst))
}

View File

@ -0,0 +1,16 @@
pub mod prelude;
pub mod io;
pub mod iter;
pub mod math;
#[macro_export]
macro_rules! declare_fn {
($env:ident, $name:ident, $arg_count:literal) => {::paste::paste!{{
let s: ::std::rc::Rc<str> = ::std::rc::Rc::from(stringify!($name));
$env.declare(s.clone(), ::complexpr::value::Value::Func(::complexpr::value::func::Func::Builtin { func: [<fn_ $name>], arg_count: $arg_count, name: s }));
}}};
($env:ident, $name:literal, $rust_name:ident, $arg_count:literal) => {{
let s: ::std::rc::Rc<str> = ::std::rc::Rc::from($name);
$env.declare(s.clone(), ::complexpr::value::Value::Func(::complexpr::value::func::Func::Builtin { func: $rust_name, arg_count: $arg_count, name: s }));
}};
}

View File

@ -1,8 +1,10 @@
use std::cmp::Ordering;
use std::{cmp::Ordering, rc::Rc};
use num_traits::{ToPrimitive, Pow, Signed};
use num_traits::{ToPrimitive, Pow, Signed, Zero};
use crate::{value::{Value, Complex, Rational}, RuntimeError, env::Environment, declare_fn};
use complexpr::{value::{Value, Complex, Rational}, RuntimeError, env::Environment};
use crate::declare_fn;
enum Floaty {
Real(f64), Complex(Complex)
@ -21,15 +23,34 @@ impl From<Complex> for Floaty {
}
pub fn load(env: &mut Environment) {
declare_fn!(env, re, 1);
declare_fn!(env, im, 1);
env.declare(Rc::from("inf"), Value::from(f64::INFINITY));
env.declare(Rc::from("nan"), Value::from(f64::NAN));
env.declare(Rc::from("tau"), Value::from(std::f64::consts::TAU));
env.declare(Rc::from("pi"), Value::from(std::f64::consts::PI));
env.declare(Rc::from("e"), Value::from(std::f64::consts::E));
declare_fn!(env, min, 2);
declare_fn!(env, max, 2);
declare_fn!(env, abs, 1);
declare_fn!(env, numer, 1);
declare_fn!(env, denom, 1);
declare_fn!(env, rationalize, 1);
declare_fn!(env, re, 1);
declare_fn!(env, im, 1);
declare_fn!(env, conj, 1);
declare_fn!(env, arg, 1);
declare_fn!(env, norm, 1);
declare_fn!(env, norm_sq, 1);
declare_fn!(env, floor, 1);
declare_fn!(env, ceil, 1);
declare_fn!(env, round, 1);
declare_fn!(env, round_to, 2);
declare_fn!(env, fract, 1);
declare_fn!(env, trunc, 1);
declare_fn!(env, signum, 1);
declare_fn!(env, sin, 1);
declare_fn!(env, cos, 1);
declare_fn!(env, tan, 1);
@ -44,6 +65,10 @@ pub fn load(env: &mut Environment) {
declare_fn!(env, atanh, 1);
declare_fn!(env, exp, 1);
declare_fn!(env, "log", fn_ln, 1);
declare_fn!(env, sqrt, 1);
declare_fn!(env, gcd, 2);
declare_fn!(env, lcm, 2);
declare_fn!(env, is_prime, 1);
declare_fn!(env, factors, 1);
}
@ -52,13 +77,13 @@ pub fn load(env: &mut Environment) {
// Helper functions
//
fn try_into_floaty(v: &Value, name: &'static str) -> Result<Floaty, String> {
fn try_into_floaty(v: &Value, name: &str) -> Result<Floaty, String> {
match v {
Value::Int(n) => Ok((*n as f64).into()),
Value::Float(f) => Ok((*f).into()),
Value::Rational(r) => Ok((r.to_f64().ok_or_else(|| "Could not convert rational to float")?).into()),
Value::Complex(z) => Ok((*z).into()),
_ => Err(format!("Argument to {} must be numeric", name).into())
Value::Int(n) => Ok((*n as f64).into()),
Value::Rational(r) => Ok((r.to_f64().ok_or("Could not convert rational to float")?).into()),
_ => Err(format!("Argument to {} must be numeric", name))
}
}
@ -66,25 +91,6 @@ fn try_into_floaty(v: &Value, name: &'static str) -> Result<Floaty, String> {
// Misc functions
//
fn fn_re(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Int(x) => Ok(Value::Float(*x as f64)),
Value::Float(x) => Ok(Value::Float(*x)),
Value::Rational(x) => Ok(Value::Float(x.to_f64().unwrap())),
Value::Complex(x) => Ok(Value::Float(x.re)),
x => Err(format!("Cannot get real part of {:?}", x).into())
}
}
fn fn_im(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Int(_) | Value::Float(_) | Value::Rational(_)
=> Ok(Value::Float(0.0)),
Value::Complex(x) => Ok(Value::Float(x.im)),
x => Err(format!("Cannot get real part of {:?}", x).into())
}
}
fn fn_min(args: Vec<Value>) -> Result<Value, RuntimeError> {
match args[0].partial_cmp(&args[1]) {
None => Err("Arguments to min must be comparable".into()),
@ -106,10 +112,109 @@ fn fn_abs(args: Vec<Value>) -> Result<Value, RuntimeError> {
Value::Int(n) => Ok(Value::Int(n.abs())),
Value::Float(f) => Ok(Value::Float(f.abs())),
Value::Rational(r) => Ok(Value::Rational(r.abs())),
_ => Err("Argument to floor must be real".into()),
_ => Err("Argument to abs must be real".into()),
}
}
//
// Rationals
//
fn fn_numer(args: Vec<Value>) -> Result<Value, RuntimeError> {
match args[0] {
Value::Rational(r) => Ok(Value::from(*r.numer())),
Value::Int(n) => Ok(Value::from(n)),
_ => Err("Argument to numer must be integer or rational".into()),
}
}
fn fn_denom(args: Vec<Value>) -> Result<Value, RuntimeError> {
match args[0] {
Value::Rational(r) => Ok(Value::from(*r.denom())),
Value::Int(_) => Ok(Value::from(1)),
_ => Err("Argument to denom must be integer or rational".into()),
}
}
fn fn_rationalize(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Float(f) => match Rational::approximate_float(*f) {
Some(r) => Ok(Value::from(r)),
None => Err("Error rationalizing float".into())
},
Value::Int(n) => Ok(Value::Rational(Rational::from(*n))),
Value::Rational(r) => Ok(Value::Rational(*r)),
x => Err(format!("Expected float, int, or rational, got {}", x).into())
}
}
//
// Complex
//
fn fn_re(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Complex(x) => Ok(Value::Float(x.re)),
Value::Float(x) => Ok(Value::Float(*x)),
Value::Int(x) => Ok(Value::Float(*x as f64)),
Value::Rational(x) => Ok(Value::Float(x.to_f64().unwrap())),
x => Err(format!("Cannot get real part of {:?}", x).into())
}
}
fn fn_im(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Complex(x) => Ok(Value::Float(x.im)),
Value::Int(_) | Value::Float(_) | Value::Rational(_)
=> Ok(Value::Float(0.0)),
x => Err(format!("Cannot get real part of {:?}", x).into())
}
}
fn fn_conj(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Complex(x) => Ok(Value::from(x.conj())),
Value::Float(n) => Ok(Value::from(Complex::from(*n))),
Value::Int(n) => Ok(Value::from(Complex::from(*n as f64))),
Value::Rational(n) => Ok(Value::from(Complex::from(n.to_f64().unwrap()))),
x => Err(format!("Cannot get conjugate of {:?}", x).into())
}
}
fn fn_arg(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Complex(x) => Ok(Value::from(x.arg())),
Value::Float(n) if *n >= 0.0 => Ok(Value::from(0.0)),
Value::Float(_) => Ok(Value::from(std::f64::consts::PI)),
Value::Int(n) if *n >= 0 => Ok(Value::from(0.0)),
Value::Int(_) => Ok(Value::from(std::f64::consts::PI)),
Value::Rational(n) if *n >= Rational::zero() => Ok(Value::from(0.0)),
Value::Rational(_) => Ok(Value::from(std::f64::consts::PI)),
x => Err(format!("Cannot get argument of {:?}", x).into())
}
}
fn fn_norm(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Complex(x) => Ok(Value::from(x.norm())),
Value::Float(n) => Ok(Value::from(n.abs())),
Value::Int(n) => Ok(Value::from(n.abs() as f64)),
Value::Rational(n) => Ok(Value::from(n.abs().to_f64().unwrap())),
x => Err(format!("Cannot get norm of {:?}", x).into())
}
}
fn fn_norm_sq(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Complex(x) => Ok(Value::from(x.norm_sqr())),
Value::Float(n) => Ok(Value::from(n*n)),
Value::Int(n) => Ok(Value::from((*n as f64)*(*n as f64))),
Value::Rational(n) => { let x = n.to_f64().unwrap(); Ok(Value::from(x*x)) },
x => Err(format!("Cannot get norm squared of {:?}", x).into())
}
}
//
// Rounding
//
@ -179,6 +284,37 @@ fn fn_round_to(args: Vec<Value>) -> Result<Value, RuntimeError> {
}
}
fn fn_fract(args: Vec<Value>) -> Result<Value, RuntimeError> {
match args[0] {
Value::Int(_) => Ok(Value::Int(0)),
Value::Float(f) => Ok(Value::Float(f.fract())),
Value::Complex(c) => Ok(Value::Complex(Complex::new(c.re.fract(), c.im.fract()))),
Value::Rational(r) => Ok(Value::Rational(r.fract())),
_ => Err("Argument to fract must be numeric".into()),
}
}
fn fn_trunc(args: Vec<Value>) -> Result<Value, RuntimeError> {
match args[0] {
Value::Int(n) => Ok(Value::Int(n)),
Value::Float(f) => Ok(Value::Float(f.trunc())),
Value::Complex(c) => Ok(Value::Complex(Complex::new(c.re.trunc(), c.im.trunc()))),
Value::Rational(r) => Ok(Value::Rational(r.trunc())),
_ => Err("Argument to trunc must be numeric".into()),
}
}
fn fn_signum(args: Vec<Value>) -> Result<Value, RuntimeError> {
match args[0] {
Value::Int(n) => Ok(Value::Int(n.signum())),
Value::Float(f) => Ok(Value::Float(f.signum())),
Value::Complex(c) => Ok(Value::Complex(Complex::new(c.re.signum(), c.im.signum()))),
Value::Rational(r) => Ok(Value::Rational(r.signum())),
_ => Err("Argument to trunc must be numeric".into()),
}
}
//
// Transcendental functions
//
@ -211,15 +347,58 @@ transcendental!{ acosh }
transcendental!{ atanh }
transcendental!{ exp }
transcendental!{ ln }
transcendental!{ sqrt } // not technically transcendental
//
// Factorization
// Integers
//
fn gcd_inner(mut a: i64, mut b: i64) -> i64 {
if a == 0 {
return b
} else if b == 0 {
return a
}
let az = a.trailing_zeros();
a >>= az;
let bz = b.trailing_zeros();
b >>= bz;
let z = az.min(bz);
loop {
if a > b {
std::mem::swap(&mut a, &mut b);
}
b -= a;
if b == 0 {
return a << z;
}
b >>= b.trailing_zeros();
}
}
fn fn_gcd(args: Vec<Value>) -> Result<Value, RuntimeError> {
let (a, b) = match (&args[0], &args[1]) {
(Value::Int(a), Value::Int(b)) => (a.abs(), b.abs()),
_ => return Err("Arguments to gcd must be integers".into())
};
Ok(Value::from(gcd_inner(a, b)))
}
fn fn_lcm(args: Vec<Value>) -> Result<Value, RuntimeError> {
let (a, b) = match (&args[0], &args[1]) {
(Value::Int(a), Value::Int(b)) => (a.abs(), b.abs()),
_ => return Err("Arguments to lcm must be integers".into())
};
let gcd = gcd_inner(a, b);
Ok(Value::from(a/gcd * b))
}
fn fn_is_prime(args: Vec<Value>) -> Result<Value, RuntimeError> {
let n = match &args[0] {
Value::Int(n) => *n,
_ => return Err("Argument to is_prime must be an integer".into())
_ => return Err("Argument to is_prime must be integers".into())
};
match n {
_ if n <= 1 => Ok(Value::Bool(false)),
@ -227,21 +406,20 @@ fn fn_is_prime(args: Vec<Value>) -> Result<Value, RuntimeError> {
_ if (n % 2 == 0) || (n % 3 == 0) => Ok(Value::Bool(false)),
_ => {
let mut i = 5;
let mut d = 2;
while i*i <= n {
if n % i == 0 {
return Ok(Value::Bool(false));
}
i += 2;
if n % i == 0 {
return Ok(Value::Bool(false));
}
i += 4;
i += d;
d = 6 - d;
}
Ok(Value::Bool(true))
}
}
}
fn fn_factors(args: Vec<Value>) -> Result<Value, RuntimeError> {
let mut n = match &args[0] {
Value::Int(n) => n.abs(),
@ -251,7 +429,7 @@ fn fn_factors(args: Vec<Value>) -> Result<Value, RuntimeError> {
return Ok(Value::from(vec![]));
}
let mut factors = vec![];
while n % 2 == 0 {
while n & 1 == 0 {
factors.push(Value::Int(2));
n >>= 1;
}
@ -260,17 +438,18 @@ fn fn_factors(args: Vec<Value>) -> Result<Value, RuntimeError> {
n /= 3;
}
let mut i = 5;
let mut d = 2;
while n != 1 {
if i*i > n {
factors.push(Value::Int(n));
break;
}
while n % i == 0 {
factors.push(Value::Int(i));
n /= i;
}
i += 2;
while n % i == 0 {
factors.push(Value::Int(i));
n /= i;
}
i += 4;
i += d;
d = 6 - d;
}
Ok(Value::from(factors))

View File

@ -0,0 +1,338 @@
use std::{time::{SystemTime, UNIX_EPOCH}, rc::Rc, cell::RefCell};
use complexpr::{value::{Value, func::Func, self}, RuntimeError, env::Environment};
use try_partialord::TrySort;
use crate::declare_fn;
pub fn load(env: &mut Environment) {
for ty in value::generate_builtin_types() {
env.declare(ty.name.clone(), Value::Type(ty));
}
declare_fn!(env, "type", fn_type, 1);
declare_fn!(env, type_id, 1);
declare_fn!(env, type_eq, 2);
declare_fn!(env, copy, 1);
declare_fn!(env, str, 1);
declare_fn!(env, repr, 1);
declare_fn!(env, ord, 1);
declare_fn!(env, chr, 1);
declare_fn!(env, to_radix, 2);
declare_fn!(env, bin, 1);
declare_fn!(env, hex, 1);
declare_fn!(env, sex, 1);
declare_fn!(env, from_radix, 2);
declare_fn!(env, has, 2);
declare_fn!(env, len, 1);
declare_fn!(env, args, 0);
declare_fn!(env, time, 0);
declare_fn!(env, assert, 1);
declare_fn!(env, list, 1);
declare_fn!(env, push, 2);
declare_fn!(env, pop, 1);
declare_fn!(env, append, 2);
declare_fn!(env, insert, 3);
declare_fn!(env, remove, 2);
declare_fn!(env, rev, 1);
declare_fn!(env, sort, 1);
declare_fn!(env, sort_by, 2);
declare_fn!(env, sort_by_key, 2);
}
fn fn_type(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(Value::Type(args[0].get_type()))
}
fn fn_type_id(args: Vec<Value>) -> Result<Value, RuntimeError> {
if let Value::Type(ty) = &args[0] {
Ok(Value::Int(ty.id as i64))
} else {
Err("Argument to id must be a type".into())
}
}
fn fn_type_eq(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(Value::Bool(if args[0].get_type() != args[1].get_type() {
false
} else {
args[0] == args[1]
}))
}
fn fn_copy(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(match &args[0] {
Value::List(l) => Value::from(l.borrow().clone()),
Value::Map(m) => Value::from(m.borrow().clone()),
// Value::Func(f) => Value::Func(f.make_copy()) // TODO copy functions
Value::Struct(_) => todo!(),
a => a.clone(),
})
}
fn fn_str(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(Value::from(args[0].to_string()))
}
fn fn_repr(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(Value::from(args[0].repr()))
}
fn fn_ord(args: Vec<Value>) -> Result<Value, RuntimeError> {
if let Value::Char(c) = args[0] {
Ok(Value::from(c as u32))
} else {
Err("Argument to ord must be a char".into())
}
}
fn fn_chr(args: Vec<Value>) -> Result<Value, RuntimeError> {
if let Value::Int(i) = args[0] {
if i >= 0 && i < (u32::MAX as i64) {
if let Some(c) = char::from_u32(i as u32) {
return Ok(Value::from(c))
}
}
Err("Out of range".into())
} else {
Err("Argument to chr must be an integer".into())
}
}
fn to_radix(r: i64, mut n: i64) -> String {
let mut result = String::new();
let mut idx = 0;
if n == 0 {
result.push('0');
return result
} else if n < 0 {
n = -n;
idx = 1;
result.push('-');
}
while n != 0 {
let c = std::char::from_digit((n % r) as u32, r as u32).unwrap();
result.insert(idx, c);
n /= r;
}
result
}
fn fn_to_radix(args: Vec<Value>) -> Result<Value, RuntimeError> {
match (&args[0], &args[1]) {
(Value::Int(r), Value::Int(n))
if *r >= 2 && *r <= 36 => Ok(Value::from(to_radix(*r, *n))),
(Value::Int(_), Value::Int(_)) => Err(format!("Radix must be an integer in the range [2, 36]").into()),
(Value::Int(_), v) => Err(format!("Second argument to to_radix must be an integer, got {:?}", v).into()),
(v, _) => Err(format!("First argument to to_radix must be an integer, got {:?}", v).into()),
}
}
fn fn_bin(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Int(n) => Ok(Value::from(to_radix(2, *n))),
v => Err(format!("Argument to bin must be an integer, got {:?}", v).into()),
}
}
fn fn_hex(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Int(n) => Ok(Value::from(to_radix(16, *n))),
v => Err(format!("Argument to bin must be an integer, got {:?}", v).into()),
}
}
fn fn_sex(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Int(n) => Ok(Value::from(to_radix(6, *n))),
v => Err(format!("Argument to bin must be an integer, got {:?}", v).into()),
}
}
fn fn_from_radix(args: Vec<Value>) -> Result<Value, RuntimeError> {
match (&args[0], &args[1]) {
(Value::Int(r), Value::String(s))
if *r >= 2 && *r <= 36
=> match i64::from_str_radix(s, *r as u32) {
Ok(n) => Ok(Value::from(n)),
Err(_) => Err(format!("Failed to convert string to integer in specified radix").into()),
},
(Value::Int(_), Value::String(_)) => Err(format!("Radix must be an integer in the range [2, 36]").into()),
(Value::Int(_), v) => Err(format!("Second argument to from_radix must be a string, got {:?}", v).into()),
(v, _) => Err(format!("First argument to from_radix must be an integer, got {:?}", v).into()),
}
}
fn fn_len(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(Value::Int(args[0].len().map_err(RuntimeError::new_no_pos)? as i64))
}
fn fn_has(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Map(m) => Ok(Value::from(m.borrow().contains_key(&args[1]))),
v => Err(format!("Argument to has must be a map, got {:?} ", v).into())
}
}
fn fn_args(_: Vec<Value>) -> Result<Value, RuntimeError> {
let mut args = std::env::args();
args.next();
let args = RefCell::new(args);
Ok(Value::Func(Func::BuiltinClosure {
arg_count: 0,
func: Rc::new(move |_| {
match args.borrow_mut().next() {
Some(s) => Ok(Value::from(s)),
None => Ok(Value::Nil)
}
})
}))
}
fn fn_time(_: Vec<Value>) -> Result<Value, RuntimeError> {
let time = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?;
Ok(Value::from(time.as_secs_f64()))
}
fn fn_assert(args: Vec<Value>) -> Result<Value, RuntimeError> {
if args[0].truthy() {
Ok(Value::Nil)
} else {
Err("Assertion failed".into())
}
}
fn fn_list(args: Vec<Value>) -> Result<Value, RuntimeError> {
let a = args[0].iter()?;
let mut res = Vec::new();
for v in a { res.push(v?); }
Ok(Value::from(res))
}
fn fn_push(args: Vec<Value>) -> Result<Value, RuntimeError> {
if let Value::List(l) = &args[0] {
l.as_ref().borrow_mut().push(args[1].clone());
Ok(Value::Nil)
} else{
Err("First argument to push must be a list".into())
}
}
fn fn_pop(args: Vec<Value>) -> Result<Value, RuntimeError> {
if let Value::List(l) = &args[0] {
l.as_ref().borrow_mut().pop().ok_or_else(|| "Pop on empty list".into())
} else{
Err("First argument to pop must be a list".into())
}
}
fn fn_append(args: Vec<Value>) -> Result<Value, RuntimeError> {
match (&args[0], &args[1]) {
(Value::List(a), Value::List(b)) => {
let mut newvals = b.borrow().clone();
a.borrow_mut().append(&mut newvals);
Ok(Value::Nil)
},
_ => Err("Both arguments to append must be lists".into())
}
}
fn fn_insert(args: Vec<Value>) -> Result<Value, RuntimeError> {
match (&args[0], &args[1]) {
(Value::List(a), Value::Int(i)) => {
if *i < 0 {
return Err(format!("List index {} cannot be negative", i).into())
}
if *i > a.borrow().len() as i64 {
return Err(format!("List index {} not valid for list of length {}", i, a.borrow().len()).into())
}
a.borrow_mut().insert(*i as usize, args[2].clone());
Ok(Value::Nil)
},
(Value::Map(a), b) => {
Ok(a.borrow_mut().insert(b.clone(), args[3].clone()).unwrap_or(Value::Nil))
},
(Value::List(_), _) => Err("Second argument to insert must be an integer when the first is a list".into()),
_ => Err("First argument to insert must be a list or map".into()),
}
}
fn fn_remove(args: Vec<Value>) -> Result<Value, RuntimeError> {
match (&args[0], &args[1]) {
(Value::List(a), Value::Int(i)) => {
if *i < 0 {
return Err(format!("List index {} cannot be negative", i).into())
}
if *i >= a.borrow().len() as i64 {
return Err(format!("List index {} not valid for list of length {}", i, a.borrow().len()).into())
}
Ok(a.borrow_mut().remove(*i as usize))
},
(Value::Map(a), b) => {
Ok(a.borrow_mut().remove(b).unwrap_or(Value::Nil))
},
(Value::List(_), _) => Err("Second argument to remove must be an integer when the first is a list".into()),
_ => Err("First argument to remove must be a list or map".into()),
}
}
fn fn_rev(mut args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::List(l) => {
l.borrow_mut().reverse();
Ok(args.swap_remove(0))
},
Value::String(s) => {
let s: String = s.chars().rev().collect();
Ok(Value::from(s))
},
_ => Err(format!("Expected list or string, got {}", args[0]).into())
}
}
fn fn_sort(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::List(l) => match l.borrow_mut().try_sort() {
Ok(_) => Ok(args[0].clone()),
Err(_) => Err("List contained incomparable items".into())
},
_ => Err(format!("Expected list, got {}", args[0]).into())
}
}
fn fn_sort_by(args: Vec<Value>) -> Result<Value, RuntimeError> {
let func = match &args[1] {
Value::Func(f) => f,
x => return Err(format!("Expected function as second argument, got {}", x).into())
};
let ord = move |a: &Value, b: &Value| {
match func.call(vec![a.clone(), b.clone()]) {
Ok(Value::Int(n)) => Some(n < 0),
_ => None
}
};
match &args[0] {
Value::List(l) => match l.borrow_mut().try_sort_by(ord) {
Ok(_) => Ok(args[0].clone()),
Err(_) => Err("Error occured in sort comparison function".into())
},
_ => Err(format!("Expected list as first argument, got {}", args[0]).into())
}
}
fn fn_sort_by_key(args: Vec<Value>) -> Result<Value, RuntimeError> {
let func = match &args[1] {
Value::Func(f) => f,
x => return Err(format!("Expected function as second argument, got {}", x).into())
};
let ord = move |a: &Value| {
func.call(vec![a.clone()]).ok()
};
match &args[0] {
Value::List(l) => match l.borrow_mut().try_sort_by_key(ord) {
Ok(_) => Ok(args[0].clone()),
Err(_) => Err("Error occured in sort key function".into())
},
_ => Err(format!("Expected list as first argument, got {}", args[0]).into())
}
}

View File

@ -8,4 +8,3 @@ num-complex = "0.4.2"
num-rational = "0.4.1"
num-traits = "0.2.15"
strum = { version = "0.24.1", features = ["derive"] }
paste = "1.0.9"

View File

@ -115,7 +115,7 @@ pub fn eval_stmt(stmt: &Stmt, env: EnvRef) -> Result<(), Unwind> {
let name = name.ty.clone().as_ident().unwrap();
let func = Func::Func {
name: Some(name.clone()),
args: args.iter().map(|a| a.ty.clone().as_ident().unwrap()).collect(),
args: args.to_vec(),
env: env.clone(),
func: Box::new(body.as_ref().clone())
};
@ -144,7 +144,9 @@ pub fn eval_expr(expr: &Expr, env: EnvRef) -> Result<Value, RuntimeError> {
Some(OpType::Additive)
| Some(OpType::Multiplicative)
| Some(OpType::Exponential)
| Some(OpType::Comparison) => {
| Some(OpType::Comparison)
| Some(OpType::BitwiseAnd)
| Some(OpType::BitwiseOr) => {
let l = eval_expr(lhs, env.clone())?;
let r = eval_expr(rhs, env)?;
eval_standard_binary(l, r, &op.ty, &op.pos)
@ -217,14 +219,14 @@ pub fn eval_expr(expr: &Expr, env: EnvRef) -> Result<Value, RuntimeError> {
Expr::Fn { args, body } => {
let func = Func::Func {
name: None,
args: args.iter().map(|a| a.ty.clone().as_ident().unwrap()).collect(),
args: args.to_vec(),
env,
func: Box::new(body.as_ref().clone())
};
Ok(Value::Func(func))
},
Expr::StructInit { ty, args, .. } => {
let ty_val = eval_expr(&ty, env.clone())?;
let ty_val = eval_expr(ty, env.clone())?;
let ty = match ty_val {
Value::Type(ty) => ty,
_ => return Err(format!("'{}' is not a type", ty_val.repr()).into())
@ -294,7 +296,7 @@ pub fn eval_assignment(lhs: &Expr, rhs: &Expr, op: &Token, env: EnvRef) -> Resul
// plain assignment
let r = eval_expr(rhs, env.clone())?;
env.borrow_mut()
.set(name.clone(), r.clone())
.set(name, r.clone())
.map_err(|_| RuntimeError::new("Variable not declared before assignment", op.pos.clone()))?;
Ok(r)
} else {
@ -306,7 +308,7 @@ pub fn eval_assignment(lhs: &Expr, rhs: &Expr, op: &Token, env: EnvRef) -> Resul
let result = compound_assignment_inner(&prev_value, &r, op)?;
env.borrow_mut().set(name, result.clone()).expect("unreachable");
env.borrow_mut().set(name, result).expect("unreachable");
Ok(Value::Nil)
}
},
@ -321,7 +323,7 @@ pub fn eval_assignment(lhs: &Expr, rhs: &Expr, op: &Token, env: EnvRef) -> Resul
let prev_value = l.index(&idx).map_err(|e| RuntimeError::new(e, pos.clone()))?;
let r = eval_expr(rhs, env)?;
let result = compound_assignment_inner(&prev_value, &r, op)?;
l.assign_index(&idx, result.clone()).map_err(|e| RuntimeError::new(e, pos.clone()))?;
l.assign_index(&idx, result).map_err(|e| RuntimeError::new(e, pos.clone()))?;
Ok(Value::Nil)
}
},
@ -354,13 +356,15 @@ pub fn eval_assignment(lhs: &Expr, rhs: &Expr, op: &Token, env: EnvRef) -> Resul
}
pub fn eval_standard_binary(l: Value, r: Value, opty: &TokenType, pos: &Position) -> Result<Value, RuntimeError> {
let mk_err = || format!("Cannot compare {:?} with {:?}", l, r);
let mk_err = || format!("Cannot compare {} with {}", l, r);
match opty {
TokenType::Plus => &l + &r,
TokenType::Minus => &l - &r,
TokenType::Star => &l * &r,
TokenType::Slash => &l / &r,
TokenType::Percent => &l % &r,
TokenType::Amper => &l & &r,
TokenType::Pipe => &l | &r,
TokenType::Caret => l.pow(&r),
TokenType::DoubleSlash => l.fracdiv(&r),
TokenType::DoubleEqual => Ok(Value::Bool(l == r)),
@ -403,7 +407,7 @@ pub fn eval_boolean(lhs: &Expr, rhs: &Expr, op: &Token, env: EnvRef) -> Result<V
fn mk_pipecolon_inner(f: Func, it: CIterator) -> Func {
let it = RefCell::new(it);
return Func::BuiltinClosure{
Func::BuiltinClosure{
arg_count: 0,
func: Rc::new(move |_| {
if let Some(next) = it.borrow_mut().next() {
@ -417,7 +421,7 @@ fn mk_pipecolon_inner(f: Func, it: CIterator) -> Func {
fn mk_pipequestion_inner(f: Func, it: CIterator) -> Func {
let it = RefCell::new(it);
return Func::BuiltinClosure {
Func::BuiltinClosure {
arg_count: 0,
func: Rc::new(move |_| {
loop {
@ -456,21 +460,6 @@ fn eval_pipeline(l: Value, r: &Func, op: &Token) -> Result<Value, RuntimeError>
}
Ok(result)
},
TokenType::PipeDoubleBackslash => {
let mut result = Value::Nil;
let mut first_iter = true;
let lst = l.iter().map_err(|e| RuntimeError::new(e, op.pos.clone()))?.collect::<Vec<Result<Value, RuntimeError>>>();
for v in lst.into_iter().rev() {
let v = v.map_err(exit_pipe(&op.pos))?;
if first_iter {
result = v;
first_iter = false;
} else {
result = r.call(vec![v, result]).map_err(exit_pipe(&op.pos))?;
}
}
Ok(result)
},
_ => todo!()
}
@ -491,19 +480,6 @@ pub fn eval_ternary(arg1: &Expr, arg2: &Expr, arg3: &Expr, op: &Token, env: EnvR
}
Ok(result)
},
TokenType::PipeBackslash => {
let iter = eval_expr(arg1, env.clone())?;
let mut result = eval_expr(arg2, env.clone())?;
let func = eval_expr(arg3, env)?;
let func = func.as_func()
.map_err(|e| RuntimeError::new(e, op.pos.clone()))?;
let lst = iter.iter().map_err(|e| RuntimeError::new(e, op.pos.clone()))?.collect::<Vec<Result<Value, RuntimeError>>>();
for v in lst.into_iter().rev() {
let v = v.map_err(exit_pipe(&op.pos))?;
result = func.call(vec![v, result]).map_err(exit_pipe(&op.pos))?;
}
Ok(result)
},
_ => unreachable!()
}
}
@ -511,8 +487,9 @@ pub fn eval_ternary(arg1: &Expr, arg2: &Expr, arg3: &Expr, op: &Token, env: EnvR
pub fn eval_unary(arg: &Expr, op: &Token, env: EnvRef) -> Result<Value, RuntimeError> {
let a = eval_expr(arg, env)?;
match op.ty {
TokenType::Minus => -a,
TokenType::Minus => -&a,
TokenType::Bang => Ok(Value::Bool(!a.truthy())),
TokenType::Tilde => !&a,
_ => todo!(),
}.map_err(|e| RuntimeError::new(e, op.pos.clone()))
}

View File

@ -13,7 +13,7 @@ pub enum Stmt {
Break { pos: Position },
Continue { pos: Position },
Return { pos: Position, expr: Expr },
Fn { name: Token, args: Vec<Token>, body: Box<Stmt> },
Fn { name: Token, args: Vec<Rc<str>>, body: Box<Stmt> },
StructDef { name: Token, ty: Type },
}
@ -47,7 +47,7 @@ pub enum Expr {
Literal { value: Token },
List { items: Vec<Expr> },
Map { items: Vec<(Expr,Expr)> },
Fn { args: Vec<Token>, body: Box<Stmt> },
Fn { args: Vec<Rc<str>>, body: Box<Stmt> },
FuncCall { func: Box<Expr>, args: Vec<Expr>, pos: Position },
Index { lhs: Box<Expr>, index: Box<Expr>, pos: Position },
StructInit { ty: Box<Expr>, args: Vec<Expr>, pos: Position },

View File

@ -1,22 +1,19 @@
use std::{cell::RefCell, rc::Rc};
use crate::{value::Value, lexer::Lexer, parser::Parser, eval::{eval_stmt, eval_expr}, expr::Stmt, stdlib, env::{EnvRef, Environment}};
use crate::{value::Value, lexer::Lexer, parser::Parser, eval::{eval_stmt, eval_expr}, expr::Stmt, env::{EnvRef, Environment}};
pub fn interpret(src: &str, fname: Option<String>, env: Option<EnvRef>, repl: bool) -> Result<Value, Box<dyn std::error::Error>> {
let ctx_name = if repl { "<interactive input>" } else { fname.as_ref().map(|s| s.as_ref()).unwrap_or("<unknown>") };
let mut lexer = Lexer::new(src, fname.clone());
lexer.lex()?;
let mut parser = Parser::new(lexer.into_tokens(), repl);
let tokens = lexer.into_tokens();
let mut parser = Parser::new(tokens);
let ast = parser.parse()?;
let environ;
if let Some(env) = env {
environ = env;
} else {
environ = Rc::new(RefCell::new(Environment::new()));
stdlib::load(&mut environ.borrow_mut());
stdlib::io::load(&mut environ.borrow_mut());
stdlib::iter::load(&mut environ.borrow_mut());
stdlib::math::load(&mut environ.borrow_mut());
}
let mut result = Value::Nil;

View File

@ -2,6 +2,19 @@ use std::rc::Rc;
use crate::{ParserError, Position, token::{Token, TokenType}};
fn is_in_base(c: char, base: u32) -> bool {
match (c, base) {
('0' | '1', 2) => true,
('0'..='5', 6) => true,
('0'..='7', 8) => true,
('0'..='9', 10) => true,
('0'..='9' | 'a' | 'b' | 'A' | 'B', 12) => true,
('0'..='9' | 'a'..='f' | 'A'..='F', 16) => true,
_ => false
}
}
pub struct Lexer {
// name of file being lexed
filename: Option<Rc<str>>,
@ -213,13 +226,10 @@ impl Lexer {
Some('/') => self.add_token(TokenType::PipeDoubleSlash, "|//"),
_ => self.add_token(TokenType::PipeSlash, "|/")
},
Some('\\') => match self.expect(&['\\']) {
Some('\\') => self.add_token(TokenType::PipeDoubleBackslash, "|\\\\"),
_ => self.add_token(TokenType::PipeBackslash, "|\\")
},
_ => self.add_token(TokenType::Pipe, "|"),
},
'~' => self.add_token(TokenType::Tilde, "~"),
'\\' => self.add_token(TokenType::Backslash, "\\"),
',' => self.add_token(TokenType::Comma, ","),
';' => self.add_token(TokenType::Semicolon, ";"),
':' => self.add_token(TokenType::Colon, ":"),
@ -256,7 +266,15 @@ impl Lexer {
'"' => self.string()?,
'\'' => self.char()?,
' ' | '\t' | '\r' | '\n' => (),
'0'..='9' => self.number()?,
'0' => match self.expect(&['b', 's', 'o', 'd', 'x']) {
Some('b') => self.number(2)?,
Some('s') => self.number(6)?,
Some('o') => self.number(8)?,
Some('d') => self.number(12)?,
Some('x') => self.number(16)?,
_ => self.number(10)?,
},
'0'..='9' => self.number(10)?,
'a'..='z' | 'A'..='Z' | '_' => self.ident()?,
c => return Err(self.mk_error(format!("Unexpected character: {}", c)))
}
@ -306,9 +324,9 @@ impl Lexer {
Ok(())
}
fn number(&mut self) -> Result<(), ParserError> {
fn number(&mut self, base: u32) -> Result<(), ParserError> {
let mut has_dot = false;
while !self.at_end() && (self.peek().is_numeric() || self.peek() == '.') {
while !self.at_end() && (is_in_base(self.peek(), base) || self.peek() == '.') {
if self.peek() == '.' {
if has_dot {
break;
@ -316,6 +334,9 @@ impl Lexer {
if self.peek_ahead(1) == Some('.') {
break;
}
if base != 10 {
return Err(self.mk_error("Numeric literals using bases other than 10 must be integers."))
}
has_dot = true;
}
}
@ -334,10 +355,16 @@ impl Lexer {
Ok(num) => self.add_token(TokenType::Float(num), literal),
Err(e) => return Err(self.mk_error(format!("Error parsing float: {}", e)))
}
} else if base != 10 {
match i64::from_str_radix(&literal[2..literal.len()], base) {
Ok(num) => self.add_token(TokenType::Int(num), literal),
Err(e) => return Err(self.mk_error(format!("Error parsing integer: {}", e)))
}
} else {
match literal.parse::<i64>() {
Ok(num) => self.add_token(TokenType::Int(num), literal),
Err(e) => return Err(self.mk_error(format!("Error parsing float: {}", e)))
Err(e) => return Err(self.mk_error(format!("Error parsing integer: {}", e)))
}
}
Ok(())

View File

@ -8,7 +8,6 @@ pub mod value;
pub mod eval;
pub mod interpreter;
pub mod env;
pub mod stdlib;
#[derive(Clone, Debug)]
pub struct Position {

View File

@ -4,19 +4,18 @@ use crate::{token::{Token, TokenType, OpType}, ParserError, expr::{Stmt, Expr},
pub struct Parser {
tokens: Vec<Token>,
repl: bool,
idx: usize
}
impl Parser {
pub fn new(tokens: Vec<Token>, repl: bool) -> Self {
Self { tokens, repl, idx: 0 }
pub fn new(tokens: Vec<Token>) -> Self {
Self { tokens, idx: 0 }
}
pub fn parse(&mut self) -> Result<Vec<Stmt>, ParserError> {
let mut stmts = vec![];
while !self.at_end() {
stmts.push(self.statement(!self.repl)?);
stmts.push(self.statement()?);
}
Ok(stmts)
}
@ -80,9 +79,9 @@ impl Parser {
if self.peek().ty == TokenType::Comma {
self.next();
} else if self.peek().ty == terminator {
break;
break
} else {
return Err(self.mk_error(format!("Expected Comma or {:?} after list", terminator)))
return Err(self.mk_error(format!("Expected comma or {} after list", terminator)))
}
}
self.err_on_eof()?;
@ -96,14 +95,23 @@ impl Parser {
// //
//////////////////
fn statement(&mut self, req_semicolon: bool) -> Result<Stmt, ParserError> {
fn statement(&mut self) -> Result<Stmt, ParserError> {
let next_ty = &self.peek().ty;
match next_ty {
TokenType::Semicolon => {
// skip lonely semicolon
self.next();
if self.at_end() {
Ok(Stmt::Block { stmts: vec![] })
} else {
self.statement()
}
}
TokenType::Let => {
// let statement
self.next();
self.letstmt(req_semicolon)
self.letstmt()
},
TokenType::LBrace => {
// block
@ -127,16 +135,16 @@ impl Parser {
},
TokenType::Break => {
let tok = self.next();
self.terminate_stmt(Stmt::Break{ pos: tok.pos }, req_semicolon)
self.terminate_stmt(Stmt::Break{ pos: tok.pos })
},
TokenType::Continue => {
let tok = self.next();
self.terminate_stmt(Stmt::Continue{ pos: tok.pos }, req_semicolon)
self.terminate_stmt(Stmt::Continue{ pos: tok.pos })
},
TokenType::Return => {
let tok = self.next();
let expr = self.assignment()?;
self.terminate_stmt(Stmt::Return{ pos: tok.pos, expr }, req_semicolon)
self.terminate_stmt(Stmt::Return{ pos: tok.pos, expr })
},
TokenType::Fn => {
self.next();
@ -149,39 +157,34 @@ impl Parser {
_ => {
// fallback to an expression terminated with a semicolon
let expr = self.assignment()?;
self.terminate_stmt(Stmt::Expr{ expr }, req_semicolon)
self.terminate_stmt(Stmt::Expr{ expr })
}
}
}
fn terminate_stmt(&mut self, stmt: Stmt, req_semicolon: bool) -> Result<Stmt, ParserError> {
fn terminate_stmt(&mut self, stmt: Stmt) -> Result<Stmt, ParserError> {
if self.at_end() {
if req_semicolon {
self.err_on_eof()?;
} else{
return Ok(stmt)
}
self.err_on_eof()?;
}
match self.expect(TokenType::Semicolon).0 {
true => Ok(stmt),
false if !req_semicolon => Ok(stmt),
false => Err(self.mk_error("Missing semicolon after statement"))
}
}
fn letstmt(&mut self, req_semicolon: bool) -> Result<Stmt, ParserError> {
fn letstmt(&mut self) -> Result<Stmt, ParserError> {
let expr = self.assignment()?;
// must be followed by an assignment expression
if let Expr::Binary{lhs, rhs, op: Token{ty: TokenType::Equal,..}} = expr {
if let Expr::Ident{value: tok} = *lhs {
self.terminate_stmt(Stmt::Let{lhs: tok, rhs: Some(*rhs)}, req_semicolon)
self.terminate_stmt(Stmt::Let{lhs: tok, rhs: Some(*rhs)})
} else {
Err(self.mk_error("Invalid expression after 'let'".to_owned()))
}
} else if let Expr::Ident{value: tok} = expr {
self.terminate_stmt(Stmt::Let{lhs: tok, rhs: None}, req_semicolon)
self.terminate_stmt(Stmt::Let{lhs: tok, rhs: None})
} else {
Err(self.mk_error("Invalid expression after 'let'".to_owned()))
}
@ -192,7 +195,7 @@ impl Parser {
let mut ec = false;
loop {
let condition = self.assignment()?;
let body = self.statement(true)?;
let body = self.statement()?;
if_clauses.push((condition, body));
match self.peek().ty {
TokenType::Elif => { self.next(); continue },
@ -201,7 +204,7 @@ impl Parser {
}
}
let else_clause = if ec {
Some(Box::new(self.statement(true)?))
Some(Box::new(self.statement()?))
} else {
None
};
@ -222,7 +225,7 @@ impl Parser {
self.err_on_eof()?;
let expr = self.assignment()?;
self.err_on_eof()?;
let stmt = self.statement(true)?;
let stmt = self.statement()?;
Ok(Stmt::For{ var, expr, stmt: Box::new(stmt), iter_pos: colon.pos })
} else {
Err(self.mk_error("Expected identifier after for"))
@ -233,7 +236,7 @@ impl Parser {
self.err_on_eof()?;
let expr = self.assignment()?;
self.err_on_eof()?;
let stmt = self.statement(true)?;
let stmt = self.statement()?;
Ok(Stmt::While{ expr, stmt: Box::new(stmt) })
}
@ -250,6 +253,7 @@ impl Parser {
return Err(self.mk_error("Expected left parenthesis to start arguments list"))
}
let args = self.commalist(TokenType::RParen, Self::ident)?;
let args = args.iter().map(|a| a.ty.clone().as_ident().unwrap()).collect();
self.err_on_eof()?;
if self.peek().ty == TokenType::LParen {
self.next();
@ -273,7 +277,7 @@ impl Parser {
fn block(&mut self) -> Result<Stmt, ParserError> {
let mut stmts = vec![];
while !self.at_end() && self.peek().ty != TokenType::RBrace {
stmts.push(self.statement(true)?)
stmts.push(self.statement()?)
}
self.err_on_eof()?;
self.next();
@ -334,7 +338,7 @@ impl Parser {
while !self.at_end() && self.peek().ty.get_op_type() == Some(OpType::Pipeline) {
let op = self.next();
let right = self.logical_or()?;
if op.ty == TokenType::PipeSlash || op.ty == TokenType::PipeBackslash {
if op.ty == TokenType::PipeSlash {
self.err_on_eof()?;
if !self.expect(TokenType::Comma).0 {
return Err(self.mk_error("Expected comma after first argument"))
@ -357,7 +361,15 @@ impl Parser {
}
fn comparison(&mut self) -> Result<Expr, ParserError> {
self.expr(OpType::Comparison, Self::additive)
self.expr(OpType::Comparison, Self::bitwise_or)
}
fn bitwise_or(&mut self) -> Result<Expr, ParserError> {
self.expr(OpType::BitwiseOr, Self::bitwise_and)
}
fn bitwise_and(&mut self) -> Result<Expr, ParserError> {
self.expr(OpType::BitwiseAnd, Self::additive)
}
fn additive(&mut self) -> Result<Expr, ParserError> {
@ -410,8 +422,8 @@ impl Parser {
};
Ok(Expr::Range {
start: Box::new(start),
end: end.map(|x| Box::new(x)),
step: step.map(|x| Box::new(x)),
end: end.map(Box::new),
step: step.map(Box::new),
incl
})
} else {
@ -422,9 +434,9 @@ impl Parser {
// unary: !x, -x
fn unary(&mut self) -> Result<Expr, ParserError> {
self.err_on_eof()?;
if matches!(self.peek().ty, TokenType::Bang | TokenType::Minus) {
if matches!(self.peek().ty, TokenType::Minus | TokenType::Bang | TokenType::Tilde) {
let op = self.next();
Ok(Expr::Unary { arg: Box::new(self.fieldaccess()?), op })
Ok(Expr::Unary { arg: Box::new(self.unary()?), op })
} else {
self.fieldaccess()
}
@ -501,7 +513,7 @@ impl Parser {
self.err_on_eof()?;
let next = self.next();
if matches!(next.ty,
TokenType::True | TokenType::False | TokenType::Nil
TokenType::True | TokenType::False | TokenType::Nil
| TokenType::Int(_) | TokenType::Float(_) | TokenType::ImFloat(_)
| TokenType::String(_) | TokenType::Char(_)
) {
@ -511,28 +523,26 @@ impl Parser {
// An identifier
Ok(Expr::Ident { value: next })
} else if next.ty == TokenType::LParen {
// Special case for "boxed infix operators"
if !self.at_end() && self.peek().ty.is_infix_op() {
let op = self.next();
self.err_on_eof()?;
if self.peek().ty != TokenType::RParen {
return Err(self.mk_error("Expected right parenthesis after enclosed operator"))
}
self.next();
// Grouping with parentheses
let expr = self.assignment()?;
if self.at_end() || TokenType::RParen != self.next().ty {
Err(self.mk_error("Left parenthesis never closed"))
} else {
Ok(expr)
}
} else if next.ty == TokenType::Backslash {
self.err_on_eof()?;
let op = self.next();
if op.ty.is_infix_op() {
let func = Func::BuiltinClosure {
arg_count: 2,
func: Rc::new(move |args| {
eval_standard_binary(args[0].clone(), args[1].clone(), &op.ty, &op.pos)
})
};
return Ok(Expr::BoxedInfix { func })
}
// general case: parentheses as grouping symbols
let expr = self.assignment()?;
if self.at_end() || TokenType::RParen != self.next().ty {
Err(self.mk_error("Left parenthesis never closed"))
Ok(Expr::BoxedInfix { func })
} else {
Ok(expr)
Err(self.mk_error("Expected infix operator after backslash"))
}
} else if next.ty == TokenType::LBrack {
// list literal
@ -549,6 +559,7 @@ impl Parser {
return Err(self.mk_error("Expected left parenthesis to start arguments list"))
}
let args = self.commalist(TokenType::RParen, Self::ident)?;
let args = args.iter().map(|a| a.ty.clone().as_ident().unwrap()).collect();
self.err_on_eof()?;
if self.peek().ty == TokenType::LParen {
self.next();
@ -568,7 +579,7 @@ impl Parser {
Err(self.mk_error("Expected '(' or '{' after function arguments list to begin body"))
}
} else {
Err(self.mk_error(format!("Unexpected token: {:?}", next.ty)))
Err(self.mk_error(format!("Unexpected token: {}", next.ty)))
}
}
}

View File

@ -1,30 +0,0 @@
use std::io::Write;
use crate::{env::Environment, declare_fn, value::Value, RuntimeError};
pub fn load(env: &mut Environment) {
declare_fn!(env, print, 1);
declare_fn!(env, println, 1);
declare_fn!(env, input, 0);
}
fn fn_print(args: Vec<Value>) -> Result<Value, RuntimeError> {
print!("{}", args[0].to_string());
std::io::stdout().flush().map_err(|e| e.to_string())?;
Ok(Value::Nil)
}
fn fn_println(args: Vec<Value>) -> Result<Value, RuntimeError> {
println!("{}", args[0].to_string());
Ok(Value::Nil)
}
fn fn_input(_: Vec<Value>) -> Result<Value, RuntimeError> {
let mut buffer = String::new();
let stdin = std::io::stdin();
stdin.read_line(&mut buffer).map_err(|e| e.to_string())?;
if buffer.ends_with('\n') {
buffer.pop();
}
Ok(Value::from(buffer))
}

View File

@ -1,179 +0,0 @@
pub mod io;
pub mod iter;
pub mod math;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::{value::Value, RuntimeError, env::Environment};
#[macro_export]
macro_rules! declare_fn {
($env:ident, $name:ident, $arg_count:literal) => {::paste::paste!{{
let s: ::std::rc::Rc<str> = ::std::rc::Rc::from(stringify!($name));
$env.declare(s.clone(), $crate::value::Value::Func($crate::value::func::Func::Builtin { func: [<fn_ $name>], arg_count: $arg_count, name: s }));
}}};
($env:ident, $name:literal, $rust_name:ident, $arg_count:literal) => {{
let s: ::std::rc::Rc<str> = ::std::rc::Rc::from($name);
$env.declare(s.clone(), $crate::value::Value::Func($crate::value::func::Func::Builtin { func: $rust_name, arg_count: $arg_count, name: s }));
}};
}
pub fn load(env: &mut Environment) {
declare_fn!(env, "type", fn_type, 1);
declare_fn!(env, type_eq, 1);
declare_fn!(env, copy, 1);
declare_fn!(env, str, 1);
declare_fn!(env, repr, 1);
declare_fn!(env, ord, 1);
declare_fn!(env, chr, 1);
declare_fn!(env, has, 2);
declare_fn!(env, len, 1);
declare_fn!(env, time, 0);
declare_fn!(env, list, 1);
declare_fn!(env, push, 2);
declare_fn!(env, pop, 1);
declare_fn!(env, append, 2);
declare_fn!(env, insert, 3);
declare_fn!(env, remove, 2);
}
fn fn_type(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(Value::Type(args[0].get_type()))
}
fn fn_type_eq(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(Value::Bool(if args[0].get_type() != args[1].get_type() {
false
} else {
args[0] == args[1]
}))
}
fn fn_copy(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(match &args[0] {
Value::List(l) => Value::from(l.borrow().clone()),
Value::Map(m) => Value::from(m.borrow().clone()),
// Value::Func(f) => Value::Func(f.make_copy()) // TODO copy functions
Value::Struct(_) => todo!(),
a => a.clone(),
})
}
fn fn_str(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(Value::from(args[0].to_string()))
}
fn fn_repr(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(Value::from(args[0].repr()))
}
fn fn_ord(args: Vec<Value>) -> Result<Value, RuntimeError> {
if let Value::Char(c) = args[0] {
Ok(Value::from(c as u32))
} else {
Err("Argument to ord must be a char".into())
}
}
fn fn_chr(args: Vec<Value>) -> Result<Value, RuntimeError> {
if let Value::Int(i) = args[0] {
if i >= 0 && i < (u32::MAX as i64) {
if let Some(c) = char::from_u32(i as u32) {
return Ok(Value::from(c))
}
}
Err("Out of range".into())
} else {
Err("Argument to chr must be an integer".into())
}
}
fn fn_len(args: Vec<Value>) -> Result<Value, RuntimeError> {
Ok(Value::Int(args[0].len().map_err(RuntimeError::new_no_pos)? as i64))
}
fn fn_has(args: Vec<Value>) -> Result<Value, RuntimeError> {
match &args[0] {
Value::Map(m) => Ok(Value::from(m.borrow().contains_key(&args[1]))),
v => Err(format!("Argument to has must be a map, got {:?} ", v).into())
}
}
fn fn_time(_: Vec<Value>) -> Result<Value, RuntimeError> {
let time = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?;
Ok(Value::from(time.as_secs_f64()))
}
fn fn_list(args: Vec<Value>) -> Result<Value, RuntimeError> {
let a = args[0].iter()?;
let mut res = Vec::new();
for v in a { res.push(v?); }
Ok(Value::from(res))
}
fn fn_push(args: Vec<Value>) -> Result<Value, RuntimeError> {
if let Value::List(l) = &args[0] {
l.as_ref().borrow_mut().push(args[1].clone());
Ok(Value::Nil)
} else{
Err("First argument to push must be a list".into())
}
}
fn fn_pop(args: Vec<Value>) -> Result<Value, RuntimeError> {
if let Value::List(l) = &args[0] {
l.as_ref().borrow_mut().pop().ok_or("Pop on empty list".into())
} else{
Err("First argument to pop must be a list".into())
}
}
fn fn_append(args: Vec<Value>) -> Result<Value, RuntimeError> {
match (&args[0], &args[1]) {
(Value::List(a), Value::List(b)) => {
let mut newvals = b.borrow().clone();
a.borrow_mut().append(&mut newvals);
Ok(Value::Nil)
},
_ => Err("Both arguments to append must be lists".into())
}
}
fn fn_insert(args: Vec<Value>) -> Result<Value, RuntimeError> {
match (&args[0], &args[1]) {
(Value::List(a), Value::Int(i)) => {
if *i < 0 {
return Err(format!("List index {} cannot be negative", i).into())
}
if *i > a.borrow().len() as i64 {
return Err(format!("List index {} not valid for list of length {}", i, a.borrow().len()).into())
}
a.borrow_mut().insert(*i as usize, args[2].clone());
Ok(Value::Nil)
},
(Value::Map(a), b) => {
Ok(a.borrow_mut().insert(b.clone(), args[3].clone()).unwrap_or(Value::Nil))
},
(Value::List(_), _) => Err("Second argument to insert must be an integer when the first is a list".into()),
_ => Err("First argument to insert must be a list or map".into()),
}
}
fn fn_remove(args: Vec<Value>) -> Result<Value, RuntimeError> {
match (&args[0], &args[1]) {
(Value::List(a), Value::Int(i)) => {
if *i < 0 {
return Err(format!("List index {} cannot be negative", i).into())
}
if *i >= a.borrow().len() as i64 {
return Err(format!("List index {} not valid for list of length {}", i, a.borrow().len()).into())
}
Ok(a.borrow_mut().remove(*i as usize))
},
(Value::Map(a), b) => {
Ok(a.borrow_mut().remove(b).unwrap_or(Value::Nil))
},
(Value::List(_), _) => Err("Second argument to remove must be an integer when the first is a list".into()),
_ => Err("First argument to remove must be a list or map".into()),
}
}

View File

@ -31,18 +31,92 @@ pub enum TokenType {
DoubleEqual, BangEqual, Greater, GreaterEqual, Less, LessEqual, Spaceship,
PipeColon, PipePoint, PipeQuestion, PipeAmper,
PipeSlash, PipeBackslash, PipeDoubleSlash, PipeDoubleBackslash,
PipeSlash, PipeDoubleSlash,
Backslash,
Comma, Semicolon, Colon,
LParen, RParen, LBrack, RBrack, LBrace, RBrace,
True, False, Nil,
True, False, Nil,
If, Elif, Else, For, While,
Fn, Let, Struct,
Break, Continue, Return
}
impl fmt::Display for TokenType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TokenType::Int(n) => write!(f, "integer literal {}", n),
TokenType::Float(x) => write!(f, "float literal {}", x),
TokenType::ImFloat(x) => write!(f, "imaginary float literal {}i", x),
TokenType::String(s) => write!(f, "string literal {}", crate::value::Value::from(s.as_ref())),
TokenType::Char(c) => write!(f, "character literal {}", crate::value::Value::from(*c)),
TokenType::Ident(n) => write!(f, "identifier '{}'", n),
TokenType::Plus => f.write_str("operator +"),
TokenType::Minus => f.write_str("operator -"),
TokenType::Star => f.write_str("operator *"),
TokenType::Slash => f.write_str("operator /"),
TokenType::Percent => f.write_str("operator %"),
TokenType::DoubleSlash => f.write_str("operator //"),
TokenType::Caret => f.write_str("operator ^"),
TokenType::Bang => f.write_str("operator !"),
TokenType::DoubleAmper => f.write_str("operator &&"),
TokenType::DoublePipe => f.write_str("operator ||"),
TokenType::Tilde => f.write_str("operator ~"),
TokenType::Amper => f.write_str("operator &"),
TokenType::Pipe => f.write_str("operator |"),
TokenType::Dot => f.write_str("operator ."),
TokenType::DoubleDot => f.write_str("operator .."),
TokenType::Equal => f.write_str("operator ="),
TokenType::PlusEqual => f.write_str("operator +="),
TokenType::MinusEqual => f.write_str("operator -="),
TokenType::StarEqual => f.write_str("operator *="),
TokenType::SlashEqual => f.write_str("operator /="),
TokenType::PercentEqual => f.write_str("operator %="),
TokenType::DoubleSlashEqual => f.write_str("operator //="),
TokenType::CaretEqual => f.write_str("operator ^="),
TokenType::DoubleEqual => f.write_str("operator =="),
TokenType::BangEqual => f.write_str("operator !="),
TokenType::Greater => f.write_str("operator >"),
TokenType::GreaterEqual => f.write_str("operator >="),
TokenType::Less => f.write_str("operator <"),
TokenType::LessEqual => f.write_str("operator <="),
TokenType::Spaceship => f.write_str("operator <=>"),
TokenType::PipeColon => f.write_str("operator |:"),
TokenType::PipePoint => f.write_str("operator |>"),
TokenType::PipeQuestion => f.write_str("operator |?"),
TokenType::PipeAmper => f.write_str("operator |&"),
TokenType::PipeSlash => f.write_str("operator |/"),
TokenType::PipeDoubleSlash => f.write_str("operator |//"),
TokenType::Backslash => f.write_str("backslash"),
TokenType::Comma => f.write_str("comma"),
TokenType::Semicolon => f.write_str("semicolon"),
TokenType::Colon => f.write_str("colon"),
TokenType::LParen => f.write_str("left paren"),
TokenType::RParen => f.write_str("right paren"),
TokenType::LBrack => f.write_str("left bracket"),
TokenType::RBrack => f.write_str("right bracket"),
TokenType::LBrace => f.write_str("left brace"),
TokenType::RBrace => f.write_str("right brace"),
TokenType::True => f.write_str("literal 'true'"),
TokenType::False => f.write_str("literal 'false'"),
TokenType::Nil => f.write_str("literal 'nil'"),
TokenType::If => f.write_str("keyword 'if'"),
TokenType::Elif => f.write_str("keyword 'elif'"),
TokenType::Else => f.write_str("keyword 'else'"),
TokenType::For => f.write_str("keyword 'for'"),
TokenType::While => f.write_str("keyword 'while'"),
TokenType::Fn => f.write_str("keyword 'fn'"),
TokenType::Let => f.write_str("keyword 'let'"),
TokenType::Struct => f.write_str("keyword 'struct'"),
TokenType::Break => f.write_str("keyword 'break'"),
TokenType::Continue => f.write_str("keyword 'continue'"),
TokenType::Return => f.write_str("keyword 'return'"),
}
}
}
impl TokenType {
pub fn get_op_type(&self) -> Option<OpType> {
match self {
@ -54,7 +128,7 @@ impl TokenType {
Self::Caret => Some(OpType::Exponential),
Self::PipeColon | Self::PipeAmper | Self::PipePoint | Self::PipeQuestion
| Self::PipeSlash | Self::PipeDoubleSlash | Self::PipeBackslash | Self::PipeDoubleBackslash => Some(OpType::Pipeline),
| Self::PipeSlash | Self::PipeDoubleSlash => Some(OpType::Pipeline),
Self::Greater | Self::GreaterEqual | Self::Less | Self::LessEqual
| Self::DoubleEqual | Self::BangEqual | Self::Spaceship => Some(OpType::Comparison),
@ -63,6 +137,9 @@ impl TokenType {
| Self::StarEqual | Self::SlashEqual | Self::DoubleSlashEqual
| Self::CaretEqual | Self::PercentEqual => Some(OpType::Assignment),
Self::Amper => Some(OpType::BitwiseAnd),
Self::Pipe => Some(OpType::BitwiseOr),
Self::DoubleAmper => Some(OpType::LogicalAnd),
Self::DoublePipe => Some(OpType::LogicalOr),
@ -83,6 +160,8 @@ impl TokenType {
| OpType::Multiplicative
| OpType::Exponential
| OpType::Comparison
| OpType::BitwiseAnd
| OpType::BitwiseOr
// TODO | OpType::Pipeline
))
}
@ -90,7 +169,10 @@ impl TokenType {
#[derive(Clone,Copy,Debug,PartialEq,Eq)]
pub enum OpType {
Assignment, Comparison, Pipeline, Additive, Multiplicative, Exponential, LogicalAnd, LogicalOr
Assignment, Comparison, Pipeline,
Additive, Multiplicative, Exponential,
LogicalAnd, LogicalOr,
BitwiseAnd, BitwiseOr,
}
impl OpType {

View File

@ -1,4 +1,4 @@
use std::{rc::Rc, collections::HashMap, ops::*, cmp::Ordering, cell::RefCell, hash::Hash, sync::atomic::{AtomicUsize, self}};
use std::{rc::Rc, collections::HashMap, ops::*, cmp::Ordering, cell::RefCell, hash::Hash, sync::atomic::{AtomicUsize, self}, fmt::{self, Write}, any::Any};
use num_traits::{Zero, ToPrimitive, Pow};
use strum::{EnumCount, EnumDiscriminants, EnumIter, IntoEnumIterator, AsRefStr};
@ -10,6 +10,12 @@ pub mod func;
pub type Rational = num_rational::Ratio<i64>;
pub type Complex = num_complex::Complex64;
pub trait Native: Any + std::fmt::Debug + std::fmt::Display {
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
fn get_type(&self) -> Type;
}
static TYPE_COUNTER: AtomicUsize = AtomicUsize::new(Value::COUNT);
#[derive(Clone, Debug)]
@ -33,6 +39,10 @@ impl PartialEq for Type {
impl Eq for Type {}
pub fn generate_type_id() -> usize {
TYPE_COUNTER.fetch_add(1, atomic::Ordering::Relaxed)
}
pub fn generate_struct_type(name: Rc<str>, fields: Vec<String>) -> Type {
Type {
name,
@ -44,32 +54,38 @@ pub fn generate_struct_type(name: Rc<str>, fields: Vec<String>) -> Type {
pub fn generate_builtin_types() -> Vec<Type> {
let mut types = vec![];
for x in ValueDiscriminants::iter() {
types.push(Type {
name: Rc::from(x.as_ref()),
id: x as usize,
typedata: TypeData::None,
})
if x != ValueDiscriminants::Struct && x != ValueDiscriminants::Native {
types.push(Type {
name: Rc::from(x.as_ref()),
id: x as usize,
typedata: TypeData::None,
})
}
}
types
}
fn fmt_list(list: &Vec<Value>) -> String {
let mut result: String = "[".into();
for v in list {
result += &(v.repr() + ", ");
if !list.is_empty() {
for v in list {
result += &(v.repr() + ", ");
}
result.pop();
result.pop();
}
result.pop();
result.pop();
result + "]"
}
fn fmt_map(map: &HashMap<Value, Value>) -> String {
let mut result: String = "{".into();
for (k, v) in map {
result += &(k.repr() + ": " + &v.repr() + ", ");
if !map.is_empty() {
for (k, v) in map {
result += &(k.repr() + ": " + &v.repr() + ", ");
}
result.pop();
result.pop();
}
result.pop();
result.pop();
result + "}"
}
@ -140,6 +156,7 @@ pub enum Value {
Map(Rc<RefCell<HashMap<Value,Value>>>),
Func(Func),
Struct(CxprStruct),
Native(Rc<RefCell<dyn Native>>),
}
impl Value {
@ -150,9 +167,9 @@ impl Value {
Float(f) => *f != 0.0,
Complex(z) => !z.is_zero(),
Rational(r) => !r.is_zero(),
String(s) => !s.len() == 0,
List(l) => !l.borrow().len() == 0,
Map(m) => !m.borrow().len() == 0,
String(s) => s.len() != 0,
List(l) => l.borrow().len() != 0,
Map(m) => m.borrow().len() != 0,
Char(c) => *c != '\0',
_ => true
}
@ -180,35 +197,6 @@ impl Value {
}
}
pub fn to_string(&self) -> String {
match self {
Self::Nil => "nil".into(),
Self::Bool(b) => b.to_string(),
Self::Int(n) => n.to_string(),
Self::Float(f) => f.to_string(),
Self::Rational(r) => r.to_string(),
Self::Complex(z) => z.to_string(),
Self::Char(c) => c.to_string(),
Self::String(s) => s.as_ref().to_owned(),
Self::List(l) => fmt_list(&l.borrow()),
Self::Map(m) => fmt_map(&m.borrow()),
Self::Type(t) => format!("<type {}>", t.name),
Self::Func(Func::Builtin { name, func, .. }) => format!("<builtin fn {} at {:?}>", name, *func as *const ()),
Self::Func(Func::BuiltinClosure { .. }) => format!("<builtin anonymous fn>"),
Self::Func(f @ Func::Partial { .. }) => match f.name() {
Some(name) => format!("<partial of fn {}>", name),
None => "<partial of anonymous fn>".into(),
}
Self::Func(Func::Func { name, .. }) => match name {
Some(name) => format!("<fn {}>", name),
None => "<anonymous fn>".into(),
},
Self::Struct(CxprStruct { ty, data })
=> format!("{} {{ {} }}", ty.name,
data.borrow().iter().map(|(k, v)| format!("{}: {}", k, v.repr()))
.collect::<Vec<String>>().join(", "))
}
}
pub fn repr(&self) -> String {
match self {
@ -290,8 +278,10 @@ impl Value {
pub fn get_type(&self) -> Type {
let discr = ValueDiscriminants::from(self);
if let Self::Struct(_) = self {
todo!()
if let Self::Struct(s) = self {
s.ty.clone()
} else if let Self::Native(n) = self {
n.borrow().get_type()
} else {
Type {
name: Rc::from(discr.as_ref()),
@ -302,6 +292,39 @@ impl Value {
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Nil => f.write_str("nil"),
Self::Bool(b) => f.write_str(&b.to_string()),
Self::Int(n) => f.write_str(&n.to_string()),
Self::Float(x) => f.write_str(&x.to_string()),
Self::Rational(r) => f.write_str(&r.to_string()),
Self::Complex(z) => f.write_str(&z.to_string()),
Self::Char(c) => f.write_char(*c),
Self::String(s) => f.write_str(s.as_ref()),
Self::List(l) => f.write_str(&fmt_list(&l.borrow())),
Self::Map(m) => f.write_str(&fmt_map(&m.borrow())),
Self::Type(t) => write!(f, "<type {}>", t.name),
Self::Func(Func::Builtin { name, func, .. }) => write!(f, "<builtin fn {} at {:?}>", name, *func as *const ()),
Self::Func(Func::BuiltinClosure { .. }) => f.write_str("<builtin anonymous fn>"),
Self::Func(func @ Func::Partial { .. }) => match func.name() {
Some(name) => write!(f, "<partial of fn {}>", name),
None => f.write_str("<partial of anonymous fn>"),
}
Self::Func(Func::Func { name, .. }) => match name {
Some(name) => write!(f, "<fn {}>", name),
None => f.write_str("<anonymous fn>"),
},
Self::Struct(CxprStruct { ty, data })
=> write!(f, "{} {{ {} }}", ty.name,
data.borrow().iter().map(|(k, v)| format!("{}: {}", k, v.repr()))
.collect::<Vec<String>>().join(", ")),
Self::Native(x) => f.write_str(&x.borrow().to_string()),
}
}
}
#[allow(clippy::ptr_eq)] // provided fix does not work
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
@ -415,6 +438,7 @@ impl Hash for Value {
Self::Map(_) => todo!(),
Self::Func(f) => f.hash(state),
Self::Struct(_) => todo!(),
Self::Native(_) => todo!(),
}
}
@ -449,14 +473,14 @@ value_from!(Float, f32 f64);
value_from!(Complex, Complex);
value_from!(Rational, Rational);
value_from!(Bool, bool);
value_from!(String, String Rc<str>);
value_from!(String, String Rc<str> &str);
value_from!(List, RefCell<Vec<Value>>);
value_from!(Char, char);
value_from!(Map, RefCell<HashMap<Value,Value>>);
macro_rules! impl_numeric_op {
($optrait:ty, $fnname:ident, { $($bonus:tt)* }) => {
($optrait:ty, $fnname:ident, $op:literal, { $($bonus:tt)* }) => {
impl $optrait for &Value {
type Output = Result<Value, String>;
fn $fnname(self, other: Self) -> Self::Output {
@ -480,14 +504,14 @@ macro_rules! impl_numeric_op {
(Rational(a), Complex(b)) => Ok(self::Complex::from(a.to_f64().ok_or(RATIO_CAST_FAIL)?).$fnname(b).into()),
(Complex(a), Rational(b)) => Ok(a.$fnname(self::Complex::from(b.to_f64().ok_or(RATIO_CAST_FAIL)?)).into()),
(Complex(a), Complex(b)) => Ok(a.$fnname(b).into()),
(lhs, rhs) => Err(format!("Unsupported operation '{}' between {} and {}", stringify!($fnname), lhs.repr(), rhs.repr()))
(lhs, rhs) => Err(format!("Unsupported operation '{}' between {} and {}", $op, lhs.repr(), rhs.repr()))
}
}
}
}
}
impl Neg for Value {
impl Neg for &Value {
type Output = Result<Value, String>;
fn neg(self) -> Self::Output {
match self {
@ -500,7 +524,7 @@ impl Neg for Value {
}
}
impl_numeric_op!(Add, add, {
impl_numeric_op!(Add, add, "+", {
(String(a), String(b)) => Ok(((**a).to_owned() + b).into()),
(String(a), Char(c)) => {
let mut s = (**a).to_owned();
@ -519,20 +543,20 @@ impl_numeric_op!(Add, add, {
Ok(a.into())
},
});
impl_numeric_op!(Sub, sub, {});
impl_numeric_op!(Mul, mul, {
impl_numeric_op!(Sub, sub, "-", {});
impl_numeric_op!(Mul, mul, "*", {
(String(a), Int(b)) | (Int(b), String(a))
=> Ok(Value::from(a.chars().cycle().take(a.chars().count()*(*b as usize)).collect::<std::string::String>())),
(List(a), Int(b)) | (Int(b), List(a))
=> Ok(Value::from(a.borrow().iter().cycle().take(a.borrow().len()*(*b as usize)).cloned().collect::<Vec<Value>>())),
});
impl_numeric_op!(Div, div, {
impl_numeric_op!(Div, div, "/", {
(Int(_), Int(b)) if *b == 0 => Err("Integer division by zero".into()),
(Rational(_), Int(b)) if *b == 0 => Err("Rational division by zero".into()),
(Int(_), Rational(b)) if b.is_zero() => Err("Rational division by zero".into()),
(Rational(_), Rational(b)) if b.is_zero() => Err("Rational division by zero".into()),
});
impl_numeric_op!(Rem, rem, {
impl_numeric_op!(Rem, rem, "%", {
(Int(_), Int(b)) if *b == 0 => Err("Integer modulo by zero".into()),
(Rational(_), Int(b)) if *b == 0 => Err("Rational modulo by zero".into()),
(Int(_), Rational(b)) if b.is_zero() => Err("Rational modulo by zero".into()),
@ -570,7 +594,46 @@ impl Pow<&Value> for &Value {
(Rational(a), Complex(b)) => Ok(self::Complex::from(a.to_f64().ok_or(RATIO_CAST_FAIL)?).pow(b).into()),
(Complex(a), Rational(b)) => Ok(a.pow(self::Complex::from(b.to_f64().ok_or(RATIO_CAST_FAIL)?)).into()),
(Complex(a), Complex(b)) => Ok(a.pow(b).into()),
(lhs, rhs) => Err(format!("Unsupported operation 'pow' between {} and {}", lhs.repr(), rhs.repr()))
(lhs, rhs) => Err(format!("Unsupported operation '^' between {} and {}", lhs.repr(), rhs.repr()))
}
}
}
impl BitAnd for &Value {
type Output = Result<Value, String>;
fn bitand(self, other: Self) -> Self::Output {
use Value::*;
match (self, other) {
(Int(a), Int(b)) => Ok(Int(a & b)),
(Bool(a), Bool(b)) => Ok(Bool(a & b)),
_ => Err(format!("Unsupported operation '&' between {} and {}", self.repr(), other.repr()))
}
}
}
impl BitOr for &Value {
type Output = Result<Value, String>;
fn bitor(self, other: Self) -> Self::Output {
use Value::*;
match (self, other) {
(Int(a), Int(b)) => Ok(Int(a | b)),
(Bool(a), Bool(b)) => Ok(Bool(a | b)),
_ => Err(format!("Unsupported operation '|' between {} and {}", self.repr(), other.repr()))
}
}
}
impl Not for &Value {
type Output = Result<Value, String>;
fn not(self) -> Self::Output {
use Value::*;
match self {
Int(a) => Ok(Int(!a)),
Bool(a) => Ok(Bool(!a)),
_ => Err(format!("Unsupported operation '~' for {}", self.repr())),
}
}
}

View File

@ -1,3 +1,3 @@
while true {
print(input());
println(input());
}

View File

@ -1,11 +1,29 @@
fn factorial(n) {
fn fact_recursive(n) {
if n <= 1 {
return 1;
} else {
return n * factorial(n-1);
}
return n * fact_recursive(n-1);
}
for n: 0..10 {
println(factorial(n));
fn fact_imperative(n) {
if n <= 1 {
return 1;
}
let res = 1;
for i: 1..=n {
res *= i;
}
return res;
}
fn fact_pipeline(n) {
if n <= 1 {
return 1;
}
return 1..=n |// \*;
}
# 10*9*8*7*6*5*4*3*2*1 = 10
println(fact_recursive(10));
println(fact_imperative(10));
println(fact_pipeline(10));

View File

@ -1,6 +1,6 @@
# compute the primorial of n - the product of all primes <= n
fn primorial(n) {
return 2..(n+1) |? is_prime |// fn(x,y) { return x*y; };
return 2..(n+1) |? is_prime |// \*;
}
println(primorial(10)); # 2*3*5*7 = 210