File rc-0+git.1725436050.2b2d211.obscpio of Package rc

07070100000000000081A400000000000000000000000166D8109200000008000000000000000000000000000000000000002700000000rc-0+git.1725436050.2b2d211/.gitignore*.1
/rc
07070100000001000081A400000000000000000000000166D810920000894D000000000000000000000000000000000000002400000000rc-0+git.1725436050.2b2d211/COPYING                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
07070100000002000081A400000000000000000000000166D8109200000242000000000000000000000000000000000000002500000000rc-0+git.1725436050.2b2d211/Makefile.POSIX:
.SUFFIXES:
HARE=hare
HAREFLAGS=
SCDOC=scdoc

BINNAME=rc
DESTDIR=
PREFIX=/usr/local
SHAREDIR=$(PREFIX)/share
MANDIR=$(SHAREDIR)/man

all: rc

rc:
	hare build $(HAREFLAGS) -o $@ cmd/$@/

doc/rc.1: doc/rc.1.scd
	scdoc < $< > $@

docs: doc/rc.1

clean:
	rm -f rc

install: rc docs
	mkdir -p $(DESTDIR)$(PREFIX)/bin
	mkdir -p $(DESTDIR)$(MANDIR)/man1
	install -m755 rc $(DESTDIR)$(PREFIX)/bin/$(BINNAME)
	install -m644 doc/rc.1 $(DESTDIR)$(MANDIR)/man1/rc.1

uninstall:
	rm -f $(DESTDIR)$(PREFIX)/bin/rc

check: rc
	./rc run-tests

.PHONY: all rc clean install uninstall doc
07070100000003000081A400000000000000000000000166D81092000001C7000000000000000000000000000000000000002600000000rc-0+git.1725436050.2b2d211/README.md# rc

*Name subject to change*

rc is an experimental shell for Unix inspired by Plan 9's [rc].

[rc]: https://man.cat-v.org/plan_9/1/rc

## Installation

1. Install an up-to-date [Hare] environment, [madeline], and [scdoc]
2. make
3. make install

To install to /bin (recommended location for shebangs), use `make install
PREFIX=/`.

[Hare]: https://harelang.org
[madeline]: https://git.d2evs.net/~ecs/madeline
[scdoc]: https://git.sr.ht/~sircmpwn/scdoc
07070100000004000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002000000000rc-0+git.1725436050.2b2d211/ast07070100000005000081A400000000000000000000000166D8109200001653000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/ast/command.hause fs;
use io;
use strings;

// A simple command.
export type simple = struct {
	args: []*value,
	redirs: []redir,
};

// A here-document.
export type heredoc = str;

// A file redirect.
export type redir = struct {
	input: (value | heredoc),
	file: io::file,
	oflag: fs::flag,
};

// Frees state associated with a [[simple]] command.
export fn simple_finish(simple: *simple) void = {
	for (let i = 0z; i < len(simple.args); i += 1) {
		value_finish(simple.args[i]);
		free(simple.args[i]);
	};
	free(simple.args);
};

// A compound operation, i.e. |, ||, or &&
export type compound_op = enum {
	PIPE,
	LOR,
	LAND,
};

// A compound command.
export type compound = struct {
	lval: *command,
	rval: *command,
	op: compound_op,
};

// An assignment (e.g. x=y)
export type assign = struct {
	target: str,
	value: *value,
};

// A function definition.
export type fndef = struct {
	name: str,
	args: []str,
	body: *command,
};

export type if_stmt = struct {
	cond: *command,
	body: *command,
	alt: nullable *command,
};

// A for loop; for (name in value) cmd
export type for_loop = struct {
	bind: str,
	values: []*value,
	body: *command,
};

// A while loop; while (cmd) cmd
export type while_loop = struct {
	cmd: *command,
	body: *command,
};

// A switch command; switch (subject) { cases... }.
export type switch_cmd = struct {
	subject: *value,
	cases: []switch_case,
};

// A switch case.
export type switch_case = struct {
	pattern: nullable *value,
	command: *command,
};

// A command to be run in a subshell.
export type subshell = struct {
	command: *command,
};

// Inverts the status of the following command.
export type not = struct {
	command: *command,
};

// A shell command.
export type command = (simple | compound | assign |
	script | fndef | if_stmt | for_loop | while_loop | switch_cmd |
	subshell | not);

// Frees state associated with a [[command]].
export fn command_finish(cmd: *command) void = {
	match (*cmd) {
	case let cmd: simple =>
		simple_finish(&cmd);
	case let cmd: compound =>
		command_finish(cmd.lval);
		command_finish(cmd.rval);
		free(cmd.lval);
		free(cmd.rval);
	case let cmd: assign =>
		free(cmd.target);
		value_finish(cmd.value);
	case let sc: script =>
		script_free(sc);
	case let cmd: fndef =>
		free(cmd.name);
		strings::freeall(cmd.args);
		command_finish(cmd.body);
	case let stmt: if_stmt =>
		match (stmt.alt) {
		case let cmd: *command =>
			command_finish(cmd);
			free(cmd);
		case null =>
			yield;
		};
		command_finish(stmt.cond);
		command_finish(stmt.body);
		free(stmt.cond);
		free(stmt.body);
	case let loop: for_loop =>
		free(loop.bind);
		for (let i = 0z; i < len(loop.values); i += 1) {
			value_finish(loop.values[i]);
			free(loop.values[i]);
		};
		free(loop.values);
		command_finish(loop.body);
	case let loop: while_loop =>
		command_finish(loop.cmd);
		command_finish(loop.body);
	case let sw: switch_cmd =>
		value_finish(sw.subject);
		for (let i = 0z; i < len(sw.cases); i += 1) {
			match (sw.cases[i].pattern) {
			case let val: *value =>
				value_finish(val);
				free(val);
			case null =>
				yield;
			};
			command_finish(sw.cases[i].command);
		};
		free(sw.cases);
	case let sub: subshell =>
		command_finish(sub.command);
		free(sub.command);
	case let n: not =>
		command_finish(n.command);
		free(n.command);
	};
};

// Duplicates a [[command]].
export fn command_dup(cmd: *command) command = {
	match (*cmd) {
	case let cmd: simple =>
		let rd: []redir = alloc([], len(cmd.redirs));
		for (let i = 0z; i < len(cmd.redirs); i += 1) {
			const orig = &cmd.redirs[i];
			const input = match (orig.input) {
			case let val: value =>
				yield value_dup(&val);
			case let doc: heredoc =>
				yield strings::dup(doc): heredoc;
			};
			append(rd, redir {
				input = input,
				file = orig.file,
				oflag = orig.oflag,
			});
		};

		return simple {
			args = values_dup(cmd.args),
			redirs = rd,
		};
	case let cmd: compound =>
		return compound {
			lval = alloc(command_dup(cmd.lval)),
			rval = alloc(command_dup(cmd.rval)),
			op = cmd.op,
		};
	case let cmd: assign =>
		return assign {
			target = strings::dup(cmd.target),
			value = alloc(value_dup(cmd.value)),
		};
	case let cmd: fndef =>
		return fndef {
			name = strings::dup(cmd.name),
			args = strings::dupall(cmd.args),
			body = alloc(command_dup(cmd.body))
		};
	case let sc: script =>
		let new: script = alloc([], len(sc));
		for (let i = 0z; i < len(sc); i += 1) {
			append(new, command_dup(&sc[i]));
		};
		return new;
	case let stmt: if_stmt =>
		return if_stmt {
			cond = alloc(command_dup(stmt.cond)),
			body = alloc(command_dup(stmt.body)),
			alt = match (stmt.alt) {
			case let cmd: *command =>
				yield alloc(command_dup(cmd));
			case null =>
				yield null;
			},
		};
	case let loop: for_loop =>
		return for_loop {
			bind = strings::dup(loop.bind),
			values = values_dup(loop.values),
			body = alloc(command_dup(loop.body)),
		};
	case let loop: while_loop =>
		return while_loop {
			cmd = alloc(command_dup(loop.cmd)),
			body = alloc(command_dup(loop.body)),
		};
	case let sw: switch_cmd =>
		let cases: []switch_case = alloc([], len(sw.cases));
		for (let i = 0z; i < len(sw.cases); i += 1) {
			const c = &sw.cases[i];
			append(cases, switch_case {
				pattern = match (c.pattern) {
				case null =>
					yield null;
				case let val: *value =>
					yield alloc(value_dup(val));
				},
				command = alloc(command_dup(c.command)),
			});
		};
		return switch_cmd {
			subject = alloc(value_dup(sw.subject)),
			cases = cases,
		};
	case let sub: subshell =>
		return subshell {
			command = alloc(command_dup(sub.command)),
		};
	case let n: not =>
		return not {
			command = alloc(command_dup(n.command)),
		};
	};
};
07070100000006000081A400000000000000000000000166D81092000000F7000000000000000000000000000000000000002A00000000rc-0+git.1725436050.2b2d211/ast/script.ha// A list of commands, forming a script.
export type script = []command;

// Frees state associated with a [[script]].
export fn script_free(sc: script) void = {
	for (let i = 0z; i < len(sc); i += 1) {
		command_finish(&sc[i]);
	};
	free(sc);
};
07070100000007000081A400000000000000000000000166D8109200000ABB000000000000000000000000000000000000002900000000rc-0+git.1725436050.2b2d211/ast/value.hause strings;

// A quoted string
export type string = str;

// An argument (unquoted)
export type argument = str;

// A shell value.
export type value = (string | argument | access | subscript | concat | []*value);

// The access type associated with an [[access]]
export type access_type = enum {
	VAR,
	LEN,
	QUOTED,
	SQUOTED,
	INDEX,
	SLICE,
};

// A variable access value, e.g. $hello
export type access = struct {
	atype: access_type,
	target: str,
	index: nullable *value,
	end: nullable *value,
};

// A subscript value, e.g. `{echo hi}.
export type subscript = struct {
	cmds: []command,
	ifs: str,
};

// A concatenation of two values.
export type concat = (*value, *value);

// Frees state associated with a [[value]].
export fn value_finish(val: *value) void = {
	match (*val) {
	case let val: access =>
		free(val.target);
		match (val.index) {
		case null =>
			yield;
		case let val: *value =>
			value_finish(val);
			free(val);
		};
		match (val.end) {
		case null =>
			yield;
		case let val: *value =>
			value_finish(val);
			free(val);
		};
	case let val: string =>
		free(val);
	case let val: argument =>
		free(val);
	case let val: []*value =>
		for (let i = 0z; i < len(val); i += 1) {
			value_finish(val[i]);
		};
		free(val);
	case let val: subscript =>
		for (let i = 0z; i < len(val.cmds); i += 1) {
			command_finish(&val.cmds[i]);
		};
		free(val.cmds);
		free(val.ifs);
	case let val: concat =>
		value_finish(val.0);
		value_finish(val.1);
		free(val.0);
		free(val.1);
	};
};

// Duplicates a [[value]].
export fn value_dup(val: *value) value = {
	match (*val) {
	case let val: access =>
		return access {
			atype = val.atype,
			target = strings::dup(val.target),
			index = match (val.index) {
			case null =>
				yield null;
			case let v: *value =>
				yield alloc(value_dup(v));
			},
			end = match (val.end) {
			case null =>
				yield null;
			case let v: *value =>
				yield alloc(value_dup(v));
			},
		};
	case let val: string =>
		return strings::dup(val): string;
	case let val: argument =>
		 return strings::dup(val): argument;
	case let val: []*value =>
		return values_dup(val);
	case let val: subscript =>
		let cmds: []command = alloc([], len(val.cmds));
		for (let i = 0z; i < len(val.cmds); i += 1) {
			append(cmds, command_dup(&val.cmds[i]));
		};
		return subscript {
			cmds = cmds,
			ifs = strings::dup(val.ifs),
		};
	case let val: concat =>
		const left = alloc(value_dup(val.0));
		const right = alloc(value_dup(val.1));
		return (left, right);
	};
};

// Duplicates a list of [[values]].
export fn values_dup(val: []*value) []*value = {
	let new: []*value = alloc([], len(val));
	for (let i = 0z; i < len(val); i += 1) {
		append(new, alloc(value_dup(val[i])));
	};
	return new;
};
07070100000008000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002000000000rc-0+git.1725436050.2b2d211/cmd07070100000009000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002300000000rc-0+git.1725436050.2b2d211/cmd/rc0707010000000A000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002900000000rc-0+git.1725436050.2b2d211/cmd/rc/+gaia0707010000000B000081A400000000000000000000000166D8109200000549000000000000000000000000000000000000003800000000rc-0+git.1725436050.2b2d211/cmd/rc/+gaia/interactive.hause ast;
use bufio;
use fmt;
use interp;
use io;
use memio;
use os::exec;
use os;
use parse;
use path;
use strings;

fn interactive() void = {
	const in = memio::dynamic();
	const parser = parse::new(&in, "stdin");
	defer parse::finish(&parser);
	const state = interp::new();
	defer interp::finish(&state);
	interp::importenv(&state);

	for (true) {
		// TODO: incomplete parse trees/multi-line input
		io::seek(&in, 0, io::whence::SET)!;
		memio::reset(&in);

		const prompt = match (interp::prompt(&state, false)) {
		case let s: str =>
			yield s;
		case let err: interp::error =>
			fmt::errorln(interp::strerror(err))!;
			yield "% ";
		};
		fmt::print(prompt)!;
		bufio::flush(os::stdout)!;

		match (bufio::read_line(os::stdin)!) {
		case io::EOF =>
			break;
		case let line: []u8 =>
			const line = strings::fromutf8(line)!;
			fmt::fprintln(&in, line)!;
			free(line);
		};

		io::seek(&in, 0, io::whence::SET)!;
		const cmd = match (parse::parse_commands(&parser)) {
		case let cmd: ast::command =>
			yield cmd;
		case io::EOF =>
			continue;
		case let err: parse::error =>
			fmt::errorln("Error:", parse::strerror(err))!;
			continue;
		};
		defer ast::command_finish(&cmd);

		match (interp::execute(&state, &cmd)) {
		case let err: interp::error =>
			fmt::errorln("Error:", interp::strerror(err))!;
		case int =>
			yield;
		};
	};
};
0707010000000C000081A400000000000000000000000166D8109200000A30000000000000000000000000000000000000003200000000rc-0+git.1725436050.2b2d211/cmd/rc/interactive.hause ast;
use dirs;
use fmt;
use interp;
use io;
use made;
use memio;
use os::exec;
use os;
use parse;
use path;
use strings;
use unix::signal;

fn sigint(sig: signal::sig, info: *signal::siginfo, uctx: *opaque) void = {
	void; // no-op (for now?)
};

type prompter = struct {
	made::prompter,
	parser: *parse::parser,
	in: *memio::stream,
	state: *interp::state,
	prompt: str,
};

fn prompt_get(p: *made::prompter, state: *made::state) (str, str) = {
	let p = p: *prompter;
	return (strings::dup(p.prompt), "");
};

fn interactive(state: *interp::state) void = {
	const in = memio::dynamic();
	const parser = parse::new(&in, "stdin");
	defer parse::finish(&parser);

	static let buf = path::buffer { ... };
	path::set(&buf, dirs::data("rc"), "history")!;

	const hist = made::histfile(path::string(&buf))!;
	let p = prompter {
		get = &prompt_get,
		state = state,
		parser = &parser,
		in = &in,
		prompt = "% ",
	};
	const ctx = made::context {
		complete = &made::complete_fs,
		hint = &made::hint_history,
		hist = &hist,
		prompt = &p,
		split = made::split_sh,
		cfg = made::config_default("rc")!,
		...
	};
	defer made::ctx_finish(&ctx)!;

	path::set(&buf, dirs::config("rc"), "rcstart")!;
	match (os::open(path::string(&buf))) {
	case let file: io::file =>
		match (interp::source(state, file, ["rcstart"])) {
		case let err: parse::error =>
			fmt::errorfln("Warning: rcstart: {}",
				parse::strerror(err))!;
		case let err: exec::error =>
			fmt::errorfln("Warning: rcstart: {}",
				exec::strerror(err))!;
		case void =>
			yield;
		};
	case =>
		yield;
	};

	signal::handle(signal::sig::INT, &sigint);

	for (true) {
		// TODO: incomplete parse trees/multi-line input
		io::seek(&in, 0, io::whence::SET)!;
		memio::reset(&in);

		p.prompt = match (interp::prompt(state, false)) {
		case let s: str =>
			yield s;
		case let err: interp::error =>
			fmt::errorln(interp::strerror(err))!;
			yield "% ";
		};

		match (made::line(&ctx)) {
		case io::EOF =>
			break;
		case void =>
			continue;
		case let s: str =>
			defer free(s);
			fmt::fprintln(&in, s)!;
		case let e: made::error =>
			fmt::fatal(made::strerror(e));
		};

		io::seek(&in, 0, io::whence::SET)!;
		const cmd = match (parse::parse_commands(&parser)) {
		case let cmd: ast::command =>
			yield cmd;
		case io::EOF =>
			continue;
		case let err: parse::error =>
			fmt::errorln("Error:", parse::strerror(err))!;
			continue;
		};
		defer ast::command_finish(&cmd);

		match (interp::execute(state, &cmd)) {
		case let err: interp::error =>
			fmt::errorln("Error:", interp::strerror(err))!;
		case int =>
			yield;
		};
	};
};
0707010000000D000081A400000000000000000000000166D8109200000B6A000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/cmd/rc/main.hause ast;
use errors;
use fmt;
use fs;
use getopt;
use interp;
use io;
use memio;
use os;
use os::exec;
use parse;
use path;
use strings;
use unix::tty;

export fn main() void = {
	const cmd = getopt::parse(os::args,
		"run commands",
		('c', "string", "run script from provided string"),
		('e', "exit on error (default for non-interactive shell)"),
		('E', "inverts -e"),
		('p', "merge exit status of pipes"),
		('P', "use the last command of a pipe for status"),
		('x', "print commands before execution"),
		('X', "inverts -x"),
		"[command]", "[args...]");
	defer getopt::finish(&cmd);

	let input: io::handle = os::stdin;
	let infile = "<stdin>";

	const state = interp::new();
	defer interp::finish(&state);
	interp::importenv(&state);

	if (len(cmd.args) != 0) {
		infile = cmd.args[0];
		input = match (interp::resolve(cmd.args[0])) {
		case let file: io::file =>
			yield file;
		case let err: fs::error =>
			fmt::fatalf("Error opening {}: {}",
				cmd.args[0], fs::strerror(err));
		};
		interp::pushctx(&state, interp::context_type::SCRIPT, cmd.args);
	} else {
		interp::pushctx(&state, interp::context_type::SCRIPT, []);
	};

	for (let i = 0z; i < len(cmd.opts); i += 1) {
		const opt = &cmd.opts[i];
		switch (opt.0) {
		case 'c' =>
			const data = strings::toutf8(opt.1);
			const src = memio::fixed(data);
			infile = "<argument>";
			input = &src;
		case 'e' =>
			state.flags |= interp::flag::ERROR;
		case 'E' =>
			state.flags &= ~interp::flag::ERROR;
		case 'p' =>
			state.flags |= interp::flag::PIPEFAIL;
		case 'P' =>
			state.flags &= ~interp::flag::PIPEFAIL;
		case 'x' =>
			state.flags |= interp::flag::DEBUG;
		case 'X' =>
			state.flags &= ~interp::flag::DEBUG;
		case =>
			abort();
		};
	};

	const istty = infile == "<stdin>" && tty::isatty(os::stdin_file);
	if (!istty) {
		// Set default non-interactive flags
		state.flags |= interp::flag::ERROR;
	};

	// Source profile if running as a login shell
	if (strings::hasprefix(os::args[0], "-")) {
		match (os::open("/etc/profile.rc")) {
		case let file: io::file =>
			match (interp::source(&state, file, ["/etc/profile.rc"])) {
			case let err: parse::error =>
				fmt::errorfln("Warning: /etc/profile.rc: {}",
					parse::strerror(err))!;
			case let err: exec::error =>
				fmt::errorfln("Warning: /etc/profile.rc: {}",
					exec::strerror(err))!;
			case void =>
				yield;
			};
		case =>
			yield;
		};
	};

	if (istty) {
		interactive(&state);
		return;
	};

	defer io::close(input)!;
	const parser = parse::new(input, infile);
	defer parse::finish(&parser);

	const sc = match (parse::parse_script(&parser)) {
	case let err: parse::error =>
		fmt::fatal("Error:", parse::strerror(err));
	case let sc: ast::script =>
		yield sc;
	};
	defer ast::script_free(sc);

	match (interp::run(&state, &sc)) {
	case let err: interp::error =>
		fmt::fatal("Error:", interp::strerror(err));
	case let status: int =>
		os::exit(status);
	};
};
0707010000000E000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002000000000rc-0+git.1725436050.2b2d211/doc0707010000000F000081A400000000000000000000000166D8109200000B6F000000000000000000000000000000000000002C00000000rc-0+git.1725436050.2b2d211/doc/grammar.txt# (value) indicates an optional terminal or non-terminal
#
# Not specified in the grammer is comments, which are
#
# '#' /[^\n]*/
#
# This may appear anywhere outside of a quoted string and should be removed by
# the lexer.
#
# Continuations are also not specified, i.e. '\' LF
#
# TODO:
# - foo=bar command
# - rework numeric tokens

script		commands (ALLWS)

commands	(ALLWS) command
		commands (ALLWS) separator command

separator	LF
		';'

command 	compound-command
		assign
		if-command
		for-command
		while-command
		switch-command
		func
		'{' commands '}'
		'@' '{' commands '}'
		WS command (WS)

simple-command	value-list (redirections)

compound-command
		simple-command
		builtin-command
		'!' (WS) compound-command
		compound-command (WS) pipe (WS) compound-command
		compound-command (WS) '&&' (WS) compound-command
		compound-command (WS) '||' (WS) compound-command

builtin-command
		builtin value-list (redirections)

builtin		'cd'
		'break'
		'continue'
		'eval'
		'exit'
		'echo'
		'shift'
		'unset'

assign		word (WS) '=' (WS) value

for-command	'for' (WS) '(' (WS) word (WS) ')' command
		'for' (WS) '(' word (WS) 'in' (WS) value-list ')' command

if-command	'if' (WS) condition command
		if-command 'else' command

while-command	'while' (WS) condition command

switch-command	'switch' (WS) '(' (WS) value (WS) ')' (WS) '{' switch-cases '}'

switch-cases	switch-case
		switch-cases switch-case

switch-case	(WS) 'case' WS value ALLWS command
		(WS) 'default' WS value ALLWS command

condition	'(' command ')'

func		'fn' WS word (params) WS command

params		'(' param-list ')'

param-list	word
		param-list WS word

pipe		'|' (file)

redirections	redirection
		redirections redirection

redirection	'<' (file) (WS) value
		'>' (file) (WS) value
		'>' '>' (file) (WS) value
		'<' '>' (file) (WS) value
		'>' '>' heredoc

heredoc
		(-) word [...] word
		(-) string-literal [...] string-literal

file		'[' (WS) integer (WS) ']'
		'[' (WS) integer (WS) '=' (WS) ']'
		'[' (WS) integer (WS) '=' (WS) integer (WS) ']'

value		literal
		access
		subscript
		pipescript
		'(' (WS) value-list (WS) ')'

value-list	value
		value WS value-list

literal		argument
		string-literal
		literal argument
		literal string-literal

string-literal
		'"' nondquote '"'
		"'" nonsquote "'"

access		'$' varname
		'$' '#' varname
		'$' '"' varname
		'$' varname '(' (WS) access-list (WS) ')'

varname		word
		numeric
		'*'

access-list	index
		'-' (WS) index
		index (WS) '-'
		index (WS) '-' (WS) index

index		numeric
		access

subscript	'`' '{' script '}'
		'`' string-literal '{' script '}'

pipescript	'<' '{' script '}'
		'>' '{' script '}'

word		/[A-Za-z_][A-Za-z0-9_.]*/
argument	/[^\[\](){}<>'"&|!;=$#@`\\ \t\n]+/
nondquote	/[^"\n]+/
nonsquote	/[^'\n]+/
numeric		integer
integer		/[0-9]+/

linefeeds	LF (WS)
		LF (WS) linefeeds

WS	SP
	TS
	WS SP
	WS TS

ALLWS
	SP
	TS
	LF
	WS SP
	WS TS
	WS LF

SP	' '
TS	'\t'
LF	'\n'
07070100000010000081A400000000000000000000000166D8109200002A98000000000000000000000000000000000000002900000000rc-0+git.1725436050.2b2d211/doc/rc.1.scdrc(1)

# NAME

rc - run commands

# SYNOPSIS

*rc* [-c _script_] [_command_] [_args_...]

# DESCRIPTION

*rc* runs the rc shell script at _command_, with the provided _args_. If no
_command_ is provided, commands are read from the standard input. If the
standard input is a terminal, rc starts an interactive shell session.

# OPTIONS

*-c* _script_
	Runs commands from the _script_ argument rather than _command_. If set,
	_command_ and _args_ must be omitted.

# EXTENDED DESCRIPTION

*rc* runs shell scripts using a shell command language with various features for
scripting command execution. Lines beginning with # are comments and are
ignored; # at any unquoted location also causes the remainder of that line to be
ignored.

If the shell is started in interactive mode, the file ~/.config/rc/rcstart is
sourced on startup (or $XDG_CONFIG_HOME/rc/rcstart, if set).

## SIMPLE COMMANDS

Simple commands are formed by forming a list of strings separated by spaces.
Double or single quotes may be used to form arguments with spaces or special
characters. Commands are terminated by a newline, and '\\' may be placed before
a newline to cause a command to continue on the subsequent line.

```
echo hello world
echo "hello world"
echo hello \\
	world	# continuation line
```

Quoted strings which immediately follow each other, without whitespace
characters between, are concatenated. Strings with double quotes are subject to
variable expansion, i.e. variable references using the *$* operators are
expanded by the shell. Unquoted characters are interpreted as arguments if they
do not include any of the following special characters:

	\[ ] ( ) { } < > ' " & | ! ; = $ # @ \` \\

Escape sequences within quoted strings (either single or double quote) are as
follows:

[[ *Sequence*
:[ *Character*
:[ *Name*
|] \\0
:  NUL
:  null
|  \\a
:  BEL
:  bell
|  \\f
:  FF
:  form feed
|  \\n
:  LF
:  line feed
|  \\r
:  CR
:  carriage return
|  \\t
:  HT
:  horizontal tab
|  \\v
:  VT
:  vertical tab
|  \\\\ 
:  \\ 
:  backslash
|  \\'
:  '
:  single quote
|  \\"
:  "
:  double quote

## GLOBBING

Unquoted strings, when used as arguments to a command, are subject to
"globbing". If \* appears in an unquoted string, it will be treated as a
globbing pattern and expanded to a list of matching files.

The globbing pattern syntax is:

- ?: matches any single character
- \*: matches any string, including empty string
- [...]: matches a set of or range of characters
- [!...]: inverse of [...]
- \\: escapes the following character
- all other characters match themselves

## VARIABLES

To define a variable, use the *=* operator and provide a value; to reference it,
use *$*:

```
x="hello world"
echo $x # prints "hello world"
```

*rc* supports two types of variables: strings and lists of strings. A list is
defined by grouping a list of values, separated by spaces, in parenthesis.

```
x=(hello world)
echo $x # echo "hello" "world"
```

The use of a list variable in a command line expands to a series of arguments,
rather than a single argument. Conversely, a string variable always expands to a
single argument. Thus, it is not necessary to quote variables.

On shell start-up, all environment variables are imported into shell variables
and marked as exported.

*VARIABLE OPERATORS*

*$#var*
	Expands to the length of *var*, i.e. the number of items in a list or
	the number of Unicode characters in a string.

	```
	x=hello
	echo $#x # 5
	x=(one two three)
	echo $#x # 3
	```

	The *$#* operator may be used on undefined variables without raising an
	error; it returns 0 in this case.

*$"var*
*$'var*
	If *var* is a list variable, it will be expanded into a single string
	consisting of all of its values, separated by spaces or joined without
	separators, respectively. String variables are expanded normally if accessed
	with *$"*.

	```
	x=(one two three)
	echo $x  # echo "one" "two" "three"
	echo $"x # echo "one two three"
	echo $'x # echo "onetwothree"
	```

*$var(*_n_*)*
	Expands to the N-th value of a list variable, or the N-th UTF-8
	character of a string variable. Indexed from 1.

*$var(*_x_-_y_*)*
	Expands to a sub-list of a list variable, or a substring of a string
	variable including the items or characters from index _x_ (inclusive)
	thru _y_ (exclusive). Either _x_ or _y_ may be omitted to respectively
	select the first or last item as the lower and upper bounds.

*SPECIAL VARIABLES*

The following variables are defined by the shell automatically:

[[ *Name*
:< *Value*
|  $\*
:  List of arguments
|  $0, $1, $2, ...
:  String representing the numbered argument\*
|  $pid
:  Process ID of the shell itself
|  $status
:  Exit status of last command

\* Note that $0 is the command name and $1 is the first argument

## ARGUMENT EXPANSION

When an argument or value appears unquoted, it is subject to argument expansion.
In addition to the operators described by *VARIABLE OPERATORS* above, the
following operators are supported:

\`{ _script..._ } ++
\`"_string_"{ _script..._ }
	The _script_ is run in the current shell. The standard output is
	captured and used as the result of the expansion.

	The second form, with the included "_string_", splits the standard
	output of _script_ into a list using the characters in "string" as
	delimiters.

@{ _script_ } ++
@"_string_"{ _script_ }
	Equivalent to \`{}, but a sub-shell is used.

<{ _script_ } ++
>{ _script_ }
	The _script_ is run in the current shell. In the first form, its
	standard output is captured and written to a named pipe (FIFO). In the
	second form, its standard input is read from a named pipe. In both
	cases, the path to the named pipe is used for the expansion.

## PIPELINES

Any command may be piped into a another with the *|* operator.

_command_ *|* _command_
	The standard output of the first command is connected to the standard
	input of the second command, then both are executed simultaneously.

_command_ *|*[_fd_] _command_ ++
_command_ *|*[_fd_=_fd_] _command_
	The first file descriptor of the first command is connected to the
	second file descriptor of the second command, then both commands are
	executed simultaneously.

	If only one file descriptor is provided, the second command's standard
	input is used.

_command_ *&&* _command_
	The first command is executed. If its $status is zero, the second
	command is executed.

_command_ *||* _command_
	The first command is executed. If its $status is non-zero, the second
	command is executed.

## REDIRECTIONS

_command_ *>* _file_ ++
_command_ *>>* _file_
	_file_ is created (or truncated) and _command_ is executed with its
	standard output connected to this file. If *>>* is used, the file is
	appended to rather than truncated if it already exists.

_command_ *<* _file_
	_file_ is opened for reading and _command_ is executed with its standard
	input connected to this file.

_command_ *>*[_fd_] _file_
	In the first form behaves like *>*, but the specified file descriptor is
	redirected to _file_ instead of the standard output or input.

	May also be used with *>>* and *<*.

_command_ *>*[_fd_=]
	_command_ is executed with the provided file descriptor closed.

## SUB-SCRIPTS

{ _script_ }
	The _script_ is executed in the current shell as a single command. May
	appear as part of a pipeline or include redirects.

## IF STATEMENTS

*if (* _command_ *)* _command_
	The first _command_ is executed. If its status is zero, the second
	command is executed.

*if (* _command_ *)* _command_ *else* _command_
	The first _command_ is executed. If its status is zero, the second
	command is executed. Otherwise, the third command is executed.

## LOOPS

*for (* _arg_ *)* _command_ ++
*for (* _arg_ *in* _arguments_... *)* _command_
	Executes _command_ with each value from the list of _arguments_ set to
	the _arg_ variable one at a time. If _arguments_ is omitted, each
	value from *$\** is used from *$1*.

*while (* _command_ *)* _command_
	The first _command_ is executed. If its status is zero, the second
	_command_ is executed. This is repeated until the first command has a
	non-zero exit status.

## FUNCTIONS

*fn* _name_ _command_ ++
*fn* _name_ *(* _variable list_... *)* _command_
	A function called _name_ is defined using the provided _command_. If a
	command with that _name_ is executed, the provided _command_ will be run
	in the current shell with *$\** set to the list of arguments provided to
	the command.

	If a variable list is provided (separated by spaces), each argument will
	be assigned to a local variable with the given name. Any arguments not
	provided will leave the corresponding variable unset. *$\** is
	unaffected, and may (for instance) be used to access additional
	arguments beyond the list of named arguments.

	```
	fn print_args {
		for (arg) {
			echo $arg
		}
	}
	print_args hello world

	fn write_file(path contents) {
		echo $contents >$path
	}
	write_file example.txt "hello world"
	```

## BUILT-IN COMMANDS

The following commands are built into the shell.

*.* _name_ _args_...
	Sources the script identified by _name_, traversing the path if
	necessary, and executing its contents in the current shell environment.
	If any arguments are provided, $\* is set to those arguments while
	executing the script.

*~* _subject_ _patterns_...
	Tests _subject_ against the provided set of _patterns_, of which there
	must be at least one. If any of the patterns match, *$status* is set to
	zero, otherwise to one.

	The pattern syntax is as follows:

	- ?: matches any single character
	- \*: matches any string, including empty string
	- [...]: matches a set of or range of characters
	- [!...]: inverse of [...]
	- \\: escapes the following character
	- all other characters match themselves

	Globbing is disabled while processing the arguments to a *~* command, so
	you needn't quote patterns explicitly.

*cd* _directory_
	Changes the current working directory to _directory_. If _directory_ is
	omitted, the cwd is set to $HOME.

*break*
	Causes a *for* or *while* loop to terminate immediately.

*continue*
	Causes a *for* or *while* loop to continue immediately to the next
	iteration.

*eval* _script_
	Parses the _script_ argument and evaluates it in the current shell.

*exit* _status_
	Exits with the provided exit status, or zero if none is provided.

*echo* _args_...
	Prints each of its arguments, separated by spaces, and followed by a
	newline.

*read*
	Reads a line from the standard input and prints it to the standard
	output. Exits with status code 0 when successful, 127 upon encountering
	EOF, and a non-zero exit code if an error occured.

	Example usage:

		while (line=`{read}) {
			# ...
		}

*shift* _n_
	Shifts *$\** over by _n_ values, such that "shift 2" will remove $1 and
	$2, then reassign $3 to $1 and so on. If _n_ is omitted, 1 is assumed.

*unset* _names_...
	Unsets the named variables.

# AUTHORS

Maintained by Drew Devault <sir@cmpwn.com>.
07070100000011000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002300000000rc-0+git.1725436050.2b2d211/interp07070100000012000081A400000000000000000000000166D8109200002430000000000000000000000000000000000000002E00000000rc-0+git.1725436050.2b2d211/interp/builtin.hause ast;
use bufio;
use fmt;
use fnmatch;
use fs;
use getopt;
use io;
use os::exec;
use os;
use parse;
use rt;
use sort;
use strconv;
use strings;

type builtin_cmd = fn(state: *state, args: []str) int;

// Keep sorted
const builtins: [_](str, *builtin_cmd) = [
	(".", &builtin_dot),
	("break", &builtin_break),
	("cd", &builtin_cd),
	("continue", &builtin_continue),
	("echo", &builtin_echo),
	("eval", &builtin_eval),
	("exec", &builtin_exec),
	("exit", &builtin_exit),
	("export", &builtin_export),
	("read", &builtin_read),
	("return", &builtin_return),
	("set", &builtin_set),
	("shift", &builtin_shift),
	("unset", &builtin_unset),
	("~", &builtin_tilde),
];

// Looks up a built-in command.
fn builtin(state: *state, args: []str) nullable *builtin_cmd = {
	match (sort::search(builtins, size((str, *builtin_cmd)),
		&args[0], &builtin_cmp)) {
	case let i: size =>
		return builtins[i].1;
	case void =>
		return null;
	};
};

fn builtin_cmp(a: const *opaque, b: const *opaque) int = {
	const a = a: const *str;
	const b = b: const *(str, *builtin_cmd);
	return strings::compare(*a, b.0);
};

fn builtin_dot(state: *state, args: []str) int = {
	args = args[1..];
	if (len(args) == 0) {
		fmt::errorln(".: expected file")!;
		return os::status::FAILURE;
	};

	const file = match (resolve(args[0])) {
	case let err: fs::error =>
		fmt::errorfln(".: open {}: {}", args[0], fs::strerror(err))!;
		return os::status::FAILURE;
	case let file: io::file =>
		yield file;
	};
	defer io::close(file)!;

	match (source(state, file, args)) {
	case let err: parse::error =>
		fmt::errorfln(".: {}", parse::strerror(err))!;
		return os::status::FAILURE;
	case let err: exec::error =>
		fmt::errorfln(".: {}", exec::strerror(err))!;
		return os::status::FAILURE;
	case void =>
		return os::status::SUCCESS;
	};
};

fn builtin_break(state: *state, args: []str) int = {
	if (len(args) != 1) {
		fmt::errorln("break: expected no arguments")!;
		return os::status::FAILURE;
	};

	const ctx = match (getctx(state, context_type::LOOP)) {
	case let ctx: *context =>
		yield ctx;
	case null =>
		fmt::errorln("break: no loop to break from")!;
		return os::status::FAILURE;
	};

	rt::longjmp(&ctx.jmp, loop_exit::BREAK);
};

fn builtin_cd(state: *state, args: []str) int = {
	if (len(args) > 2) {
		fmt::errorln("cd: usage: cd dir")!;
		return os::status::FAILURE;
	};

	const targ = if (len(args) == 1) {
		const home = match (get(state, "HOME")) {
		case let v: *variable =>
			yield value_str(&v.value);
		case null =>
			fmt::errorln("cd: $HOME unset")!;
			return os::status::FAILURE;
		};
		yield home;
	} else {
		yield strings::dup(args[1]);
	};
	if (targ == "-") {
		targ = match (get(state, "OLDPWD")) {
		case null =>
			return os::status::SUCCESS;
		case let var: *variable =>
			yield value_str(&var.value);
		};
	};
	defer free(targ);

	const oldcwd = strings::dup(os::getcwd());
	defer free(oldcwd);
	match (os::chdir(targ)) {
	case let err: fs::error =>
		fmt::errorln("Error:", fs::strerror(err))!;
		return os::status::FAILURE;
	case void =>
		const cwd = strings::dup(os::getcwd());
		defer free(cwd);
		set(state, "PWD", &(cwd: value), true);
		set(state, "OLDPWD", &(oldcwd: value), true);
		return os::status::SUCCESS;
	};
};

fn builtin_continue(state: *state, args: []str) int = {
	if (len(args) != 1) {
		fmt::errorln("continue: expected no arguments")!;
		return os::status::FAILURE;
	};

	const ctx = match (getctx(state, context_type::LOOP)) {
	case let ctx: *context =>
		yield ctx;
	case null =>
		fmt::errorln("break: no loop to break from")!;
		return os::status::FAILURE;
	};

	rt::longjmp(&ctx.jmp, loop_exit::CONTINUE);
};

fn builtin_echo(state: *state, args: []str) int = {
	for (let i = 1z; i < len(args); i += 1) {
		fmt::printf("{}{}", args[i],
			if (i + 1 < len(args)) " " else "")!;
	};
	fmt::println()!;
	return 0;
};

fn builtin_eval(state: *state, args: []str) int = {
	const in = strings::join(" ", args[1..]...);
	defer free(in);

	match (eval(state, in)) {
	case let err: parse::error =>
		fmt::errorln("Error:", parse::strerror(err))!;
		return os::status::FAILURE;
	case let err: error =>
		fmt::errorln("Error:", strerror(err))!;
		return os::status::FAILURE;
	case let st: int =>
		return st;
	};
};

fn builtin_exec(state: *state, args: []str) int = {
	if (len(args) <= 1) {
		fmt::errorln("exec: expected command to execute")!;
		return os::status::FAILURE;
	};

	let argv: []*ast::value = alloc([], len(args) - 1);
	for (let i = 1z; i < len(args); i += 1) {
		append(argv, alloc(args[i]: ast::argument: ast::value));
	};

	const cmd = ast::simple {
		args = argv,
		redirs = [],
	};
	return exec_simple(state, &cmd, false)!;
};

fn builtin_exit(state: *state, args: []str) int = {
	let status: int = os::status::SUCCESS;
	if (len(args) > 2) {
		status = os::status::FAILURE;
	} else if (len(args) > 1) {
		match (strconv::stoi(args[1])) {
		case let i: int =>
			status = i;
		case =>
			status = os::status::FAILURE;
		};
	};
	os::exit(status);
};

fn builtin_export(state: *state, args: []str) int = {
	if (len(args) < 2) {
		fmt::errorln("export: expected variable list")!;
		return os::status::FAILURE;
	};
	// TODO: export x=y
	for (let i = 1z; i < len(args); i += 1) {
		const var = match (get(state, args[i])) {
		case null =>
			fmt::errorfln("export: {}: unset variable", args[i])!;
			return os::status::FAILURE;
		case let var: *variable =>
			yield var;
		};
		// TODO: Prevent locals from being exported
		var.exported = true;
	};
	return os::status::SUCCESS;
};

fn builtin_read(state: *state, args: []str) int = {
	if (len(args) > 1) {
		fmt::errorln("read: expected no arguments")!;
		return os::status::FAILURE;
	};

	match (bufio::read_line(os::stdin_file)) {
	case let err: io::error =>
		fmt::errorfln("read: error: {}", io::strerror(err))!;
		return os::status::FAILURE;
	case io::EOF =>
		return 127;
	case let line: []u8 =>
		match (strings::fromutf8(line)) {
		case let s: str =>
			fmt::println(s)!;
		case =>
			fmt::errorfln("read: invalid UTF-8 data")!;
			return os::status::FAILURE;
		};
	};

	return os::status::SUCCESS;
};

fn builtin_return(state: *state, args: []str) int = {
	if (len(args) > 2) {
		fmt::errorln("return: expected return value")!;
		return os::status::FAILURE;
	};

	let st = 0;
	if (len(args) == 2) {
		match (strconv::stoi(args[1])) {
		case let i: int =>
			st = i;
		case =>
			fmt::errorln("return: expected return value")!;
			return os::status::FAILURE;
		};
	};

	const ctx = match (getctx(state, context_type::FUNC)) {
	case let ctx: *context =>
		yield ctx;
	case null =>
		fmt::errorln("return: no function to return from")!;
		return os::status::FAILURE;
	};

	rt::longjmp(&ctx.jmp, st << 1 | 1);
};

fn builtin_set(state: *state, args: []str) int = {
	static const help: [_]getopt::help = [
		('e', "exit on error"),
		('E', "inverts -e"),
		('p', "merge exit status of pipes"),
		('P', "use the last command of a pipe for status"),
		('x', "print commands before execution"),
		('X', "inverts -x"),
	];
	const cmd = match (getopt::tryparse(args, help...)) {
	case let cmd: getopt::command =>
		yield cmd;
	case getopt::error =>
		return os::status::FAILURE;
	};
	defer getopt::finish(&cmd);

	if (len(cmd.args) != 0) {
		getopt::printusage(os::stderr, args[0], help)!;
		return os::status::FAILURE;
	};

	if (len(cmd.opts) == 0) {
		fmt::printf("set")!;
		if (state.flags != 0) {
			fmt::printf(" -")!;
		};
		if (state.flags & flag::ERROR != 0) {
			fmt::printf("e")!;
		};
		if (state.flags & flag::PIPEFAIL != 0) {
			fmt::printf("p")!;
		};
		if (state.flags & flag::DEBUG != 0) {
			fmt::printf("x")!;
		};
		fmt::println()!;
	};

	for (let i = 0z; i < len(cmd.opts); i += 1) {
		const opt = cmd.opts[i];
		switch (opt.0) {
		case 'e' =>
			state.flags |= flag::ERROR;
		case 'E' =>
			state.flags &= ~flag::ERROR;
		case 'p' =>
			state.flags |= flag::PIPEFAIL;
		case 'P' =>
			state.flags &= ~flag::PIPEFAIL;
		case 'x' =>
			state.flags |= flag::DEBUG;
		case 'X' =>
			state.flags &= ~flag::DEBUG;
		case => abort();
		};
	};

	return os::status::SUCCESS;
};

fn builtin_shift(state: *state, args: []str) int = {
	let n = 1u;
	if (len(args) == 2) {
		match (strconv::stou(args[1])) {
		case let u: uint =>
			n = u;
		case =>
			fmt::errorln("shift: expected number")!;
			return os::status::FAILURE;
		};
	} else if (len(args) > 2) {
		fmt::errorln("shift: expected number")!;
		return os::status::FAILURE;
	};

	let ctx = getctx(state,
		context_type::FUNC,
		context_type::SCRIPT) as *context;
	if (n > len(ctx.args)) {
		n = len(ctx.args): uint;
	};

	const args = strings::dupall(ctx.args[n..]);
	strings::freeall(ctx.args);
	ctx.args = args;

	clearargs(state);
	setargs(state, args);
	return os::status::SUCCESS;
};

fn builtin_unset(state: *state, args: []str) int = {
	for (let i = 1z; i < len(args); i += 1) {
		unset(state, args[i]);
	};
	return os::status::SUCCESS;
};

fn builtin_tilde(state: *state, args: []str) int = {
	if (len(args) < 2) {
		fmt::errorln("~: usage: ~ subject pattern...")!;
		return os::status::FAILURE;
	};

	let status = os::status::FAILURE;
	const subject = args[1];
	for (let i = 2z; i < len(args); i += 1) {
		if (fnmatch::fnmatch(args[i], subject)) {
			status = os::status::SUCCESS;
		};
	};
	return status;
};
07070100000013000081A400000000000000000000000166D81092000006F3000000000000000000000000000000000000002F00000000rc-0+git.1725436050.2b2d211/interp/compound.hause ast;
use io;
use os;
use os::exec;
use rt;

fn exec_compound(state: *state, cmd: *ast::compound) (int | error) = {
	switch (cmd.op) {
	case ast::compound_op::LAND, ast::compound_op::LOR =>
		return exec_binop(state, cmd);
	case ast::compound_op::PIPE =>
		return exec_pipe(state, cmd);
	};
};

fn exec_binop(state: *state, cmd: *ast::compound) (int | error) = {
	const lret = execute(state, cmd.lval)?;
	switch (cmd.op) {
	case ast::compound_op::LAND =>
		if (lret == os::status::SUCCESS) {
			return execute(state, cmd.rval);
		};
		return lret;
	case ast::compound_op::LOR =>
		if (lret != os::status::SUCCESS) {
			return execute(state, cmd.rval);
		};
		return lret;
	case =>
		abort();
	};
};

fn exec_pipe(state: *state, cmd: *ast::compound) (int | error) = {
	const (rd, wr) = exec::pipe();

	const lval = match (exec::fork()) {
	case void =>
		exec_child(state, cmd.lval, rd, wr, os::stdout_file);
	case let child: exec::process =>
		yield child;
	};

	const rval = match (exec::fork()) {
	case void =>
		exec_child(state, cmd.rval, wr, rd, os::stdin_file);
	case let child: exec::process =>
		yield child;
	};

	io::close(rd)!;
	io::close(wr)!;

	const lst = exec::wait(&lval)?;
	const lst = waitstatus(&lst);

	const rst = exec::wait(&rval)?;
	const rst = waitstatus(&rst);

	if (state.flags & flag::PIPEFAIL != 0) {
		if (lst != os::status::SUCCESS) {
			return lst;
		};
		return rst;
	} else {
		return rst;
	};
};

fn exec_child(
	state: *state,
	cmd: *ast::command,
	close: io::file,
	dup_old: io::file,
	dup_new: io::file,
) never = {
	io::dup2(dup_old, dup_new, io::dupflag::NOCLOEXEC)!;
	io::close(dup_old)!;
	io::close(close)!;

	match (execute(state, cmd)) {
	case let r: int =>
		os::exit(r);
	case exec::error =>
		os::exit(os::status::FAILURE);
	};
};
07070100000014000081A400000000000000000000000166D810920000047D000000000000000000000000000000000000002C00000000rc-0+git.1725436050.2b2d211/interp/error.hause fmt;
use fs;
use os::exec;

// Undefined variable, set to the name of the variable in question (borrowed
// from the AST).
export type undef = !struct {
	name: str,
};

// Mismatched lengths in concatenation.
export type lenmismatch = !void;

// Bounds exceeded in index operation.
export type bounds = !void;

// Value is not a number.
export type invalnum = !void;

// Invalid type.
export type invaltype = !void;

// An interpreter error.
export type error = !(
	exec::error |
	fs::error |
	undef |
	lenmismatch |
	bounds |
	invalnum |
	invaltype |
);

// Returns a human-friendly representation of an error.
export fn strerror(err: error) const str = {
	static let buf: [256]u8 = [0...];
	match (err) {
	case let err: exec::error =>
		return exec::strerror(err);
	case let err: fs::error =>
		return fs::strerror(err);
	case let err: undef =>
		return fmt::bsprintf(buf, "{}: undefined variable", err.name);
	case lenmismatch =>
		return "Mismatched lengths in concatenation operation";
	case bounds =>
		return "List bounds exceeded";
	case invalnum =>
		return "Value is not a number";
	case invaltype =>
		return "Incorrect type";
	};
};
07070100000015000081A400000000000000000000000166D81092000001B5000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/interp/eval.hause ast;
use memio;
use parse;
use strings;

// Evaluates a script from a string.
export fn eval(state: *state, in: str) (int | parse::error | error) = {
	const in = memio::fixed(strings::toutf8(in));
	const p = parse::new(&in, "eval");
	defer parse::finish(&p);

	const sc = parse::parse_script(&p)?;
	defer ast::script_free(sc);

	let st = 0;
	for (let i = 0z; i < len(sc); i += 1) {
		st = execute(state, &sc[i])?;
	};
	return st;
};
07070100000016000081A400000000000000000000000166D81092000021BA000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/interp/exec.hause ast;
use fmt;
use fnmatch;
use fs;
use io;
use os;
use os::exec;
use rt;
use strconv;
use strings;

// Executes a command with the interpreter.
export fn execute(state: *state, cmd: *ast::command) (int | error) = {
	match (execute_internal(state, cmd)) {
	case let st: int =>
		return st;
	case let err: error =>
		set(state, "status", &("1": value), false);
		return err;
	};
};

fn execute_internal(state: *state, cmd: *ast::command) (int | error) = {
	const status = match (*cmd) {
	case let cmd: ast::simple =>
		yield exec_simple(state, &cmd, true)?;
	case let cmd: ast::compound =>
		yield exec_compound(state, &cmd)?;
	case let cmd: ast::assign =>
		// Does not set status code
		return exec_assign(state, &cmd)?;
	case let sc: ast::script =>
		let st = 0;
		for (let i = 0z; i < len(sc); i += 1) {
			st = execute(state, &sc[i])?;
			if (st != os::status::SUCCESS && state.flags & flag::ERROR != 0) {
				return st;
			};
		};
		yield st;
	case let func: ast::fndef =>
		set_func(state, &func);
		yield 0;
	case let cond: ast::if_stmt =>
		yield exec_if_stmt(state, &cond)?;
	case let loop: ast::for_loop =>
		yield exec_for_loop(state, &loop)?;
	case let loop: ast::while_loop =>
		yield exec_while_loop(state, &loop)?;
	case let sw: ast::switch_cmd =>
		yield exec_switch_cmd(state, &sw)?;
	case let sub: ast::subshell =>
		yield exec_subshell(state, &sub)?;
	case let n: ast::not =>
		yield exec_not(state, &n)?;
	};
	set(state, "status", &(strconv::itos(status): value), false);
	return status;
};

fn exec_simple(state: *state, cmd: *ast::simple, fork: bool) (int | error) = {
	let args: []str = [];

	let glob = true;
	for (let i = 0z; i < len(cmd.args); i += 1) {
		// Hack: don't expand ~
		if (i == 0) match (*cmd.args[i]) {
		case let s: ast::string =>
			if (s == "~") {
				append(args, "~");
				continue;
			};
		case let s: ast::argument =>
			if (s == "~") {
				append(args, "~");
				continue;
			};
		case => yield;
		};

		const val = expand(state, cmd.args[i], glob && i != 0)?;
		append(args, value_list(&val)...);
		glob = args[0] != "~";
	};
	if (args[0] == "") {
		return os::status::SUCCESS;
	};

	if (state.flags & flag::DEBUG != 0) {
		fmt::errorf("+ ")!;
		for (let i = 0z; i < len(args); i += 1) {
			fmt::errorf("{} ", args[i])!;
		};
		fmt::errorln()!;
	};

	const b = builtin(state, args);
	const f = get_func(state, args[0]);

	let savefd = false;
	if (b != null) {
		savefd = true;
	};
	if (f != null) {
		savefd = true;
	};

	let saved: []io::file = [];
	if (savefd) {
		if (!fork) {
			fmt::errorfln("Error: cannot exec built-in command {}", args[0])!;
			return os::status::FAILURE;
		};

		// Save file descriptors to restore later
		saved = alloc([], len(cmd.redirs));
		for (let i = 0z; i < len(cmd.redirs); i += 1) {
			const backup = io::dup(cmd.redirs[i].file,
				io::dupflag::NOCLOEXEC)!;
			append(saved, backup);
		};
	} else if (fork) {
		match (exec::fork()?) {
		case void =>
			yield;
		case let child: exec::process =>
			const st = exec::wait(&child)?;
			strings::freeall(args);
			return waitstatus(&st);
		};
	};

	apply_redirs(state, cmd.redirs)?;

	match (f) {
	case let fun: *func =>
		defer restore_fd(cmd.redirs, saved);
		return exec_func(state, fun, args);
	case null =>
		yield;
	};

	match (b) {
	case let builtin: *builtin_cmd =>
		const status = builtin(state, args);
		restore_fd(cmd.redirs, saved);
		return status;
	case null =>
		yield;
	};

	const cmd = match (exec::cmd(args[0], args[1..]...)) {
	case let cmd: exec::command =>
		yield cmd;
	case let err: exec::error =>
		fmt::errorfln("{}: {}", args[0], exec::strerror(err))!;
		os::exit(os::status::FAILURE);
	};
	exec::clearenv(&cmd);
	exportenv(state, &cmd);
	exec::exec(&cmd);
};

fn exec_func(
	state: *state,
	fun: *func,
	args: []str,
) (int | error) = {
	let ctx = pushctx(state, context_type::FUNC, args);
	defer popctx(state);

	let st = rt::setjmp(&ctx.jmp);
	if (st != 0) {
		return st >> 1;
	};

	for (let i = 1z; i - 1 < len(fun.args) && i < len(args); i += 1) {
		const name = fun.args[i - 1];
		set_local(state, name, &(args[i]: value));
	};

	return execute(state, &fun.body);
};

fn apply_redirs(state: *state, redirs: []ast::redir) (void | error) = {
	for (let i = 0z; i < len(redirs); i += 1) {
		const redir = &redirs[i];

		const val = match (redir.input) {
		case let doc: ast::heredoc =>
			// heredoc
			const (rd, wr) = exec::pipe();
			match (exec::fork()!) {
			case let proc: exec::process =>
				io::dup2(rd, redir.file, io::dupflag::NOCLOEXEC)!;
				io::close(rd)!;
				io::close(wr)!;
				continue;
			case void =>
				yield;
			};
			io::close(rd)!;
			io::writeall(wr, strings::toutf8(doc))!;
			os::exit(os::status::SUCCESS);
		case let val: ast::value =>
			yield expand(state, &val, true)?;
		};
		defer value_finish(&val);

		const path = value_str(&val);
		defer free(path);

		let file: io::file = 0;
		match (os::create(path, 0o644, redir.oflag)) {
		case let err: fs::error =>
			fmt::errorfln("{}: {}", path, fs::strerror(err))!;
			os::exit(os::status::FAILURE);
		case let f: io::file =>
			file = f;
		};

		io::dup2(file, redir.file, io::dupflag::NOCLOEXEC)!;
		io::close(file)!;
	};
};

fn restore_fd(redirs: []ast::redir, saved: []io::file) void = {
	for (let i = 0z; i < len(redirs); i += 1) {
		const rd = &redirs[i];
		const file = saved[i];
		io::dup2(file, rd.file, io::dupflag::NOCLOEXEC)!;
		io::close(file)!;
	};
	free(saved);
};

fn exec_assign(state: *state, cmd: *ast::assign) (int | error) = {
	const val = expand(state, cmd.value, true)?;
	defer value_finish(&val);
	set(state, cmd.target, &val, false);

	match (get(state, "status")) {
	case let var: *variable =>
		return value_int(&var.value)?;
	case null =>
		return os::status::SUCCESS;
	};
};

fn exec_if_stmt(state: *state, cmd: *ast::if_stmt) (int | error) = {
	const cond = execute(state, cmd.cond)?;
	if (cond == os::status::SUCCESS) {
		return execute(state, cmd.body)?;
	} else if (cmd.alt != null) {
		const alt = cmd.alt as *ast::command;
		return execute(state, alt)?;
	};
	return os::status::SUCCESS;
};

fn exec_for_loop(state: *state, cmd: *ast::for_loop) (int | error) = {
	let i = 0z;
	let iter: []str = [];
	defer strings::freeall(iter);

	if (len(cmd.values) == 0) {
		const args = get(state, "*") as *variable;
		iter = value_list(&args.value);
		i = 1z;
	} else {
		let args: []str = [];

		for (let i = 0z; i < len(cmd.values); i += 1) {
			const item = expand(state, cmd.values[i], true)?;
			append(args, value_list(&item)...);
		};

		iter = args;
	};

	let ctx = pushctx(state, context_type::LOOP, state.ctx[0].args);
	defer popctx(state);

	let st = 0;
	for (i < len(iter); i += 1) {
		set(state, cmd.bind, &(iter[i]: value), false);

		let r = rt::setjmp(&ctx.jmp);
		if (r != 0) {
			switch (r) {
			case loop_exit::CONTINUE =>
				continue;
			case loop_exit::BREAK =>
				break;
			case => abort();
			};
		};

		st = execute(state, cmd.body)?;
	};
	unset(state, cmd.bind);

	return st;
};

fn exec_while_loop(state: *state, cmd: *ast::while_loop) (int | error) = {
	let ctx = pushctx(state, context_type::LOOP, []);
	defer popctx(state);

	let st = 0;
	for (true) {
		const ret = execute(state, cmd.cmd)?;
		if (ret != 0) {
			break;
		};

		let r = rt::setjmp(&ctx.jmp);
		if (r != 0) {
			switch (r) {
			case loop_exit::CONTINUE =>
				continue;
			case loop_exit::BREAK =>
				break;
			case => abort();
			};
		};

		st = execute(state, cmd.body)?;
	};

	return st;
};

fn exec_switch_cmd(state: *state, sw: *ast::switch_cmd) (int | error) = {
	const subject = expand(state, sw.subject, true)?;
	const subject = match (subject) {
	case let s: str =>
		yield s;
	case []str =>
		return invaltype;
	};

	for (let i = 0z; i < len(sw.cases); i += 1) {
		const c = &sw.cases[i];
		const pat = match (c.pattern) {
		case null =>
			return execute(state, c.command)?;
		case let v: *ast::value =>
			yield v;
		};
		const pat = expand(state, pat, false)?;
		const pat = match (pat) {
		case let s: str =>
			yield s;
		case []str =>
			return invaltype;
		};
		if (fnmatch::fnmatch(pat, subject)) {
			return execute(state, c.command)?;
		};
	};

	return os::status::SUCCESS;
};

fn exec_subshell(state: *state, sw: *ast::subshell) (int | error) = {
	match (exec::fork()?) {
	case let child: exec::process =>
		const st = exec::wait(&child)?;
		return waitstatus(&st);
	case void =>
		yield;
	};

	os::exit(execute(state, sw.command)?);
};

fn exec_not(state: *state, n: *ast::not) (int | error) = {
	const st = execute(state, n.command)?;
	if (st == os::status::SUCCESS) {
		return os::status::FAILURE;
	} else {
		return os::status::SUCCESS;
	};
};
07070100000017000081A400000000000000000000000166D81092000002A2000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/interp/path.hause errors;
use fs;
use io;
use os;
use path;
use strings;

// Resolves a command within the path and opens it as a file.
export fn resolve(cmd: str) (io::file | fs::error) = {
	if (strings::contains(cmd, '/')) {
		return os::open(cmd);
	};

	const path = match (os::getenv("PATH")) {
	case let s: str =>
		yield s;
	case void =>
		return errors::noentry;
	};

	let buf = path::init()!;
	let tok = strings::tokenize(path, ":");
	for (const item => strings::next_token(&tok)) {
		path::set(&buf, item, cmd)!;
		match (os::open(path::string(&buf))) {
		case fs::error =>
			continue;
		case let fd: io::file =>
			return fd;
		};
	};

	// Try ./cmd
	return os::open(cmd);

};
07070100000018000081A400000000000000000000000166D8109200000592000000000000000000000000000000000000002D00000000rc-0+git.1725436050.2b2d211/interp/prompt.hause ast;
use memio;
use parse;
use strings;

// Returns the shell prompt string. The return value must be freed by the
// caller.
export fn prompt(state: *state, incomplete: bool) (str | error) = {
	// Preserve $status
	const status = get(state, "status");
	const status: nullable *value = match (status) {
	case null =>
		yield null;
	case let var: *variable =>
		yield alloc(value_dup(&var.value));
	};
	defer match (status) {
	case null =>
		yield;
	case let val: *value =>
		set(state, "status", val, false);
		value_finish(val);
	};

	// TODO: prompt can be a list of length 2 to set PS2
	const prompt = match (get(state, "prompt")) {
	case null =>
		yield strings::dup("% ");
	case let v: *variable =>
		yield value_str(&v.value);
	};

	const data = memio::fixed(strings::toutf8(prompt));
	const par = parse::new(&data, "$prompt");
	defer parse::finish(&par);

	const val = match (parse::parse_value_list(&par, false)) {
	case let val: []*ast::value =>
		yield val;
	case =>
		return prompt;
	};

	let vals: value = [];
	defer value_finish(&vals);
	for (let i = 0z; i < len(val); i += 1) {
		const expanded = expand(state, val[i], true)?;
		defer value_finish(&expanded);

		value_append(&vals, expanded);

		ast::value_finish(val[i]);
		free(val[i]);
	};

	// XXX: HACK
	let p = value_str(&vals);
	if (strings::hassuffix(prompt, " ")) {
		const temp = strings::concat(p, " ");
		free(p);
		p = temp;
	};

	return p;
};
07070100000019000081A400000000000000000000000166D8109200002076000000000000000000000000000000000000002C00000000rc-0+git.1725436050.2b2d211/interp/state.hause ast;
use io;
use os::exec;
use os;
use parse;
use rt;
use sort;
use strconv;
use strings;
use unix::passwd;
use unix;

// Interpreter flags
export type flag = enum uint {
	ERROR = 1 << 0,
	DEBUG = 1 << 1,
	PIPEFAIL = 1 << 2,
};

export type state = struct {
	// Interpreter flags
	flags: flag,
	// Stack of argument vectors
	ctx: []*context,
	// sorted
	vars: []variable,
	// sorted
	funcs: []func,
};

export type context_type = enum {
	SCRIPT,
	FUNC,
	LOOP,
};

export type loop_exit = enum {
	BREAK = 1,
	CONTINUE = 2,
};

export type context = struct {
	// Context type
	ctype: context_type,
	// Long jump
	jmp: rt::jmpbuf,
	// Arguments
	args: []str,
	// sorted
	locals: []variable,
};

// A variable binding.
export type variable = struct {
	name: str,
	value: value,
	exported: bool,
};

// A shell function.
export type func = struct {
	name: str,
	args: []str,
	body: ast::command,
};

// Initializes a new interpreter.
export fn new() state = {
	return state {
		flags = flag::PIPEFAIL,
		...
	};
};

// Frees state associated with an interpreter's [[state]].
export fn finish(interp: *state) void = {
	for (let i = 0z; i < len(interp.vars); i += 1) {
		variable_finish(&interp.vars[i]);
	};
	for (let i = 0z; i < len(interp.funcs); i += 1) {
		const func = &interp.funcs[i];
		ast::command_finish(&func.body);
		free(func.name);
	};
	free(interp.vars);
};

// Imports environment variables into the interpreter state.
export fn importenv(state: *state) void = {
	const envs = os::getenvs();
	for (let i = 0z; i < len(envs); i += 1) {
		const (key, val) = strings::cut(envs[i], "=");
		const key = strings::dup(key);
		const val: value = strings::dup(val);
		append(state.vars, variable {
			name = key,
			value = val,
			exported = true,
		});
	};

	const user = getuser();
	append(state.vars, variable {
		name = strings::dup("HOME"),
		value = strings::dup(user.homedir),
		exported = true,
	});

	sort::sort(state.vars, size(variable), &varcmp);

	const pid: value = strconv::itos(getpid());
	set(state, "pid", &pid, false);
};

// Exports the shell's environment to the given [[os::exec::command]].
export fn exportenv(state: *state, cmd: *exec::command) void = {
	for (let i = 0z; i < len(state.vars); i += 1) {
		const var = &state.vars[i];
		if (!var.exported) {
			continue;
		};
		const val = value_str(&var.value);
		defer free(val);
		exec::setenv(cmd, var.name, val)!;
	};
};

// Runs a script, returning its exit code.
export fn run(state: *state, sc: *ast::script) (int | error) = {
	let last = 0;
	for (let i = 0z; i < len(sc); i += 1) {
		last = execute(state, &sc[i])?;
		if (last != os::status::SUCCESS && state.flags & flag::ERROR != 0) {
			return last;
		};
	};
	return last;
};

// Sources a script in the current shell environment.
export fn source(
	state: *state,
	file: io::handle,
	args: []str,
) (void | parse::error | error) = {
	assert(len(args) > 0);
	if (len(args) > 1) {
		pushctx(state, context_type::SCRIPT, args);
	};
	defer if (len(args) > 1) {
		popctx(state);
	};

	const parse = parse::new(file, args[0]);
	defer parse::finish(&parse);
	const sc = parse::parse_script(&parse)?;
	defer ast::script_free(sc);
	run(state, &sc)?;
};

// Pushes an argument vector to the stack.
export fn pushctx(state: *state, ctype: context_type, args: []str) *context = {
	let ctx = alloc(context {
		ctype = ctype,
		args = strings::dupall(args),
		...
	});
	insert(state.ctx[0], ctx);
	if (ctype != context_type::LOOP) {
		clearargs(state);
		setargs(state, args);
	};
	return ctx;
};

// Pops an argument vector from the stack.
export fn popctx(state: *state) void = {
	const old = state.ctx[0];
	defer free(old);
	delete(state.ctx[0]);

	switch (old.ctype) {
	case context_type::FUNC, context_type::SCRIPT =>
		// Restore old args
		match (getctx(state,
			context_type::FUNC,
			context_type::SCRIPT)) {
			case let ctx: *context =>
				clearargs(state);
				setargs(state, ctx.args);
			case null =>
				void;
		};
	case => yield;
	};

	assert(len(state.ctx) != 0);
};

// Sets the argument vector without modifying the stack.
export fn setargs(state: *state, args: []str) void = {
	let val: []str = [];
	for (let i = 0z; i < len(args); i += 1) {
		const name = strconv::ztos(i);
		set(state, name, &(args[i]: value), false);
		append(val, args[i]);
	};
	set(state, "*", &(val: value), false);
};

// Returns the top-most context which matches the required type.
fn getctx(state: *state, ctype: context_type...) nullable *context = {
	for (let i = 0z; i < len(state.ctx); i += 1) {
		for (let j = 0z; j < len(ctype); j += 1) {
			if (state.ctx[i].ctype == ctype[j]) {
				return state.ctx[i];
			};
		};
	};
	return null;
};

fn clearargs(state: *state) void = {
	if (len(state.ctx) == 0) {
		return;
	};

	const ctx = state.ctx[0];
	for (let i = 0z; i < len(ctx.args); i += 1) {
		const name = strconv::ztos(i);
		unset(state, name);
	};
	unset(state, "*");
};

// Frees state associated with a [[variable]].
export fn variable_finish(var: *variable) void = {
	free(var.name);
	value_finish(&var.value);
};

// Gets a variable from the interpreter.
export fn get(interp: *state, name: str) nullable *variable = {
	const key = variable {
		name = name,
		value = "",
		...
	};

	// TODO: Put globals into a top-level context
	for (let i = 0z; i < len(interp.ctx); i += 1) {
		const ctx = &interp.ctx[i];
		match (sort::search(ctx.locals, size(variable), &key, &varcmp)) {
		case let i: size =>
			return &ctx.locals[i];
		case void =>
			yield;
		};
	};

	match (sort::search(interp.vars, size(variable), &key, &varcmp)) {
	case let i: size =>
		return &interp.vars[i];
	case void =>
		return null;
	};
};

fn set_internal(
	list: *[]variable,
	name: str,
	val: const *value,
	exported: bool,
) void = {
	const var = variable {
		name = name,
		value = value_dup(val),
		exported = exported,
	};
	const i = sort::lbisect(*list, size(variable), &var, &varcmp);
	if (i < len(list) && list[i].name == name) {
		value_finish(&list[i].value);
		list[i].value = var.value;
	} else {
		var.name = strings::dup(var.name);
		insert(list[i], var);
	};
};

// Sets a variable in the interpreter state.
export fn set(
	interp: *state,
	name: str,
	val: const *value,
	exported: bool,
) void = {
	set_internal(&interp.vars, name, val, exported);
};

// Sets a local variable in the interpreter's current context.
export fn set_local(
	interp: *state,
	name: str,
	val: const *value,
) void = {
	const ctx = &interp.ctx[0];
	set_internal(&ctx.locals, name, val, false);
};

// Unsets a variable in the interpeter. No-op if there is no such variable.
export fn unset(interp: *state, name: str) void = {
	const key = variable {
		name = name,
		value = "",
		...
	};
	match (sort::search(interp.vars, size(variable), &key, &varcmp)) {
	case let i: size =>
		delete(interp.vars[i]);
	case void =>
		yield;
	};
};

@test fn variables() void = {
	let state = new();
	defer finish(&state);

	let val: value = "bar";
	set(&state, "foo", &val, false);
	match (get(&state, "foo")) {
	case let var: *variable =>
		assert(var.value as str == "bar");
	case null =>
		abort();
	};
};

fn varcmp(a: const *opaque, b: const *opaque) int = {
	const a = a: const *variable;
	const b = b: const *variable;
	return strings::compare(a.name, b.name);
};

// Gets a function definition from the interpreter.
export fn get_func(interp: *state, name: str) nullable *func = {
	const key = func {
		name = name,
		args = [],
		body = ast::simple { ... },
	};
	match (sort::search(interp.funcs, size(func), &key, &fncmp)) {
	case let i: size =>
		return &interp.funcs[i];
	case void =>
		return null;
	};
};

// Sets a function definition in the interpreter.
export fn set_func(interp: *state, fndef: *ast::fndef) void = {
	const fun = func {
		name = fndef.name,
		args = strings::dupall(fndef.args),
		body = ast::command_dup(fndef.body),
	};
	const i = sort::lbisect(interp.funcs, size(func), &fun, &fncmp);
	if (i < len(interp.funcs) && interp.funcs[i].name == fndef.name) {
		let slot = &interp.funcs[i];
		ast::command_finish(&slot.body);
		slot.body = fun.body;
	} else {
		fun.name = strings::dup(fun.name);
		insert(interp.funcs[i], fun);
	};
};

fn fncmp(a: const *opaque, b: const *opaque) int = {
	const a = a: const *func;
	const b = b: const *func;
	return strings::compare(a.name, b.name);
};
0707010000001A000081A400000000000000000000000166D8109200000C5D000000000000000000000000000000000000002C00000000rc-0+git.1725436050.2b2d211/interp/token.ha// SPDX-License-Identifier: MPL-2.0
// (c) Hare authors <https://harelang.org>
// Replacement for bytes/strings::tokenize which accepts multiple delimiters

use bytes;
use strings;
use types;

type btokenizer = struct {
	s: []u8, // string being tokenized
	d: [][]u8, // delimiter
	p: i64, // p < 0 for reverse tokenizers, 0 <= p for forward ones.
};

fn btokenize(s: []u8, delim: []u8...) btokenizer = {
	assert(len(delim) > 0, "bytes::tokenize called with empty slice");
	for (let i = 0z; i < len(delim); i += 1) {
		assert(len(delim[i]) > 0,
			"bytes::tokenize called with empty slice");
	};

	if (len(s) == 0) {
		delim = [];
	};

	return btokenizer {
		s = s,
		d = alloc(delim...),
		p = types::I64_MAX, // I64_MAX means we haven't peeked the next token yet.
	};
};

fn btok_finish(s: *btokenizer) void = {
	free(s.d);
};

fn bnext_token(s: *btokenizer) ([]u8 | void) = {
	let d: []u8 = [];
	const b = match (bpeek_token(s, &d)) {
	case let b: []u8 =>
		yield b;
	case => return;
	};

	if (s.p == len(s.s): i64) {
		s.d = s.d[..0];
		s.s = s.s[..0];
	} else {
		s.s = s.s[s.p: size + len(d)..];
	};
	s.p = types::I64_MAX;

	return b;
};

fn bpeek_token(s: *btokenizer, dout: *[]u8) ([]u8 | void) = {
	if (len(s.d) == 0) {
		return;
	};

	if (s.p == types::I64_MAX) {
		let i = types::I64_MAX;
		let dlen = 0i64;
		let slen = len(s.s): i64;

		for (let j = 0z; j < len(s.d); j += 1) {
			const d = s.d[j];
			match (bytes::index(s.s, d)) {
			case let ix: size =>
				const ix = ix: i64;
				if (ix < i) {
					i = ix;
					dlen = len(d): i64;
					*dout = d;
				};
			case void =>
				if (slen < i) {
					i = slen;
				};
			};
		};

		assert(i != types::I64_MAX);
		s.p = i;
	};

	return s.s[..s.p: size];
};

// The state for a tokenizer.
type tokenizer = btokenizer;

// Returns a tokenizer which yields sub-strings tokenized by a delimiter,
// starting at the beginning of the string.
//
// 	let tok = strings::tokenize("hello, my name is drew", " ");
// 	assert(strings::next_token(&tok) as str == "hello,");
// 	assert(strings::next_token(&tok) as str == "my");
// 	assert(strings::next_token(&tok) as str == "name");
// 	assert(strings::remaining_tokens(&tok) == "is drew");
//
// The caller must ensure that 'delim' is not an empty string.
fn tokenize(s: str, delim: str...) tokenizer = {
	let delims: [][]u8 = alloc([], len(delim));
	for (let i = 0z; i < len(delim); i += 1) {
		append(delims, strings::toutf8(delim[i]));
	};
	defer free(delims);
	return btokenize(strings::toutf8(s), delims...);
};

// Returns the next string from a tokenizer, and advances the cursor. Returns
// void if there are no tokens left.
fn next_token(s: *tokenizer) (str | void) = {
	let s = s: *btokenizer;
	return match (bnext_token(s)) {
	case let b: []u8 =>
		yield strings::fromutf8_unsafe(b);
	case void => void;
	};
};

// Same as next_token(), but does not advance the cursor
fn peek_token(s: *tokenizer) (str | void) = {
	let s = s: *btokenizer;
	let d: []u8 = [];
	return match (bpeek_token(s, &d)) {
	case let b: []u8 =>
		yield strings::fromutf8_unsafe(b);
	case void => void;
	};
};

fn tok_finish(s: *tokenizer) void = {
	btok_finish(s: *btokenizer);
};
0707010000001B000081A400000000000000000000000166D8109200000118000000000000000000000000000000000000003000000000rc-0+git.1725436050.2b2d211/interp/util+gaia.hause os::exec;
use rt;
use rt::sys;
use unix::passwd;

fn waitstatus(st: *exec::status) int = {
	return exec::exit(st);
};

fn getuser() passwd::pwent = {
	return passwd::pwent {
		homedir = "/home",
		...
	};
};

fn getpid() int = {
	return sys::process_getpid(rt::self): int;
};
0707010000001C000081A400000000000000000000000166D810920000015A000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/interp/util.hause os::exec;
use unix;
use unix::passwd;

fn waitstatus(st: *exec::status) int = {
	match (exec::exit(st)) {
	case exec::signaled =>
		return 129;
	case let st: exec::exited =>
		return st: int;
	};
};

fn getuser() passwd::pwent = {
	return passwd::getuid(unix::getuid()) as passwd::pwent;
};

fn getpid() int = {
	return exec::self(): int;
};
0707010000001D000081A400000000000000000000000166D810920000269F000000000000000000000000000000000000002C00000000rc-0+git.1725436050.2b2d211/interp/value.hause ast;
use ast::{access_type};
use fmt;
use glob;
use io;
use os::exec;
use os;
use path;
use rt;
use strconv;
use strings;
use unix::passwd;
use unix;

// A value object.
// TODO: Consider dropping str in favor of a 1-length slice
export type value = (str | []str);

// Expands an AST value into an interpreter value. The return value must be
// freed by the caller with [[value_finish]].
export fn expand(
	state: *state,
	val: *ast::value,
	glob: bool,
) (value | error) = {
	match (*val) {
	case let val: ast::string =>
		return strings::dup(val);
	case let val: ast::argument =>
		if (strings::hasprefix(val, '~')) {
			val = expand_tilde(val);
		};
		if (glob && strings::contains(val, '*')) {
			return expand_glob(val)?;
		};
		return strings::dup(val);
	case let val: ast::access =>
		const var = match (get(state, val.target)) {
		case let var: *variable =>
			yield var;
		case null =>
			// XXX: Plan 9 compat; should we have a different way of
			// detecting unset variables?
			if (val.atype == access_type::LEN) {
				return strings::dup("0");
			};
			return undef {
				name = val.target,
			};
		};

		switch (val.atype) {
		case access_type::VAR =>
			return value_dup(&var.value);
		case access_type::LEN =>
			match (var.value) {
			case let x: str =>
				return strings::dup(strconv::ztos(len(x)));
			case let x: []str =>
				return strings::dup(strconv::ztos(len(x)));
			};
		case access_type::QUOTED =>
			return value_str(&var.value);
		case access_type::SQUOTED =>
			return value_sstr(&var.value);
		case access_type::INDEX =>
			const ix = expand(state, val.index as *ast::value, true)?;
			defer value_finish(&ix);
			const ix = value_int(&ix)?;
			if (ix <= 0) {
				return bounds;
			};
			const ix = ix: size - 1;

			match (var.value) {
			case let x: str =>
				if (ix >= len(x)) {
					return bounds;
				};
				const sub = strings::sub(x, ix, ix + 1);
				return strings::dup(sub);
			case let x: []str =>
				if (ix >= len(x)) {
					return bounds;
				};
				return strings::dup(x[ix]);
			};
		case access_type::SLICE =>
			const ix = expand(state, val.index as *ast::value, true)?;
			defer value_finish(&ix);
			const ix = value_int(&ix)?;
			if (ix <= 0) {
				return bounds;
			};
			const ix = ix: size - 1;

			const end = expand(state, val.end as *ast::value, true)?;
			defer value_finish(&end);
			let end = value_int(&end)?;
			if (end <= -1) {
				return bounds;
			};
			let end = end: size;

			match (var.value) {
			case let x: str =>
				if (ix >= len(x)) {
					return bounds;
				};
				const end = if (end == 0) strings::end else end;
				const sub = strings::sub(x, ix, end);
				return strings::dup(sub);
			case let x: []str =>
				if (ix >= len(x)) {
					return bounds;
				};
				let v: value =
					if (end == 0) x[ix..]
					else x[ix..end];
				return value_dup(&v);
			};
		};
	case let val: []*ast::value =>
		let list: value = alloc([], len(val));
		for (let i = 0z; i < len(val); i += 1) {
			const item = expand(state, val[i], true)?;
			value_append(&list, item);
		};
		return list;
	case let val: ast::subscript =>
		return expand_subscript(state, &val)?;
	case let val: ast::concat =>
		return expand_concat(state, &val)?;
	};
};

fn expand_tilde(pattern: str) str = {
	let buf = path::init(pattern)!;

	let iter = path::iter(&buf);
	const prefix = match (path::nextiter(&iter)) {
		case let s: str =>
			yield s;
		case =>
			abort();
	};

	const pw = if (prefix == "~") {
		yield getuser();
	} else {
		const user = strings::dup(strings::ltrim(prefix, '~'));
		yield passwd::getuser(user);
	};
	match (pw) {
	case void =>
		void;
	case =>
		const pw = pw as passwd::pwent;
		defer passwd::pwent_finish(&pw);
		const home = strings::dup(pw.homedir);
		path::popprefix(&buf, prefix)!;
		path::prepend(&buf, home)!;
	};

	const s = path::string(&buf);
	if (strings::hassuffix(pattern, '/')) {
		return strings::join("", s, "/");
	} else {
		return strings::dup(s);
	};
};

fn expand_glob(pattern: str) (value | error) = {
	let result: []str = [];

	const glob = glob::glob(pattern);
	for (true) {
		const item = match (glob::next(&glob)) {
		case let s: str =>
			yield s;
		case done =>
			break;
		case let err: glob::failure =>
			return err.error;
		};
		append(result, item);
	};

	return result;
};

fn expand_subscript(
	state: *state,
	script: *ast::subscript,
) (value | error) = {
	// Here we fork a child process off to soak up writes from the current
	// shell. We dup the stdout file descriptor over a pipe and the child
	// process reads until EOF, then writes it back to a second pipe, which
	// the parent reads from to get the output of the subscript.
	//
	// This whole dance is necessary because it allows the subscript to run
	// in the current shell rather than a subshell.

	// parent writes to this pipe and child reads from it
	const (read1, write1) = exec::pipe();
	// child writes to this pipe and parent reads from it
	const (read2, write2) = exec::pipe();

	const stdout = io::dup(os::stdout_file, io::dupflag::NOCLOEXEC)!;
	io::dup2(write1, os::stdout_file, io::dupflag::NOCLOEXEC)!;
	io::close(write1)!;

	// TODO: Expand error handling here, e.g. on invalid UTF-8
	const data = match (exec::fork()?) {
	case let proc: exec::process =>
		defer {
			io::dup2(stdout, os::stdout_file, io::dupflag::NOCLOEXEC)!;
			io::close(stdout)!;
		};
		io::close(read1)!;
		io::close(write2)!;

		let st: int = os::status::SUCCESS;
		for (let i = 0z; i < len(script.cmds); i += 1) {
			const cmd = &script.cmds[i];
			st = execute(state, cmd)?;
			if (st != os::status::SUCCESS && state.flags & flag::ERROR != 0) {
				break;
			};
		};
		io::close(os::stdout_file)!;
		set(state, "status", &(strconv::itos(st): value), false);

		const data = io::drain(read2)!;
		io::close(read2)!;
		exec::wait(&proc)?;

		yield data;
	case void =>
		io::close(read2)!;
		io::close(os::stdout_file)!;

		const data = io::drain(read1)!;
		io::writeall(write2, data)!;
		os::exit(0);
	};

	const string = match (strings::fromutf8(data)) {
	case let s: str =>
		yield strings::rtrim(s);
	case =>
		fmt::errorln("error: subscript `{{}} has invalid UTF-8 data in stdout")!;
		return invaltype;
	};

	if (script.ifs == "") {
		return string;
	};

	let ifs: []str = [];
	defer free(ifs);

	const iter = strings::iter(script.ifs);
	for (let i = 0z; !(strings::next(&iter) is done); i += 1) {
		const chr = strings::sub(script.ifs, i, i + 1);
		append(ifs, chr);
	};

	let tokens: []str = [];
	defer free(tokens);

	const tok = tokenize(string, ifs...);
	for (true) {
		match (next_token(&tok)) {
		case let tok: str =>
			if (tok == "") {
				continue; // skip empty tokens
			};
			append(tokens, tok);
		case void => break;
		};
	};

	return strings::dupall(tokens);
};

fn expand_concat(state: *state, val: *ast::concat) (value | error) = {
	const left = expand(state, val.0, true)?;
	defer value_finish(&left);
	const right = expand(state, val.1, true)?;
	defer value_finish(&right);

	if (left is str && right is str) {
		const left = value_str(&left);
		defer free(left);
		const right = value_str(&right);
		defer free(right);
		return strings::concat(left, right);
	};

	let result: []str = [];
	if (left is []str && right is []str) {
		const left = left as []str;
		const right = right as []str;
		if (len(left) != len(right)) {
			return lenmismatch;
		};

		for (let i = 0z; i < len(left); i += 1) {
			const item = strings::concat(left[i], right[i]);
			append(result, item);
		};

		return result;
	} else if (left is []str) {
		const left = left as []str;
		const right = value_str(&right);
		defer free(right);

		for (let i = 0z; i < len(left); i += 1) {
			const item = strings::concat(left[i], right);
			append(result, item);
		};

		return result;
	} else if (right is []str) {
		const right = right as []str;
		const left = value_str(&left);
		defer free(left);

		for (let i = 0z; i < len(right); i += 1) {
			const item = strings::concat(left, right[i]);
			append(result, item);
		};

		return result;
	};

	abort(); // Unreachable
};

// Converts a [[value]] into a string, with spaces between values. The return
// value must be freed by the caller.
export fn value_str(val: *value) str = {
	match (*val) {
	case let s: str =>
		return strings::dup(s);
	case let v: []str =>
		return strings::join(" ", v...);
	};
};

// Converts a [[value]] into a string, without spaces between values. The return
// value must be freed by the caller.
export fn value_sstr(val: *value) str = {
	match (*val) {
	case let s: str =>
		return strings::dup(s);
	case let v: []str =>
		return strings::join("", v...);
	};
};

// Converts a value into an integer.
export fn value_int(val: *value) (int | error) = {
	match (*val) {
	case let x: str =>
		match (strconv::stoi(x)) {
		case let x: int =>
			return x;
		case =>
			return invalnum;
		};
	case let x: []str =>
		return invalnum;
	};
};

// Duplicates a [[value]].
export fn value_dup(val: *value) value = {
	match (*val) {
	case let s: str =>
		return strings::dup(s);
	case let v: []str =>
		return strings::dupall(v);
	};
};

// Frees state associated with a [[value]].
export fn value_finish(val: *value) void = {
	match (*val) {
	case let s: str =>
		free(s);
	case let v: []str =>
		strings::freeall(v);
	};
};

// Appends a value to another value.
export fn value_append(val: *value, other: value) void = {
	match (*val) {
	case let s: str =>
		*val = alloc([s]);
	case => void;
	};

	let list = *val as []str;
	match (other) {
	case let s: str =>
		append(list, strings::dup(s));
	case let s: []str =>
		append(list, strings::dupall(s)...);
	};
	*val = list;
};

// Coerces a value into a list, and returns that list. The return value is
// statically allocated.
fn value_list(val: *value) []str = {
	match (*val) {
	case let s: str =>
		static let list: [1]str = [""];
		list[0] = s;
		return list;
	case let s: []str =>
		return s;
	};
};
0707010000001E000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002000000000rc-0+git.1725436050.2b2d211/lex0707010000001F000081A400000000000000000000000166D81092000002D8000000000000000000000000000000000000002A00000000rc-0+git.1725436050.2b2d211/lex/errors.hause encoding::utf8;
use fmt;
use io;

// A syntax error. The tuple contains the file name, line number, and column
// number of the error.
export type syntaxerr = !(const str, uint, uint);

// All possible errors that can be returned from the lexer.
export type error = !(io::error | utf8::invalid | syntaxerr);

// Converts a lexer error into a human-friendly error message.
export fn strerror(err: error) const str = {
	static let buf: [256]u8 = [0...];
	match (err) {
	case let err: io::error =>
		return io::strerror(err);
	case utf8::invalid =>
		return "Invalid UTF-8 sequence";
	case let loc: syntaxerr =>
		const (path, line, col) = loc;
		return fmt::bsprintf(buf, "{}:{}:{}: Syntax error",
			path, line, col);
	};
};
07070100000020000081A400000000000000000000000166D8109200002564000000000000000000000000000000000000002700000000rc-0+git.1725436050.2b2d211/lex/lex.hause ascii;
use bufio;
use io;
use memio;
use os;
use strconv;
use strings;

export type lexer = struct {
	in: bufio::stream,
	buffer: []u8,
	strbuf: memio::stream,
	strtok: uint,
	loc: (const str, uint, uint),
	un: []token,
	unr: (rune | void),
	prevrloc: (const str, uint, uint),
};

// Creates a new lexer. The "path" argument is borrowed from the caller for the
// lifetime of the lexer. Once the user is done using the lexer, the return
// value must be passed to [[finish]] to free associated resources.
export fn new(in: io::handle, path: const str) lexer = {
	let buffer = alloc([0u8...], os::BUFSZ);
	return lexer {
		in = bufio::init(in, buffer, []),
		buffer = buffer,
		strbuf = memio::dynamic(),
		strtok = 0,
		loc = (path, 1, 0),
		un = [],
		unr = void,
		prevrloc = (path, 1, 0),
	};
};

// Frees resources associated with the lexer. Does not close the underlying I/O
// handle.
export fn finish(lex: *lexer) void = {
	free(lex.buffer);
	free(lex.un);
	io::close(&lex.strbuf)!;
};

// Returns a single token from the lexer. The return value is borrowed from the
// internal lexer state and will be overwritten on subsequent calls.
//
// If word is true, the lexer will scan for word tokens, otherwise for argument
// tokens.
export fn next(lex: *lexer, word: bool) (token | error) = {
	if (len(lex.un) != 0) {
		const tok = lex.un[0];
		delete(lex.un[0]);
		return tok;
	};

	if (lex.strtok != 0) {
		lex.strtok -= 1;
		if (lex.strtok == 0) {
			return lexstring(lex, '"');
		};
	};

	let rn: rune = '\0';
	for (true) {
		rn = match (scanrune(lex)?) {
		case let rn: rune =>
			yield rn;
		case io::EOF =>
			return (ltok::EOF, "");
		};

		if (rn == '\\') {
			rn = match (scanrune(lex)?) {
			case let rn: rune =>
				yield rn;
			case io::EOF =>
				return lex.loc: syntaxerr;
			};

			if (rn == '\n') {
				continue;
			} else {
				return lex.loc: syntaxerr;
			};
		} else {
			break;
		};
	};

	if (rn == '#') {
		match (scancomment(lex)?) {
		case io::EOF =>
			return (ltok::EOF, "");
		case void =>
			return next(lex, word);
		};
	};

	if (word) {
		if (ascii::isalnum(rn) || rn == '_' || rn == '*' || rn == '.') {
			unread(lex, rn);
			return lexword(lex);
		};

		// Some tokens are only matched in word mode
		switch (rn) {
		case '-' =>
			return (ltok::DASH, "");
		case =>
			yield;
		};
	};

	switch (rn) {
	case '\n' =>
		return (ltok::LF, "");
	case ' ', '\t' =>
		return (ltok::WS, "");
	case ';' =>
		return (ltok::SEMICOLON, "");
	case '!' =>
		return (ltok::BANG, "");
	case '`' =>
		return (ltok::BACKTICK, "");
	case '^' =>
		return (ltok::CARET, "");
	case '=' =>
		return (ltok::EQUAL, "");
	case '@' =>
		return (ltok::AT, "");
	case '{' =>
		return (ltok::LBRACE, "");
	case '}' =>
		return (ltok::RBRACE, "");
	case '(' =>
		return (ltok::LPAREN, "");
	case ')' =>
		return (ltok::RPAREN, "");
	case '[' =>
		return (ltok::LBRACKET, "");
	case ']' =>
		return (ltok::RBRACKET, "");
	case '$', '|', '&', '>', '<' =>
		unread(lex, rn);
		return lex2(lex);
	case '"', '\'' =>
		return lexstring(lex, rn);
	case =>
		if (!word) {
			unread(lex, rn);
			return lexarg(lex);
		};
		return lex.loc: syntaxerr;
	};
};

// Unreads a token from the lexer. Note that the storage of any value associated
// with the token is the caller's problem, you should dup the string if present.
export fn unlex(lex: *lexer, tok: token) void = {
	insert(lex.un[0], tok);
};

// Reads the next token and immediately unlexes it.
export fn peek(lex: *lexer, word: bool) (token | error) = {
	const tok = next(lex, word)?;
	unlex(lex, tok);
	return tok;
};

const nonarg = "[](){}<>'\"|;$#`\\ \t\n";

fn lexarg(lex: *lexer) (token | error) = {
	memio::reset(&lex.strbuf);

	for (true) {
		const rn = match (scanrune(lex)?) {
		case let rn: rune =>
			yield rn;
		case io::EOF =>
			break;
		};

		// XXX: O(n^2) I guess
		if (strings::contains(nonarg, rn)) {
			unread(lex, rn);
			break;
		};

		memio::appendrune(&lex.strbuf, rn)!;
	};

	const string = memio::string(&lex.strbuf)!;
	switch (string) {
	case "if" =>
		return (ltok::IF, "");
	case "else" =>
		return (ltok::ELSE, "");
	case "for" =>
		return (ltok::FOR, "");
	case "fn" =>
		return (ltok::FN, "");
	case "while" =>
		return (ltok::WHILE, "");
	case "switch" =>
		return (ltok::SWITCH, "");
	case "case" =>
		return (ltok::CASE, "");
	case "default" =>
		return (ltok::DEFAULT, "");
	case "in" =>
		return (ltok::IN, "");
	case =>
		return (ltok::ARGUMENT, string);
	};
};

fn lexword(lex: *lexer) (token | error) = {
	memio::reset(&lex.strbuf);

	for (let i = 0z; true; i += 1) {
		const rn = match (scanrune(lex)?) {
		case let rn: rune =>
			yield rn;
		case io::EOF =>
			break;
		};

		if (!ascii::isalnum(rn) && rn != '_' && rn != '*' && rn != '.') {
			unread(lex, rn);
			break;
		};

		memio::appendrune(&lex.strbuf, rn)!;
	};

	const string = memio::string(&lex.strbuf)!;
	switch (string) {
	case "if" =>
		return (ltok::IF, "");
	case "else" =>
		return (ltok::ELSE, "");
	case "for" =>
		return (ltok::FOR, "");
	case "fn" =>
		return (ltok::FN, "");
	case "while" =>
		return (ltok::WHILE, "");
	case "switch" =>
		return (ltok::SWITCH, "");
	case "case" =>
		return (ltok::CASE, "");
	case "default" =>
		return (ltok::DEFAULT, "");
	case "in" =>
		return (ltok::IN, "");
	case =>
		return (ltok::WORD, string);
	};
};

fn lexstring(lex: *lexer, sigil: rune) (token | error) = {
	memio::reset(&lex.strbuf);
	for (true) {
		const rn = match (scanrune(lex)?) {
		case let rn: rune =>
			yield rn;
		case io::EOF =>
			break;
		};

		if (rn == sigil) {
			break;
		};

		switch (rn) {
		case '$' =>
			if (sigil == '"') {
				unread(lex, '$');
				lex.strtok = 3;
				break;
			};
		case '\\' =>
			if (sigil == '"') {
				rn = lexesc(lex)?;
			};
		case =>
			yield;
		};

		memio::appendrune(&lex.strbuf, rn)!;
	};

	return (ltok::STRING, memio::string(&lex.strbuf)!);
};

fn lexesc(lex: *lexer) (rune | error) = {
	const rn = match (scanrune(lex)?) {
	case let rn: rune =>
		yield rn;
	case io::EOF =>
		return lex.loc: syntaxerr;
	};

	// TODO:
	// - Add escape sequences to grammar
	// - Consider adding support for \x00 and \u0000 etc
	switch (rn) {
	case '\\' =>
		return '\\';
	case '\'' =>
		return '\'';
	case '0' =>
		return '\0';
	case 'a' =>
		return '\a';
	case 'b' =>
		return '\b';
	case 'f' =>
		return '\f';
	case 'n' =>
		return '\n';
	case 'r' =>
		return '\r';
	case 't' =>
		return '\t';
	case 'v' =>
		return '\v';
	case '"' =>
		return '\"';
	case =>
		return rn;
	};
};

fn lex2(lex: *lexer) (token | error) = {
	const rn = match (scanrune(lex)?) {
	case let rn: rune =>
		yield rn;
	case io::EOF =>
		abort(); // Invariant
	};

	switch (rn) {
	case '|' =>
		return scan2(lex, '|', ltok::PIPE, ltok::LOR)?;
	case '&' =>
		return scan2(lex, '&', ltok::AND, ltok::LAND)?;
	case '>' =>
		return scan2(lex, '>', ltok::GT, ltok::GTGT)?;
	case '<' =>
		const tok = scan2(lex, '<', ltok::LT, ltok::HEREDOC)?;
		switch (tok.0) {
		case ltok::LT =>
			return tok;
		case ltok::HEREDOC =>
			return heredoc(lex);
		case => abort();
		};
	case '$' =>
		const rn = match (scanrune(lex)?) {
		case let rn: rune =>
			yield rn;
		case io::EOF =>
			return (ltok::DOLLAR, "");
		};

		switch (rn) {
		case '#' =>
			return (ltok::DOLLAR_POUND, "");
		case '"' =>
			return (ltok::DOLLAR_QUOTE, "");
		case '\'' =>
			return (ltok::DOLLAR_SQUOTE, "");
		case =>
			unread(lex, rn);
			return (ltok::DOLLAR, "");
		};
	case =>
		abort();
	};
};

fn heredoc(lex: *lexer) (token | error) = {
	const tok = next(lex, true)?;

	let sigil = "", quoted = false;
	switch (tok.0) {
	case ltok::WORD =>
		sigil = tok.1;
	case ltok::STRING =>
		sigil = tok.1;
		quoted = true;
	case => return lex.loc: syntaxerr;
	};

	assert(quoted); // TODO

	if (next(lex, true)?.0 != ltok::LF) {
		return lex.loc: syntaxerr;
	};

	memio::reset(&lex.strbuf);

	for (true) {
		const line = match (scanline(lex)?) {
		case io::EOF =>
			return lex.loc: syntaxerr;
		case let line: str =>
			yield line;
		};
		defer free(line);

		if (strings::rtrim(line, '\n') == sigil) {
			break;
		};

		memio::concat(&lex.strbuf, line)!;
	};

	const doc = memio::string(&lex.strbuf)!;
	return (ltok::HEREDOC, doc);
};

fn scancomment(lex: *lexer) (void | io::EOF | error) = {
	for (true) {
		match (scanrune(lex)?) {
		case let rn: rune =>
			if (rn == '\n') {
				break;
			};
		case io::EOF =>
			return io::EOF;
		};
	};
};

fn scan2(
	lex: *lexer,
	next: rune,
	tok1: ltok,
	tok2: ltok,
) (token | error) = {
	const rn = match (scanrune(lex)?) {
	case let rn: rune =>
		yield rn;
	case io::EOF =>
		return (tok1, "");
	};

	if (rn == next) {
		return (tok2, "");
	} else {
		unread(lex, rn);
		return (tok1, "");
	};
};

fn scanrune(lex: *lexer) (rune | io::EOF | error) = {
	const rn = match (lex.unr) {
	case let rn: rune =>
		lex.unr = void;
		yield rn;
	case void =>
		yield match (bufio::read_rune(&lex.in)?) {
		case let rn: rune =>
			yield rn;
		case io::EOF =>
			return io::EOF;
		};
	};

	lex.prevrloc = lex.loc;
	switch (rn) {
	case '\n' =>
		lex.loc.1 += 1;
		lex.loc.2 = 0;
	case =>
		lex.loc.2 += 1;
	};

	return rn;
};

// Caller must free return value
fn scanline(lex: *lexer) (str | io::EOF | error) = {
	let line = memio::dynamic();
	for (true) {
		const rn = match (scanrune(lex)?) {
		case let rn: rune =>
			yield rn;
		case io::EOF =>
			return io::EOF;
		};
		memio::appendrune(&line, rn)!;
		if (rn == '\n') {
			break;
		};
	};
	return memio::string(&line)!;
};

fn unread(lex: *lexer, rn: rune) void = {
	assert(lex.unr is void);
	lex.unr = rn;
	lex.loc = lex.prevrloc;
};
07070100000021000081A400000000000000000000000166D810920000082E000000000000000000000000000000000000002900000000rc-0+git.1725436050.2b2d211/lex/token.hause fmt;

// A lexical token.
export type ltok = enum {
	LF,
	WS,
	SEMICOLON,
	BANG,
	DASH,
	BACKTICK,
	CARET,
	EQUAL,
	AT,
	LT,
	GT,
	GTGT,
	AND,
	LAND,
	LOR,
	PIPE,
	DOLLAR,
	DOLLAR_POUND,
	DOLLAR_QUOTE,
	DOLLAR_SQUOTE,
	FN,
	IF,
	ELSE,
	FOR,
	WHILE,
	SWITCH,
	CASE,
	DEFAULT,
	IN,
	LBRACE,
	RBRACE,
	LPAREN,
	RPAREN,
	LBRACKET,
	RBRACKET,

	// Value tokens
	WORD,
	ARGUMENT,
	STRING,
	HEREDOC,

	// Special
	EOF,
};

// A single lexigraphical token.
export type token = (ltok, str);

// Converts a token to a user-friendly string.
export fn tokenstr(tok: token) const str = {
	switch (tok.0) {
	case ltok::LF =>
		return "line feed";
	case ltok::WS =>
		return "whitespace";
	case ltok::SEMICOLON =>
		return ";";
	case ltok::BANG =>
		return "!";
	case ltok::DASH =>
		return "-";
	case ltok::BACKTICK =>
		return "`";
	case ltok::CARET =>
		return "^";
	case ltok::EQUAL =>
		return "=";
	case ltok::AT =>
		return "@";
	case ltok::LT =>
		return "<";
	case ltok::GT =>
		return ">";
	case ltok::GTGT =>
		return ">>";
	case ltok::AND =>
		return "&";
	case ltok::LAND =>
		return "&&";
	case ltok::LOR =>
		return "||";
	case ltok::PIPE =>
		return "|";
	case ltok::DOLLAR =>
		return "$";
	case ltok::DOLLAR_POUND =>
		return "$#";
	case ltok::DOLLAR_QUOTE =>
		return "$\"";
	case ltok::DOLLAR_SQUOTE =>
		return "$'";
	case ltok::FN =>
		return "fn";
	case ltok::IF =>
		return "if";
	case ltok::ELSE =>
		return "else";
	case ltok::FOR =>
		return "for";
	case ltok::WHILE =>
		return "while";
	case ltok::SWITCH =>
		return "switch";
	case ltok::CASE =>
		return "case";
	case ltok::DEFAULT =>
		return "default";
	case ltok::IN =>
		return "in";
	case ltok::LBRACE =>
		return "{";
	case ltok::RBRACE =>
		return "}";
	case ltok::LPAREN =>
		return "(";
	case ltok::RPAREN =>
		return ")";
	case ltok::LBRACKET =>
		return "[";
	case ltok::RBRACKET =>
		return "]";
	case ltok::ARGUMENT =>
		return "argument";
	case ltok::STRING =>
		return "string";
	case ltok::WORD =>
		return "word";
	case ltok::HEREDOC =>
		return "heredoc";
	case ltok::EOF =>
		return "end of file";
	};
};
07070100000022000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002000000000rc-0+git.1725436050.2b2d211/lib07070100000023000081A400000000000000000000000166D810920000072D000000000000000000000000000000000000002A00000000rc-0+git.1725436050.2b2d211/lib/getopt.rc# Usage:
#
# while (true) {
# 	eval `{getopt "abc:d:" $*}
#	switch ($opt) {
#	case a echo option A
#	case b echo option B
#	case c echo option C: $arg
#	case d echo option D: $arg
#	}
# }
#
# for (arg) echo non-option argument: $arg
#
# Sets "opt" to the selected option and "arg" to the argument, if provided.
# Breaks the loop and shifts the remaning args after all option arguments have
# been parsed, so $* contains only non-option arguments.
#
# optstr uses the same format as getopt(3).
fn getopt(optstr) {
	# Initial setup
	if (test $#optind -eq 0) {
		optind=1
		optpos=2

		# Parse option string
		_nonarg=""
		_arg=""
		_i=1
		while (test $_i -le $#optstr) {
			_opt=$optstr($_i)
			_j=`{expr $_i + 1}
			if (test $_j -gt $#optstr) {
				_nonarg=$_nonarg^$_opt
				break
			}

			if (test $optstr($_j) "=" ":") {
				_arg=$_arg^$_opt
				_i=`{expr $_i + 2}
			} else {
				_nonarg=$_nonarg^$_opt
				_i=`{expr $_i + 1}
			}
		}
	}

	# Parse arguments
	shift 3
	echo "unset opt arg"
	if (test $optind -gt $#*) {
		echo break
		return
	}

	arg=$*($optind)
	if (test $arg "=" "--") {
		echo shift $optind
		echo break
		return
	}
	if (test $arg(1) "!=" "-") {
		echo shift `{expr $optind - 1}
		echo break
		return
	}

	_ochar=$arg($optpos)
	echo "opt=$_ochar"
	if (~ $_nonarg "*$_ochar""*") {
		optpos=`{expr $optpos + 1}
		if (test $optpos -gt $#arg) {
			optind=`{expr $optind + 1}
			optpos=2
		}
	} else if (~ $_arg "*$_ochar""*") {
		optpos=`{expr $optpos + 1}
		if (test $optpos -le $#arg) {
			# -owhatever
			_optarg=$*($optind)
			echo "arg="`{echo $_optarg | cut -c$optpos-}
			optind=`{expr $optind + 1}
		} else {
			# -o whatever
			optind=`{expr $optind + 1}
			_optarg=$*($optind)
			optind=`{expr $optind + 1}
			echo "arg=$_optarg"
		}
		optpos=2
	} else {
		echo echo Unknown option -$_ochar
		echo exit 1
	}
}
07070100000024000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002200000000rc-0+git.1725436050.2b2d211/parse07070100000025000081A400000000000000000000000166D8109200001EE5000000000000000000000000000000000000002D00000000rc-0+git.1725436050.2b2d211/parse/command.hause ast;
use fs;
use io;
use lex;
use lex::{ltok};
use os;
use regex;
use strings;

// Parses the next [[ast::command]] from a list of commands.
export fn parse_commands(p: *parser) (ast::command | io::EOF | error) = {
	allws(p)?;

	if (try(p, ltok::EOF)? is lex::token) {
		return io::EOF;
	};

	const cmd = parse_command(p);
	try(p, ltok::SEMICOLON)?;
	return cmd;
};

fn parse_command(p: *parser) (ast::command | error) = {
	const tok = want(p,
		ltok::IF,
		ltok::FOR,
		ltok::WHILE,
		ltok::SWITCH,
		ltok::FN,
		ltok::LBRACE,
		ltok::AT,
		ltok::BANG,
		ltok::DOLLAR,
		ltok::DOLLAR_QUOTE,
		ltok::DOLLAR_POUND,
		ltok::LPAREN,
		ltok::BACKTICK,
		ltok::ARGUMENT,
		ltok::STRING,
	)?;
	if (tok.0 != ltok::ARGUMENT && tok.0 != ltok::STRING) {
		lex::unlex(&p.lex, tok);
	};

	switch (tok.0) {
	case ltok::IF =>
		return parse_if(p)?;
	case ltok::FOR =>
		return parse_for_loop(p)?;
	case ltok::WHILE =>
		return parse_while_loop(p)?;
	case ltok::SWITCH =>
		return parse_switch(p)?;
	case ltok::FN =>
		return parse_func(p)?;
	case ltok::LBRACE =>
		return parse_nested(p)?;
	case ltok::AT =>
		want(p, ltok::AT)?;
		return ast::subshell {
			command = alloc(parse_command(p)?),
		};
	case ltok::BANG =>
		want(p, ltok::BANG)?;
		return ast::not {
			command = alloc(parse_command(p)?),
		};
	case ltok::ARGUMENT =>
		const word = strings::dup(tok.1);
		defer free(word);

		if (regex::test(&assignre, word)) {
			const parts = strings::splitn(word, "=", 2);
			defer free(parts);

			if (len(parts) > 1 && len(parts[1]) != 0) {
				// Example: x=4
				lex::unlex(&p.lex, (ltok::ARGUMENT, parts[1]));
			} else {
				// Example: x= 4
				ws(p, false)?;
			};
			lex::unlex(&p.lex, (ltok::EQUAL, ""));
			lex::unlex(&p.lex, (ltok::WORD, parts[0]));
			return parse_assignment(p)?;
		};
		const had_ws = ws(p, false)?;
		if (peek(p, ltok::EQUAL)? is lex::token) {
			// Example: x = 4 or x =4
			want(p, ltok::EQUAL)?;
			ws(p, false)?;
			lex::unlex(&p.lex, (ltok::EQUAL, ""));
			lex::unlex(&p.lex, (ltok::WORD, word));
			return parse_assignment(p)?;
		} else if (had_ws) {
			// Example: x = 4 or x =4
			lex::unlex(&p.lex, (ltok::WS, ""));
		};

		lex::unlex(&p.lex, (tok.0, word));
		return parse_compound(p)?;
	case ltok::STRING =>
		return parse_compound(p)?;
	case ltok::DOLLAR, ltok::DOLLAR_QUOTE, ltok::DOLLAR_POUND,
			ltok::DOLLAR_SQUOTE, ltok::LPAREN, ltok::BACKTICK =>
		return parse_compound(p)?;
	case => abort();
	};
};

fn parse_compound(p: *parser) (ast::command | error) = {
	const simple = parse_simple(p)?;
	ws(p, false)?;

	const tok = match (try(p, ltok::PIPE, ltok::LAND, ltok::LOR)?) {
	case let tok: lex::token =>
		yield tok;
	case void =>
		return simple;
	};
	ws(p, false)?;

	if (tok.0 == ltok::PIPE) {
		if (try(p, ltok::LBRACKET)? is lex::token) {
			abort(); // TODO
		};
	};

	return ast::compound {
		lval = alloc(simple: ast::command),
		rval = alloc(parse_command(p)?),
		op = switch (tok.0) {
		case ltok::PIPE =>
			yield ast::compound_op::PIPE;
		case ltok::LOR =>
			yield ast::compound_op::LOR;
		case ltok::LAND =>
			yield ast::compound_op::LAND;
		case =>
			abort();
		},
		...
	};
};

// Parses an [[ast::simple]] command.
fn parse_simple(p: *parser) (ast::simple | error) = {
	const simple = ast::simple {
		args = parse_value_list(p, false)?,
		redirs = [],
	};

	for (true) {
		const tok = match (try(p,
			ltok::GT,
			ltok::GTGT,
			ltok::LT,
			ltok::HEREDOC)) {
		case let tok: lex::token =>
			yield tok;
		case void =>
			return simple;
		};

		const file = switch (tok.0) {
		case ltok::LT, ltok::HEREDOC =>
			yield os::stdin_file;
		case ltok::GT, ltok::GTGT =>
			yield os::stdout_file;
		case =>
			// TODO: foo <>file
			abort();
		};
		const oflag = switch (tok.0) {
		case ltok::LT, ltok::HEREDOC =>
			yield fs::flag::RDONLY;
		case ltok::GT =>
			yield fs::flag::WRONLY
				| fs::flag::CREATE;
		case ltok::GTGT =>
			yield fs::flag::WRONLY
				| fs::flag::APPEND
				| fs::flag::CREATE;
		case =>
			abort();
		};

		if (tok.0 == ltok::HEREDOC) {
			append(simple.redirs, ast::redir {
				input = strings::dup(tok.1): ast::heredoc,
				oflag = oflag,
				file = file,
			});
			continue;
		};

		if (try(p, ltok::LBRACKET) is lex::token) {
			abort(); // TODO
		};

		ws(p, false)?;

		const (path, _) = parse_value(p)?;
		append(simple.redirs, ast::redir {
			input = path,
			oflag = oflag,
			file = file,
		});
	};
};

fn parse_assignment(p: *parser) (ast::assign | error) = {
	const word = strings::dup(want(p, ltok::WORD)?.1);
	want(p, ltok::EQUAL)?;
	const (value, _) = parse_value(p)?;
	return ast::assign {
		target = word,
		value = alloc(value),
	};
};

fn parse_func(p: *parser) (ast::fndef | error) = {
	want(p, ltok::FN)?;
	ws(p, true)?;
	const name = strings::dup(want(p, ltok::WORD)?.1);

	let args: []str = [];
	if (try(p, ltok::LPAREN)? is lex::token) {
		args = parse_params(p)?;
	};

	ws(p, false)?;

	const body = parse_command(p)?;
	return ast::fndef {
		name = name,
		args = args,
		body = alloc(body),
	};
};

fn parse_params(p: *parser) ([]str | error) = {
	let params: []str = [];

	for (true) {
		const tok = want(p, ltok::WORD, ltok::RPAREN)?;
		switch (tok.0) {
		case ltok::RPAREN =>
			break;
		case ltok::WORD =>
			yield;
		case => abort();
		};

		append(params, strings::dup(tok.1));
		ws(p, true)?;
	};

	return params;
};

fn parse_nested(p: *parser) (ast::script | error) = {
	want(p, ltok::LBRACE)?;

	let cmds: []ast::command = [];
	for (true) {
		const cmd = match (parse_commands(p)?) {
		case io::EOF =>
			return mksyntaxerr(&p.lex, [ltok::RBRACE],
				(ltok::EOF, ""));
		case let cmd: ast::command =>
			yield cmd;
		};

		append(cmds, cmd);

		allws(p)?;

		if (try(p, ltok::RBRACE)? is lex::token) {
			break;
		};
	};

	return cmds;
};

fn parse_if(p: *parser) (ast::if_stmt | error) = {
	want(p, ltok::IF)?;
	ws(p, false)?;
	want(p, ltok::LPAREN)?;
	ws(p, false)?;

	const cond = parse_command(p)?;
	ws(p, false)?;
	want(p, ltok::RPAREN)?;
	ws(p, false)?;

	const body = parse_command(p)?;
	let stmt = ast::if_stmt {
		cond = alloc(cond),
		body = alloc(body),
		alt = null,
	};

	ws(p, false)?;

	if (try(p, ltok::ELSE)? is lex::token) {
		ws(p, false)?;
		stmt.alt = alloc(parse_command(p)?);
	};

	return stmt;
};

fn parse_for_loop(p: *parser) (ast::for_loop | error) = {
	want(p, ltok::FOR)?;
	ws(p, false)?;
	want(p, ltok::LPAREN)?;
	ws(p, true)?;

	const bind = strings::dup(want(p, ltok::WORD)?.1);
	ws(p, false)?;

	let values: []*ast::value = [];
	if (try(p, ltok::IN) is lex::token) {
		ws(p, false)?;
		values = parse_value_list(p, false)?;
		ws(p, false)?;
	};

	want(p, ltok::RPAREN)?;
	ws(p, false)?;

	return ast::for_loop {
		bind = bind,
		values = values,
		body = alloc(parse_command(p)?),
	};
};

fn parse_while_loop(p: *parser) (ast::while_loop | error) = {
	want(p, ltok::WHILE)?;
	ws(p, false)?;
	want(p, ltok::LPAREN)?;
	const cmd = alloc(parse_command(p)?);
	want(p, ltok::RPAREN)?;
	ws(p, false)?;

	return ast::while_loop {
		cmd = cmd,
		body = alloc(parse_command(p)?),
	};
};

fn parse_switch(p: *parser) (ast::switch_cmd | error) = {
	want(p, ltok::SWITCH)?;
	ws(p, false)?;
	want(p, ltok::LPAREN)?;
	const (subject, _) = parse_value(p)?;
	want(p, ltok::RPAREN)?;
	ws(p, false)?;

	want(p, ltok::LBRACE)?;

	let cases: []ast::switch_case = [];
	for (true) {
		allws(p)?;

		switch (want(p, ltok::CASE, ltok::DEFAULT, ltok::RBRACE)?.0) {
		case ltok::CASE =>
			ws(p, false)?;
			const (val, _) = parse_value(p)?;
			allws(p)?;
			const cmd = parse_command(p)?;
			append(cases, ast::switch_case {
				pattern = alloc(val),
				command = alloc(cmd),
			});
		case ltok::DEFAULT =>
			allws(p)?;
			const cmd = parse_command(p)?;
			append(cases, ast::switch_case {
				pattern = null,
				command = alloc(cmd),
			});
		case ltok::RBRACE => break;
		case => abort();
		};
	};

	return ast::switch_cmd {
		subject = alloc(subject),
		cases = cases,
	};
};
07070100000026000081A400000000000000000000000166D8109200000582000000000000000000000000000000000000002C00000000rc-0+git.1725436050.2b2d211/parse/errors.hause fmt;
use lex;
use memio;

// All errors which can be raised by the parser.
export type error = !(lex::error | syntaxerr);

// A syntax error.
export type syntaxerr = struct {
	loc: (const str, uint, uint),
	want: []lex::ltok,
	found: lex::token,
};

// Converts an [[error]] into a user-friendly string. The return value is
// statically allocated and will be overwritten on subsequent calls.
export fn strerror(err: error) const str = {
	static let buf: [1024]u8 = [0...];
	match (err) {
	case let err: lex::error =>
		return lex::strerror(err);
	case let syn: syntaxerr =>
		static let buf: [1024]u8 = [0...];
		const found = lex::tokenstr(syn.found);
		const (file, line, col) = syn.loc;
		const sink = memio::fixed(buf);
		if (len(syn.want) != 0) {
			fmt::fprintf(&sink,
				"Syntax error: {}:{}:{}: unexpected {}, expected ",
				file, line, col, found)!;
		} else {
			fmt::fprintf(&sink,
				"Syntax error: {}:{}:{}: unexpected {}",
				file, line, col, found)!;
		};
		for (let i = 0z; i < len(syn.want); i += 1) {
			fmt::fprintf(&sink, "{}",
				lex::tokenstr((syn.want[i], "")))!;
			if (i + 1 < len(syn.want)) {
				fmt::fprintf(&sink, ", ")!;
			};
		};
		return memio::string(&sink)!;
	};
};

fn mksyntaxerr(
	lex: *lex::lexer,
	want: []lex::ltok,
	found: lex::token,
) syntaxerr = {
	// XXX: memory leak
	return syntaxerr {
		loc = lex.loc,
		want = alloc(want...),
		found = found,
	};
};
07070100000027000081A400000000000000000000000166D8109200000B1E000000000000000000000000000000000000002C00000000rc-0+git.1725436050.2b2d211/parse/parser.hause io;
use lex;
use lex::{ltok};
use regex;

let assignre: regex::regex = regex::regex { ... };

@init fn assignre() void = {
	assignre = regex::compile(`^[A-Za-z_][A-Za-z0-9_]*=.*`)!;
};

@fini fn assignre() void = {
	regex::finish(&assignre);
};

export type parser = struct {
	lex: lex::lexer,
};

// Creates a new [[parser]].
export fn new(in: io::handle, path: str) parser = {
	return parser {
		lex = lex::new(in, path),
	};
};

// Frees resources associated with a [[parser]]. Does not close the underlying
// file.
export fn finish(p: *parser) void = {
	lex::finish(&p.lex);
};

// Consumes any number of whitespace tokens and returns true if there was at
// least one. Set "word" to true if the next token is expected to be a word.
fn ws(p: *parser, word: bool) (bool | error) = {
	const word = if (word) ltok::WORD else ltok::ARGUMENT;

	let nws = 0z;
	for (true) {
		match (try(p, ltok::WS, word)?) {
		case let tok: lex::token =>
			if (tok.0 == word) {
				lex::unlex(&p.lex, tok);
				break;
			};
			nws += 1;
		case void =>
			break;
		};
	};

	return nws != 0;
};

// Consumes all whitespace, including line feeds.
fn allws(p: *parser) (void | error) = {
	for (try(p, ltok::LF, ltok::WS)? is lex::token) void;
};

// Requires the next token to have a matching simple tok. Returns that token, or
// an error.
fn want(p: *parser, want: ltok...) (lex::token | error) = {
	let word = false;
	for (let i = 0z; i < len(want); i += 1) {
		if (want[i] == ltok::WORD) {
			word = true;
		};
	};

	const tok = lex::next(&p.lex, word)?;
	if (len(want) == 0) {
		return tok;
	};

	for (let i = 0z; i < len(want); i += 1) {
		if (want[i] == tok.0) {
			return tok;
		};
	};

	return mksyntaxerr(&p.lex, want, tok);
};

// Attempts to read a token from the lexer and match it against a list of
// desired tokens. If the next token is one of the desired tokens, it is
// returned. Otherwise, the token is unlexed and void is returned.
fn try(p: *parser, want: ltok...) (lex::token | error | void) = {
	assert(len(want) != 0);

	let word = false;
	for (let i = 0z; i < len(want); i += 1) {
		if (want[i] == ltok::WORD) {
			word = true;
		};
	};

	const tok = lex::next(&p.lex, word)?;
	for (let i = 0z; i < len(want); i += 1) {
		if (want[i] == tok.0) {
			return tok;
		};
	};

	lex::unlex(&p.lex, tok);
};

// Attempts to peek a token from the lexer and match it against a list of
// desired tokens. If the next token is one of the desired tokens, it is
// returned, otherwise void is returned.
fn peek(p: *parser, want: ltok...) (lex::token | error | void) = {
	assert(len(want) != 0);
	let word = false;
	for (let i = 0z; i < len(want); i += 1) {
		if (want[i] == ltok::WORD) {
			word = true;
		};
	};

	const tok = lex::peek(&p.lex, word)?;
	for (let i = 0z; i < len(want); i += 1) {
		if (want[i] == tok.0) {
			return tok;
		};
	};
};
07070100000028000081A400000000000000000000000166D8109200000168000000000000000000000000000000000000002C00000000rc-0+git.1725436050.2b2d211/parse/script.hause ast;
use io;

// Parses a list of [[ast::command]]s until [[io::EOF]] is encountered.
export fn parse_script(p: *parser) (ast::script | error) = {
	let cmds: ast::script = [];

	for (true) {
		const cmd = match (parse_commands(p)?) {
		case io::EOF =>
			break;
		case let cmd: ast::command =>
			yield cmd;
		};
		append(cmds, cmd);
	};

	return cmds;
};
07070100000029000081A400000000000000000000000166D81092000017AD000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/parse/value.hause ast;
use ast::{access_type};
use lex;
use lex::{ltok};
use io;
use strings;
use strconv;

// Parses a list of values.
export fn parse_value_list(p: *parser, lf: bool) ([]*ast::value | error) = {
	// XXX: Drop pointer from return value []*ast::value?
	let list: []*ast::value = [];

	for (true) {
		const tok = match (peek(p,
			ltok::DOLLAR,
			ltok::DOLLAR_POUND,
			ltok::DOLLAR_QUOTE,
			ltok::DOLLAR_SQUOTE,
			ltok::LPAREN,
			ltok::BACKTICK,
			ltok::ARGUMENT,
			ltok::STRING)?) {
		case let tok: lex::token =>
			yield tok;
		case void =>
			break;
		};

		const (val, _ws) = parse_value(p)?;
		append(list, alloc(val));

		if (lf) {
			if (!_ws && try(p, ltok::LF)? is lex::token) {
				ws(p, false)?;
				_ws = true;
			};
		};

		if (!_ws) {
			break;
		};
	};

	return list;
};

// Parses an [[ast::value]], returning true if there was trailing whitespace.
export fn parse_value(p: *parser, access: bool...) ((ast::value, bool) | error) = {
	const tok = want(p,
		ltok::DOLLAR,
		ltok::DOLLAR_POUND,
		ltok::DOLLAR_QUOTE,
		ltok::DOLLAR_SQUOTE,
		ltok::LPAREN,
		ltok::BACKTICK,
		ltok::LT,
		ltok::GT,
		ltok::ARGUMENT,
		ltok::STRING)?;

	const lval: ast::value = switch (tok.0) {
	case ltok::ARGUMENT =>
		yield strings::dup(tok.1): ast::argument;
	case ltok::STRING =>
		yield strings::dup(tok.1): ast::string;
	case ltok::DOLLAR, ltok::DOLLAR_POUND,
		ltok::DOLLAR_QUOTE, ltok::DOLLAR_SQUOTE =>
		lex::unlex(&p.lex, tok);
		yield parse_access(p)?;
	case ltok::LPAREN =>
		// Value list
		ws(p, false)?;
		for (try(p, ltok::LF) is lex::token) void;
		ws(p, false)?;
		let list = parse_value_list(p, true)?;
		ws(p, false)?;
		want(p, ltok::RPAREN)?;
		yield list;
	case ltok::BACKTICK =>
		lex::unlex(&p.lex, tok);
		yield parse_subscript(p)?;
	case =>
		abort();
	};

	let had_ws = ws(p, false)?;
	let is_access = len(access) > 0 && access[0] == true;
	if (!had_ws && !is_access && peek(p,
		ltok::DOLLAR,
		ltok::DOLLAR_POUND,
		ltok::DOLLAR_QUOTE,
		ltok::DOLLAR_SQUOTE,
		ltok::BACKTICK,
		ltok::ARGUMENT,
		ltok::STRING) is lex::token) {
		lex::unlex(&p.lex, (ltok::CARET, ""));
	};

	if (try(p, ltok::CARET)? is lex::token) {
		ws(p, false)?;

		const (rval, rval_ws) = parse_value(p)?;
		const val = (alloc(lval), alloc(rval)): ast::concat;
		return (val, rval_ws);
	};

	return (lval, had_ws);
};

// Parses an [[ast::access]] value.
fn parse_access(p: *parser) (ast::access | error) = {
	const sigil = want(p,
		ltok::DOLLAR,
		ltok::DOLLAR_POUND,
		ltok::DOLLAR_QUOTE,
		ltok::DOLLAR_SQUOTE)?.0;
	const var = want(p, ltok::WORD)?;

	const atype: access_type = switch (sigil) {
	case ltok::DOLLAR =>
		yield access_type::VAR;
	case ltok::DOLLAR_POUND =>
		yield access_type::LEN;
	case ltok::DOLLAR_QUOTE =>
		yield access_type::QUOTED;
	case ltok::DOLLAR_SQUOTE =>
		yield access_type::SQUOTED;
	case =>
		abort();
	};

	let access = ast::access {
		atype = atype,
		target = strings::dup(var.1),
		index = null,
		end = null,
	};

	if (atype == access_type::VAR && try(p, ltok::LPAREN)? is lex::token) {
		parse_access_range(p, &access)?;
		want(p, ltok::RPAREN)?;
	};

	return access;
};

// Parses an [[ast::access]] index or slice.
fn parse_access_range(p: *parser, access: *ast::access) (void | error) = {
	access.atype = access_type::INDEX;
	let had_dash = false;

	ws(p, false)?;

	const (ix, _) = parse_value(p, true)?;
	match (ix) {
	case ast::access =>
		// p.e. $var($index) or $var($start-$end) or $var($start - $end)
		access.index = alloc(ix);
	case let arg: ast::argument =>
		// p.e. $var(2-4) or $var(-$end), everything starting with a number
		// or a dash
		if (arg == "-") {
			// p.e. $var(- 4) or $var(- $end)
			access.index = alloc("1": ast::string: ast::value);
			access.end = alloc("0": ast::string: ast::value);
			had_dash = true;
		} else if (strings::contains(arg, '-')) {
			// p.e. $var(2-4) or $var(2-) or $var(-4)
			let tokens = strings::tokenize(arg, "-");
			let start = strings::next_token(&tokens) as str;
			if (start == "") {
				start = "1"; // start with first value
			};
			access.index = alloc(strings::dup(start): ast::string: ast::value);

			let end = strings::remaining_tokens(&tokens);
			if (end == "") {
				end = "0"; // "open end"
			};
			access.end = alloc(strings::dup(end): ast::string: ast::value);
			access.atype = access_type::SLICE;
			had_dash = true;
		} else {
			// p.e. $var(2) or $var(2 - 4)
			access.index = alloc(ix);
		};
	// error for all other types?
	};

	if (peek(p, ltok::RPAREN) is lex::token) {
		return;
	};

	access.atype = access_type::SLICE;

	// check for "-" and end index
	if (!had_dash) {
		const tok = try(p, ltok::ARGUMENT)?;
		if (tok is lex::token) {
			const arg = (tok as lex::token).1;
			if (arg != "-") {
				if (strings::sub(arg, 0, 1) != "-") {
					abort();
				};
				const rest = strings::sub(arg, 1, strings::end);
				access.end = alloc(strings::dup(rest): ast::string: ast::value);
			};
		};
	};

	ws(p, false)?;

	if (peek(p, ltok::RPAREN)? is lex::token) {
		if (access.end == null) {
			access.end = alloc("0": ast::string: ast::value);
		};
	} else {
		const (end, _) = parse_value(p, true)?;
		match (end) {
		case let acc: ast::access =>
			access.end = alloc(end);
		case let end: ast::argument =>
			if (end == "") {
				end = "0"; // "open end"
			};
			access.end = alloc(strings::dup(end): ast::string: ast::value);
		case =>
			abort(); // error?
		};
	};
};

// Parses an [[ast::subscript]] value.
fn parse_subscript(p: *parser) (ast::subscript | error) = {
	let ifs = "";

	want(p, ltok::BACKTICK)?;

	match (try(p, ltok::STRING)?) {
	case let tok: lex::token =>
		ifs = strings::dup(tok.1);
	case => void;
	};

	want(p, ltok::LBRACE)?;

	let cmds: []ast::command = [];
	for (true) {
		const cmd = match (parse_commands(p)?) {
		case io::EOF =>
			return mksyntaxerr(&p.lex, [], (ltok::EOF, ""));
		case let cmd: ast::command =>
			yield cmd;
		};

		append(cmds, cmd);

		allws(p)?;
		if (try(p, ltok::RBRACE)? is lex::token) {
			break;
		};
	};

	return ast::subscript {
		cmds = cmds,
		ifs = ifs,
	};
};
0707010000002A000081ED00000000000000000000000166D8109200000118000000000000000000000000000000000000002600000000rc-0+git.1725436050.2b2d211/run-tests#!./rc
npass=0
nfail=0
ntest=0

for (t in test/*.rc) {
	printf "%-30s..." $t
	if (./rc $t) {
		npass=`{expr $npass + 1}
		echo OK
	} else {
		nfail=`{expr $nfail + 1}
		echo FAIL
	}
	ntest=`{expr $ntest + 1}
}

echo
echo $ntest tests run, $npass passed, $nfail failed
exit $nfail
0707010000002B000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002100000000rc-0+git.1725436050.2b2d211/test0707010000002C000081A400000000000000000000000166D8109200000950000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/test/access.rc. test/lib/harness.rc

begin "Basic accesses"
@{
	x=42
	test $x -eq 42 || fail 'expected $x to equal 42'
}
end

begin "List index access"
@{
	x=(1 2 3 4 5)
	test $x(1) -eq 1 || fail 'expected $x(1) to equal 1'

	i=1
	while (test $i -le $#x) {
		test $i -eq $x($i) || fail 'unexpected value'
		i=`{expr $i + 1}
	}

	i=3
	test $i -eq $x( $i ) || fail 'unexpected value'
}
end

begin "List length access"
@{
	x=(1 2 3 4 5)
	test $#x -eq 5 || fail 'Expected $#x to equal 5'
}
end

begin "Quoted access"
@{
	x=(hello world foo bar)
	test $"x '=' "hello world foo bar" || fail \
		'Expected $"x to be joined with spaces'
	test $'x '=' "helloworldfoobar" || fail \
		'Expected $"x to be joined without spaces'
}
end

begin "String slice access"
@{
	x="ABCDE"
	test $x(2-4) "=" "BCD" || fail 'expected $x(2-4) to equal "BCD"'
	test $x(2-) "=" "BCDE" || fail 'expected $x(2-) to equal "BCDE"'
	test $x(-4) "=" "ABCD" || fail 'expected $x(-4) to equal "ABCD"'
	test $x(2 - 4) "=" "BCD" || fail 'expected $x(2 - 4) to equal "BCD"'
	test $x(2 -) "=" "BCDE" || fail 'expected $x(2 -) to equal "BCDE"'
	test $x(2 - ) "=" "BCDE" || fail 'expected $x(2 - ) to equal "BCDE"'
	test $x(- 4) "=" "ABCD" || fail 'expected $x(- 4) to equal "ABCD"'
	test $x( - 4) "=" "ABCD" || fail 'expected $x( - 4) to equal "ABCD"'

	start=2
	end=4
	test $x($start-$end) "=" "BCD" || fail 'expected $x($start-$end) to equal "BCD"'
	test $x($start-) "=" "BCDE" || fail 'expected $x($start-) to equal "BCDE"'
	test $x(-$end) "=" "ABCD" || fail 'expected $x(-$end) to equal "ABCD"'
	test $x($start - $end) "=" "BCD" || fail 'expected $x($start - $end) to equal "BCD"'
	test $x($start -) "=" "BCDE" || fail 'expected $x($start -) to equal "BCDE"'
	test $x(- $end) "=" "ABCD" || fail 'expected $x(- $end) to equal "ABCD"'

	test $x($start-4) "=" "BCD" || fail 'expected $x($start-) to equal "BCD"'
	test $x(2-$end) "=" "BCD" || fail 'expected $x(-$end) to equal "BCD"'

	test $x($start - 4) "=" "BCD" || fail 'expected $x($start-) to equal "BCD"'
	test $x(2 - $end) "=" "BCD" || fail 'expected $x(-$end) to equal "BCD"'
}
end

begin "List slice access"
@{
	x=(1 2 3 4 5)
	y=$x(2-4)
	test $"y "=" "2 3 4" || fail 'expected $"x(2-4) to equal "2 3 4"'

	y=$x(2-)
	test $"y "=" "2 3 4 5" || fail 'expected $"x(2-) to equal "2 3 4 5"'

	y=$x(-4)
	test $"y "=" "1 2 3 4" || fail 'expected $"x(-4) to equal "1 2 3 4"'
}
end

finish
0707010000002D000081A400000000000000000000000166D810920000039E000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/test/assign.rc. test/lib/harness.rc

begin "Basic assignments"
@{
	x=10
	test $x -eq 10 || fail 'expected $x to equal 10'

	x=20
	test $x -eq 20 || fail 'expected $x to equal 20'

	x = 30
	test $x -eq 30 || fail 'expected $x to equal 30'

	x =40
	test $x -eq 40 || fail 'expected $x to equal 40'

	x= 50
	test $x -eq 50 || fail 'expected $x to equal 50'

	x="60"
	test $x -eq 60 || fail 'expected $x to equal 60'

	x = "70"
	test $x -eq 70 || fail 'expected $x to equal 70'

	x ="80"
	test $x -eq 80 || fail 'expected $x to equal 80'

	x= "90"
	test $x -eq 90 || fail 'expected $x to equal 90'
}
end

begin "List assignments"
@{
	x=(1 2 3)
	test $x(1) -eq 1 || fail 'expected $x(1) to equal 1'
	test $x(2) -eq 2 || fail 'expected $x(2) to equal 2'
	test $x(3) -eq 3 || fail 'expected $x(3) to equal 3'
}
end

begin "Should not ovewrite $status"
@{
	x=`{false}
	test $status -ne 0 || fail "assign should not overwrite $status"
}
end

finish
0707010000002E000081A400000000000000000000000166D8109200000558000000000000000000000000000000000000002C00000000rc-0+git.1725436050.2b2d211/test/builtin.rc. test/lib/harness.rc

begin "."
@{
	. test/lib/source.rc foo bar baz
	test $foobar -eq 42 || fail "expected source to execute in parent context"
	test $#args -eq 4 || fail "expected args to be passed to sourced script"
	test $args(1) "=" test/lib/source.rc || fail
	test $args(2) "=" foo || fail
	test $args(3) "=" bar || fail
	test $args(4) "=" baz || fail
}
end

begin "cd"
@{
	cd
	test $PWD '=' $HOME || fail "$PWD != $HOME"
}
end

begin "cd <dir>"
@{
	prev=$PWD
	cd test/lib
	test $PWD '=' $prev/test/lib || fail "$PWD != $prev/test/lib"
}
end

begin "cd -"
@{
	prev=$PWD
	cd test/
	test $PWD '=' $prev/test || fail "$PWD = $prev/test"
	test $OLDPWD '=' $prev || fail "$OLDPWD != $prev"
	cd -
	test $PWD '=' $prev || fail "$PWD != $prev/test"
	test $OLDPWD '=' $prev/test || fail "$PWD != $prev/test"
}
end

begin "eval"
@{
	eval "x=1337"
	test $x -eq 1337 || fail
}
end

begin "exec"
@{
	hello=`{@exec printf "hello world\n"}
	test $hello "=" "hello world" || fail
}
end

begin "exit"
@{
	@{exit 42}
	test $status -eq 42 || fail
}
end

begin "export"
@{
	foobar=42
	export foobar
	env | grep foobar >/dev/null
	test $status -eq 0 || fail
}
end

begin "read"
@{
	fn genseq for (x in 1 2 3) echo $x
	genseq | {
		test `{read} -eq 1 || fail
		test `{read} -eq 2 || fail
		test `{read} -eq 3 || fail
		read >/dev/null
		test $status -eq 127 || fail
	}
}
end

finish
0707010000002F000081A400000000000000000000000166D81092000003B8000000000000000000000000000000000000002A00000000rc-0+git.1725436050.2b2d211/test/funcs.rc. test/lib/harness.rc

begin "Basic inline functions"
@{
	fn basic true
	basic || fail
}
end

begin "Command list functions"
@{
	fn list {
		x=10
		test $x -eq 10 || fail
		true
	}

	list || fail
}
end

begin "Simple parameters"
@{
	fn func {
		test $#* -eq 3 || fail
		test $0 '=' func || fail
		test $1 '=' arg1 || fail
		test $2 '=' arg2 || fail
		shift
		test $0 '=' arg1 || fail
		test $1 '=' arg2 || fail
	}

	func arg1 arg2
}
end

begin "Named parameters"
@{
	fn func(x y z) {
		test $#* -eq 5 || fail
		test $x -eq 1 || fail
		test $1 -eq 1 || fail
		test $y -eq 2 || fail
		test $2 -eq 2 || fail
		test $z -eq 3 || fail
		test $3 -eq 3 || fail
		test $4 -eq 4 || fail
	}

	func 1 2 3 4
}
end

begin "return"
@{
	x=0
	fn early_return {
		return
		x=1
	}
	early_return
	test $x -eq 0 || fail "expected return to terminate function"

	fn rvalue {
		return 42
	}
	rvalue
	test $status -eq 42 || fail "expected return value to be 42"
}
end

finish
07070100000030000041ED00000000000000000000000266D8109200000000000000000000000000000000000000000000002500000000rc-0+git.1725436050.2b2d211/test/lib07070100000031000081A400000000000000000000000166D81092000001AC000000000000000000000000000000000000003000000000rc-0+git.1725436050.2b2d211/test/lib/harness.rccurrent=""
npass=0
nfail=0
nbegin=0
nend=0
set -E

fn fail {
	shift && echo "($current)" Assertion failed: $*
	exit 1
}

fn pass true

fn begin(test) {
	current=$test
	nbegin=`{expr $nbegin + 1}
}

fn end {
	if (test $status -eq 0) {
		npass=`{expr $npass + 1}
	} else {
		nfail=`{expr $nfail + 1}
	}
	nend=`{expr $nend + 1}
}

fn finish {
	if (test $nbegin -ne $nend) {
		echo "warning: mismatched begin/end"
	}
	exit $nfail
}
07070100000032000081A400000000000000000000000166D8109200000012000000000000000000000000000000000000002F00000000rc-0+git.1725436050.2b2d211/test/lib/source.rcfoobar=42
args=$*
07070100000033000081A400000000000000000000000166D81092000002EC000000000000000000000000000000000000002A00000000rc-0+git.1725436050.2b2d211/test/loops.rc. test/lib/harness.rc

begin "Basic for loop"
@{
	fn loop {
		x=1
		for (arg) {
			test $arg -eq $x || fail
			x=`{expr $x + 1}
		}
	}
	loop 1 2 3 4 5
}
end

begin "for over list"
@{
	x=1
	for (item in (1 2 3 4 5)) {
		test $item -eq $x || fail
		x=`{expr $x + 1}
	}
}
end

begin "while loop"
@{
	x=0
	while (test $x -lt 5) {
		x=`{expr $x + 1}
	}
	test $x -eq 5 || fail
}
end

begin "break"
@{
	x=0
	while (test $x -lt 5) {
		if (test $x -eq 3) {
			break
		}
		x=`{expr $x + 1}
	}
	test $x -eq 3 || fail "Expected loop to terminate early"
}
end

begin "continue"
@{
	x=0
	y=0
	while (test $x -lt 5) {
		x=`{expr $x + 1}
		if (test $x -eq 3) {
			continue
		}
		y=`{expr $y + 1}
	}
	test $y -eq 4 || fail "Expected loop to continue"
}
end

finish
07070100000034000081A400000000000000000000000166D81092000002C9000000000000000000000000000000000000002800000000rc-0+git.1725436050.2b2d211/test/set.rc. test/lib/harness.rc

if (test $#TMPDIR -eq 0) {
	TMPDIR=/tmp
}

begin "set -e"
@{
	@{
		set -e
		false
		touch $TMPDIR/testfile
	}
	test -e $TMPDIR/testfile && {
		rm $TMPDIR/testfile
		fail 'expected set -e to terminate program on error'
	}
	pass
}
end

begin "set -E"
@{
	@{
		set -E
		false
		touch $TMPDIR/testfile
	}
	test -e $TMPDIR/testfile || fail 'expected set -E to ignore errors'
	rm $TMPDIR/testfile
}
end

begin "pipefail"
@{
	false | true
	test $status -ne 0 || fail 'expected pipe failure to propegate'

	true | false | true
	test $status -ne 0 || fail 'expected pipe failure to propegate'

	set -P
	false | true
	test $status -eq 0 || fail 'expected pipe failure to be suppressed'
}
end

finish
07070100000035000081A400000000000000000000000166D8109200000285000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/test/subscr.rc. test/lib/harness.rc

begin "Simple subscript"
@{
	x=`{echo hello world}
	test $x '=' "hello world" || fail 'expected $x to equal hello world'
}
end

begin "Simple IFS subscript"
@{
	x=`':'{echo 42:24}
	test $#x -eq 2 || fail 'expected $#x to equal 2'
	test $x(1) -eq 42 || fail 'expected $x(1) to equal 42'
	test $x(2) -eq 24 || fail 'expected $x(2) to equal 24'
}
end

begin "Multiple IFS separators"
@{
	ref=(12 34 56 78 90)
	x=`':;,'{echo "12:34,56,78;90"}
	test $#x -eq $#ref || fail 'expected $#x to equal reference'
	i=1
	for (val in $ref) {
		test $x($i) -eq $val || fail "expected x($i) to be $val"
		i=`{expr $i + 1}
	}
}
end

finish
07070100000036000081A400000000000000000000000166D8109200000181000000000000000000000000000000000000002B00000000rc-0+git.1725436050.2b2d211/test/switch.rc. test/lib/harness.rc

begin "switch"
@{
	out=`{
	switch (foobar) {
	case foo*
		echo 1
	case *bar
		echo 2
	default
		echo 3
	}
	}
	test $out -eq 1 || fail "expected switch to choose first suitable branch"
}
end

begin "default"
@{
	out=`{
	switch (foobar) {
	case baz
		echo 1
	default
		echo 2
	}
	}
	test $out -eq 2 || fail "expected switch to choose default branch"
}
end

finish
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!315 blocks
openSUSE Build Service is sponsored by