Compare commits

..

10 commits

57 changed files with 1956 additions and 705 deletions

29
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,29 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "gcc build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/bin/test",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "tasks",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}

11
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,11 @@
{
"files.associations": {
"*.ts": "typescript",
"*.asm": "python",
"stdio.h": "c",
"string_view": "c",
"state.h": "c",
"stack.h": "c",
"var_store.h": "c"
}
}

16
.vscode/tasks.json vendored Normal file
View file

@ -0,0 +1,16 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "tasks",
"type": "shell",
"command": "make test-debug",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

6
Dockerfile Normal file
View file

@ -0,0 +1,6 @@
FROM alpine:3.14
RUN apk add gcc
RUN apk add make
RUN mkdir /app
COPY ./ /app
ENTRYPOINT ["sleep", "infinity"]

674
LICENSE Normal file
View file

@ -0,0 +1,674 @@
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>.

View file

@ -6,12 +6,22 @@ TEST_SRCS_ENC := $(foreach DIR,src,$(patsubst $(DIR)/%,%,$(wildcard ./src/*.c)))
TEST_SRCS_ENC := $(filter-out %main.c, $(TEST_SRCS_ENC)) TEST_SRCS_ENC := $(filter-out %main.c, $(TEST_SRCS_ENC))
build: build:
cp src/config_env_main.h src/config_env.h
gcc src/* -o ./bin/main ${CXXFLAGS_WITHOUT_PKGS} gcc src/* -o ./bin/main ${CXXFLAGS_WITHOUT_PKGS}
test: test:
cp src/config_env_main.h src/config_env.h
gcc ${TEST_SRCS_ENC} ./tests/* -o ./bin/test ${CXXFLAGS_WITHOUT_PKGS} gcc ${TEST_SRCS_ENC} ./tests/* -o ./bin/test ${CXXFLAGS_WITHOUT_PKGS}
./bin/test ./bin/test
test-no-run: test-no-run: ./tests/*
cp src/config_env_main.h src/config_env.h
gcc ${TEST_SRCS_ENC} ./tests/* -o ./bin/test ${CXXFLAGS_WITHOUT_PKGS} gcc ${TEST_SRCS_ENC} ./tests/* -o ./bin/test ${CXXFLAGS_WITHOUT_PKGS}
test-debug: ./tests/*
cp src/config_env_main.h src/config_env.h
gcc -g ${TEST_SRCS_ENC} ./tests/* -o ./bin/test ${CXXFLAGS_WITHOUT_PKGS}
emscripten:
cp wasm/config_env_wasm.h src/config_env.h
emcc -O3 -s WASM=1 -s EXPORTED_RUNTIME_METHODS=ccall,cwrap,getValue,setValue \
./wasm/emscripten.c ${TEST_SRCS_ENC} -o wasm/langatator_adapter.js
sandbox: sandbox:
gcc ${TEST_SRCS_ENC} ./sandbox.c -o ./bin/sandbox ${CXXFLAGS_WITHOUT_PKGS} gcc ${TEST_SRCS_ENC} ./sandbox.c -o ./bin/sandbox ${CXXFLAGS_WITHOUT_PKGS}
./bin/sandbox ./bin/sandbox

167
README.md
View file

@ -1,13 +1,12 @@
# Langatator # Langatator
A very basic interpreted programming language. A very basic interpreted imperative programming language.
## Background ## Background
The goal of this project is to create a simple implementation of a BASIC-like language just to learn a few things along the way and practice my C programming skills. The goal of this project is to create a simple implementation of a BASIC-like language just to learn a few things along the way and practice my C programming skills.
No need to do complex things, just to create a simple interpreted language that can be used to do some arithmetics No need to do complex things, just to create a simple interpreted language that can be used to do some arithmetics and create for example a number guessing game.
and create for example a number guessing game.
I didn't really study how others languages works beforehand, I'm just guessing how I'm implementing things so that I can make mistakes to learn from. I didn't really study how others languages works beforehand, I'm just guessing how I'm implementing things so that I can make mistakes to learn from.
@ -18,34 +17,52 @@ I didn't really study how others languages works beforehand, I'm just guessing h
ToDo List: ToDo List:
- [X] pow operator - [X] feat: pow operator
- [X] binary operators - [X] feat: binary operators
- [X] implement basic math functions - [X] feat: basic math functions
- [X] implement random_int(min, max) - [X] feat: random_int(min, max)
- [X] implement print_number(message) - [X] feat: print_number(message)
- [X] add unit tests - [X] base of unit tests
- [X] allow to set variables - [X] feat: set variables
- [X] read line comments - [X] feat: read line comments
- [X] add modulus operator '%' - [X] feat: modulus operator '%'
- [ ] add support for multiple characters operators - [X] feat: input_number() std function
- [ ] add inclusive operators like '!=', '>=', '<=' - [X] feat: NULL type (dirty way to handle no returns and some errors)
- [ ] add input_number() std function - [X] feat: type() std function and others type checking functions
- [ ] add type() std function - [X] feat: ceil() and floor() std functions
- [ ] add ceil() and floor() std functions - [X] feat: base of the CLI
- [X] base of the CLI - [X] feat: process from a file
- [X] feat: if statements
- [X] feat: while statements (with break and continue)
- [ ] feat(Evaluator): multiple characters operators
- [ ] feat(Evaluator): inclusive operators like '!=', '>=', '<='
- [ ] feat: functions support
- [ ] feat(Evaluator): priority operators
- [ ] feat: multiline expressions
- [ ] feat: short hand if statement without 'end'
- [ ] feat: repeat statement
- [ ] feat: static string support (just for ui)
- [ ] feat: print_string function
- [ ] feat: basic number list support
- [ ] feat: fully features strings support
- [ ] feat: function to access to environment variables
- [ ] feat: hexadecimal and binary constants
- [X] feat: REPL environment
- [ ] feat: add history to REPL
- [ ] evaluate expression from stdin - [ ] evaluate expression from stdin
- [X] read a file - [X] feat: config header file
- [X] if statements - [X] ability to modify keywords and customize the lang
- [ ] while statements (with break and continue) - [ ] more config options
- [ ] add functions support
- [ ] add config header file
- [ ] ability to modify keywords and customize the lang
- [ ] add static string support (just for ui)
- [ ] add print_string function
- [ ] add basic number list support
- [ ] add fully features strings support
- [ ] add [classic problem solving](https://rosettacode.org) with code examples - [ ] add [classic problem solving](https://rosettacode.org) with code examples
- [ ] add Web Assembly support and publish a demo website - [ ] feat: web Assembly support and publish a demo website
- [ ] refactor: add 'Literal' struct with type and data
- [ ] refactor(Evaluator): if branching around token identification
- [ ] refactor(List): use malloc
- [ ] refactor: remove inconsistency on how functions returns error codes
## Installation ## Installation
@ -56,6 +73,17 @@ You will need to compile the code from source.
I use GNU Make with GCC, but I'm sure you can use any C compilers though you may need to edit some part of the code to cope with other compilers (eg. binary constants). I use GNU Make with GCC, but I'm sure you can use any C compilers though you may need to edit some part of the code to cope with other compilers (eg. binary constants).
## Build to Web assembly
I use emscripten.org
It would be great if I'm not using emscripten.
I have to find implementation for stdlib
## Unit testing
I try to have some sort of code coverage, you can run the unit tests by issuing `make test`
## The language ## The language
@ -141,89 +169,16 @@ abs(nb)
sqrt,sin,cos,exp,ln,log etc. sqrt,sin,cos,exp,ln,log etc.
print_number(nb) print_number(nb)
input_number() input_number()
ceil(nb)
floor(nb)
random_int(min, max) random_int(min, max)
random_float(min, max) random_float(min, max)
type(var) -> return the type of a var as int type(var) -> return the type of a var as int
is_int(var) is_null(var)
is_float(var) is_number(var)
print_string(str) print_string(str)
print_newline() print_newline()
print_ascii(nb) print_ascii(nb)
``` ```
# Evaluator (draft)
EDIT: that's not actually quite how I implemented the evaluator.
Map
componentList:
bytes steam
first byte is a uint8 representing the type of the component
then depending on the type of the component there is 0 or N bytes
components types:
- name: integer
size: 4 bytes (for int)
- name: open parenthesis
size: 0 bytes
- name: close parenthesis
size: 0 bytes
- name: float
size: 32 bytes (IEEE 754)
- name: operator
size: 1 byte (255 operators are possible)
- name: function designator
desc: id of a function
size: 2 bytes (65536 functions are possibles)
Example map of `9+(5*(8+6))`
lexed stream
-TYPE:NUMERAL
VALUE:9
-TYPE:OPERATOR
VALUE:PLUS
-TYPE:OPEN_PARENTHESIS
VALUE:NULL
-TYPE:NUMERAL
VALUE:5
-TYPE:OPERATOR
VALUE:TIMES
-TYPE:OPEN_PARENTHESIS
VALUE:NULL
-TYPE:NUMERAL
VALUE:8
-TYPE:OPERATOR
VALUE:PLUS
-TYPE:NUMERAL
VALUE:6
-TYPE:CLOSE_P
VALUE:NULL
-TYPE:CLOSE_P
VALUE:NULL
scan the whole lexed stream
So there will be a kind of time line with reference, a list of reference
in the begining we allocate two lists, one for the component type, one for the component values
## Dynamics lists
we allocate N bytes (uint_8 list[2048])
methods:
list_length()
list_assign_int(int index, int value)
list_assign_float(int index, float value)
list_assign_uint_8(int index, uint_8 value)
list_get_int(int index)
etc...

8
docker-compose.yml Normal file
View file

@ -0,0 +1,8 @@
version: "3.9"
services:
app:
build:
context: ./
volumes:
- ./:/app

77
draft.md Normal file
View file

@ -0,0 +1,77 @@
# Evaluator (draft)
EDIT: that's not actually quite how I implemented the evaluator.
Map
componentList:
bytes steam
first byte is a uint8 representing the type of the component
then depending on the type of the component there is 0 or N bytes
components types:
- name: integer
size: 4 bytes (for int)
- name: open parenthesis
size: 0 bytes
- name: close parenthesis
size: 0 bytes
- name: float
size: 32 bytes (IEEE 754)
- name: operator
size: 1 byte (255 operators are possible)
- name: function designator
desc: id of a function
size: 2 bytes (65536 functions are possibles)
Example map of `9+(5*(8+6))`
lexed stream
-TYPE:NUMERAL
VALUE:9
-TYPE:OPERATOR
VALUE:PLUS
-TYPE:OPEN_PARENTHESIS
VALUE:NULL
-TYPE:NUMERAL
VALUE:5
-TYPE:OPERATOR
VALUE:TIMES
-TYPE:OPEN_PARENTHESIS
VALUE:NULL
-TYPE:NUMERAL
VALUE:8
-TYPE:OPERATOR
VALUE:PLUS
-TYPE:NUMERAL
VALUE:6
-TYPE:CLOSE_P
VALUE:NULL
-TYPE:CLOSE_P
VALUE:NULL
scan the whole lexed stream
So there will be a kind of time line with reference, a list of reference
in the begining we allocate two lists, one for the component type, one for the component values
## Dynamics lists
we allocate N bytes (uint_8 list[2048])
methods:
list_length()
list_assign_int(int index, int value)
list_assign_float(int index, float value)
list_assign_uint_8(int index, uint_8 value)
list_get_int(int index)
etc...

View file

@ -0,0 +1,8 @@
definir index comme 0
tant que index < 10 faire
print_number(index)
definir index comme index + 1
fin
print_number(index)

23
examples/guessing.ltor Normal file
View file

@ -0,0 +1,23 @@
set i to 0
set toGuess to random_int(0, 100)
while 1 do
set guessed to input_number()
if i > 20 then
# do you really want to continue?
break
end
if guessed = toGuess then
# success
print_ascii(83)
break
end
if guessed < toGuess then
# too low
print_ascii(76)
end
if guessed > toGuess then
# too high
print_ascii(72)
end
set i to i+1
end

View file

@ -2,5 +2,4 @@
set a to input_number() set a to input_number()
set b to input_number() set b to input_number()
set res to a+b set res to a+b
print_number(res)
print_int(res)

View file

@ -1,2 +0,0 @@
# test modulus operator
print_number(20.2 % 10)

3
examples/sandbox2.ltor Normal file
View file

@ -0,0 +1,3 @@
print_number(2)
print_number(3)

304
log.err
View file

@ -1,304 +0,0 @@
./src/funcs.c:43:33: error: '#' is not followed by a macro parameter
43 | #define SIMPLE_FUNC_BINDING(name) ({\
| ^
./src/funcs.c:51:1: warning: return type defaults to int [-Wimplicit-int]
51 | SIMPLE_FUNC_BINDING(sqrt)
| ^~~~~~~~~~~~~~~~~~~
./src/funcs.c: In function SIMPLE_FUNC_BINDING:
./src/funcs.c:53:1: error: expected declaration specifiers before SIMPLE_FUNC_BINDING
53 | SIMPLE_FUNC_BINDING(exp)
| ^~~~~~~~~~~~~~~~~~~
./src/funcs.c:114:1: error: expected =, ,, ;, asm or __attribute__ before { token
114 | {
| ^
./src/funcs.c:121:1: warning: empty declaration
121 | struct FuncIntro {
| ^~~~~~
./src/funcs.c:129:8: error: parameter intros is initialized
129 | struct FuncIntro intros[] = {
| ^~~~~~~~~
./src/funcs.c:130:5: warning: braces around scalar initializer
130 | {"abs", &abs_impl, 1},
| ^
./src/funcs.c:130:5: note: (near initialization for intros)
./src/funcs.c:130:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
130 | {"abs", &abs_impl, 1},
| ^~~~~
./src/funcs.c:130:6: note: (near initialization for intros)
./src/funcs.c:130:13: warning: excess elements in scalar initializer
130 | {"abs", &abs_impl, 1},
| ^
./src/funcs.c:130:13: note: (near initialization for intros)
./src/funcs.c:130:24: warning: excess elements in scalar initializer
130 | {"abs", &abs_impl, 1},
| ^
./src/funcs.c:130:24: note: (near initialization for intros)
./src/funcs.c:132:5: warning: braces around scalar initializer
132 | {"sqrt", &sqrt_impl, 1},
| ^
./src/funcs.c:132:5: note: (near initialization for intros)
./src/funcs.c:132:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
132 | {"sqrt", &sqrt_impl, 1},
| ^~~~~~
./src/funcs.c:132:6: note: (near initialization for intros)
./src/funcs.c:132:15: error: sqrt_impl undeclared (first use in this function)
132 | {"sqrt", &sqrt_impl, 1},
| ^~~~~~~~~
./src/funcs.c:132:15: note: each undeclared identifier is reported only once for each function it appears in
./src/funcs.c:132:14: warning: excess elements in scalar initializer
132 | {"sqrt", &sqrt_impl, 1},
| ^
./src/funcs.c:132:14: note: (near initialization for intros)
./src/funcs.c:132:26: warning: excess elements in scalar initializer
132 | {"sqrt", &sqrt_impl, 1},
| ^
./src/funcs.c:132:26: note: (near initialization for intros)
./src/funcs.c:132:5: warning: excess elements in scalar initializer
132 | {"sqrt", &sqrt_impl, 1},
| ^
./src/funcs.c:132:5: note: (near initialization for intros)
./src/funcs.c:133:5: warning: braces around scalar initializer
133 | {"exp", &exp_impl, 1},
| ^
./src/funcs.c:133:5: note: (near initialization for intros)
./src/funcs.c:133:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
133 | {"exp", &exp_impl, 1},
| ^~~~~
./src/funcs.c:133:6: note: (near initialization for intros)
./src/funcs.c:133:14: error: exp_impl undeclared (first use in this function)
133 | {"exp", &exp_impl, 1},
| ^~~~~~~~
./src/funcs.c:133:13: warning: excess elements in scalar initializer
133 | {"exp", &exp_impl, 1},
| ^
./src/funcs.c:133:13: note: (near initialization for intros)
./src/funcs.c:133:24: warning: excess elements in scalar initializer
133 | {"exp", &exp_impl, 1},
| ^
./src/funcs.c:133:24: note: (near initialization for intros)
./src/funcs.c:133:5: warning: excess elements in scalar initializer
133 | {"exp", &exp_impl, 1},
| ^
./src/funcs.c:133:5: note: (near initialization for intros)
./src/funcs.c:135:5: warning: braces around scalar initializer
135 | {"sin", &sin_impl, 1},
| ^
./src/funcs.c:135:5: note: (near initialization for intros)
./src/funcs.c:135:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
135 | {"sin", &sin_impl, 1},
| ^~~~~
./src/funcs.c:135:6: note: (near initialization for intros)
./src/funcs.c:135:14: error: sin_impl undeclared (first use in this function)
135 | {"sin", &sin_impl, 1},
| ^~~~~~~~
./src/funcs.c:135:13: warning: excess elements in scalar initializer
135 | {"sin", &sin_impl, 1},
| ^
./src/funcs.c:135:13: note: (near initialization for intros)
./src/funcs.c:135:24: warning: excess elements in scalar initializer
135 | {"sin", &sin_impl, 1},
| ^
./src/funcs.c:135:24: note: (near initialization for intros)
./src/funcs.c:135:5: warning: excess elements in scalar initializer
135 | {"sin", &sin_impl, 1},
| ^
./src/funcs.c:135:5: note: (near initialization for intros)
./src/funcs.c:136:5: warning: braces around scalar initializer
136 | {"cos", &cos_impl, 1},
| ^
./src/funcs.c:136:5: note: (near initialization for intros)
./src/funcs.c:136:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
136 | {"cos", &cos_impl, 1},
| ^~~~~
./src/funcs.c:136:6: note: (near initialization for intros)
./src/funcs.c:136:14: error: cos_impl undeclared (first use in this function); did you mean abs_impl?
136 | {"cos", &cos_impl, 1},
| ^~~~~~~~
| abs_impl
./src/funcs.c:136:13: warning: excess elements in scalar initializer
136 | {"cos", &cos_impl, 1},
| ^
./src/funcs.c:136:13: note: (near initialization for intros)
./src/funcs.c:136:24: warning: excess elements in scalar initializer
136 | {"cos", &cos_impl, 1},
| ^
./src/funcs.c:136:24: note: (near initialization for intros)
./src/funcs.c:136:5: warning: excess elements in scalar initializer
136 | {"cos", &cos_impl, 1},
| ^
./src/funcs.c:136:5: note: (near initialization for intros)
./src/funcs.c:137:5: warning: braces around scalar initializer
137 | {"tan", &tan_impl, 1},
| ^
./src/funcs.c:137:5: note: (near initialization for intros)
./src/funcs.c:137:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
137 | {"tan", &tan_impl, 1},
| ^~~~~
./src/funcs.c:137:6: note: (near initialization for intros)
./src/funcs.c:137:14: error: tan_impl undeclared (first use in this function)
137 | {"tan", &tan_impl, 1},
| ^~~~~~~~
./src/funcs.c:137:13: warning: excess elements in scalar initializer
137 | {"tan", &tan_impl, 1},
| ^
./src/funcs.c:137:13: note: (near initialization for intros)
./src/funcs.c:137:24: warning: excess elements in scalar initializer
137 | {"tan", &tan_impl, 1},
| ^
./src/funcs.c:137:24: note: (near initialization for intros)
./src/funcs.c:137:5: warning: excess elements in scalar initializer
137 | {"tan", &tan_impl, 1},
| ^
./src/funcs.c:137:5: note: (near initialization for intros)
./src/funcs.c:138:5: warning: braces around scalar initializer
138 | {"ln", &ln_impl, 1},
| ^
./src/funcs.c:138:5: note: (near initialization for intros)
./src/funcs.c:138:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
138 | {"ln", &ln_impl, 1},
| ^~~~
./src/funcs.c:138:6: note: (near initialization for intros)
./src/funcs.c:138:13: error: ln_impl undeclared (first use in this function)
138 | {"ln", &ln_impl, 1},
| ^~~~~~~
./src/funcs.c:138:12: warning: excess elements in scalar initializer
138 | {"ln", &ln_impl, 1},
| ^
./src/funcs.c:138:12: note: (near initialization for intros)
./src/funcs.c:138:22: warning: excess elements in scalar initializer
138 | {"ln", &ln_impl, 1},
| ^
./src/funcs.c:138:22: note: (near initialization for intros)
./src/funcs.c:138:5: warning: excess elements in scalar initializer
138 | {"ln", &ln_impl, 1},
| ^
./src/funcs.c:138:5: note: (near initialization for intros)
./src/funcs.c:139:5: warning: braces around scalar initializer
139 | {"log", &log_impl, 1},
| ^
./src/funcs.c:139:5: note: (near initialization for intros)
./src/funcs.c:139:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
139 | {"log", &log_impl, 1},
| ^~~~~
./src/funcs.c:139:6: note: (near initialization for intros)
./src/funcs.c:139:14: error: log_impl undeclared (first use in this function)
139 | {"log", &log_impl, 1},
| ^~~~~~~~
./src/funcs.c:139:13: warning: excess elements in scalar initializer
139 | {"log", &log_impl, 1},
| ^
./src/funcs.c:139:13: note: (near initialization for intros)
./src/funcs.c:139:24: warning: excess elements in scalar initializer
139 | {"log", &log_impl, 1},
| ^
./src/funcs.c:139:24: note: (near initialization for intros)
./src/funcs.c:139:5: warning: excess elements in scalar initializer
139 | {"log", &log_impl, 1},
| ^
./src/funcs.c:139:5: note: (near initialization for intros)
./src/funcs.c:141:5: warning: braces around scalar initializer
141 | {"max", &max_impl, 2},
| ^
./src/funcs.c:141:5: note: (near initialization for intros)
./src/funcs.c:141:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
141 | {"max", &max_impl, 2},
| ^~~~~
./src/funcs.c:141:6: note: (near initialization for intros)
./src/funcs.c:141:14: error: max_impl undeclared (first use in this function)
141 | {"max", &max_impl, 2},
| ^~~~~~~~
./src/funcs.c:141:13: warning: excess elements in scalar initializer
141 | {"max", &max_impl, 2},
| ^
./src/funcs.c:141:13: note: (near initialization for intros)
./src/funcs.c:141:24: warning: excess elements in scalar initializer
141 | {"max", &max_impl, 2},
| ^
./src/funcs.c:141:24: note: (near initialization for intros)
./src/funcs.c:141:5: warning: excess elements in scalar initializer
141 | {"max", &max_impl, 2},
| ^
./src/funcs.c:141:5: note: (near initialization for intros)
./src/funcs.c:142:5: warning: braces around scalar initializer
142 | {"get_pi", &get_pi_impl, 0},
| ^
./src/funcs.c:142:5: note: (near initialization for intros)
./src/funcs.c:142:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
142 | {"get_pi", &get_pi_impl, 0},
| ^~~~~~~~
./src/funcs.c:142:6: note: (near initialization for intros)
./src/funcs.c:142:17: error: get_pi_impl undeclared (first use in this function)
142 | {"get_pi", &get_pi_impl, 0},
| ^~~~~~~~~~~
./src/funcs.c:142:16: warning: excess elements in scalar initializer
142 | {"get_pi", &get_pi_impl, 0},
| ^
./src/funcs.c:142:16: note: (near initialization for intros)
./src/funcs.c:142:30: warning: excess elements in scalar initializer
142 | {"get_pi", &get_pi_impl, 0},
| ^
./src/funcs.c:142:30: note: (near initialization for intros)
./src/funcs.c:142:5: warning: excess elements in scalar initializer
142 | {"get_pi", &get_pi_impl, 0},
| ^
./src/funcs.c:142:5: note: (near initialization for intros)
./src/funcs.c:143:5: warning: braces around scalar initializer
143 | {"", 0, 0}
| ^
./src/funcs.c:143:5: note: (near initialization for intros)
./src/funcs.c:143:6: warning: initialization of struct FuncIntro * from incompatible pointer type char * [-Wincompatible-pointer-types]
143 | {"", 0, 0}
| ^~
./src/funcs.c:143:6: note: (near initialization for intros)
./src/funcs.c:143:10: warning: excess elements in scalar initializer
143 | {"", 0, 0}
| ^
./src/funcs.c:143:10: note: (near initialization for intros)
./src/funcs.c:143:13: warning: excess elements in scalar initializer
143 | {"", 0, 0}
| ^
./src/funcs.c:143:13: note: (near initialization for intros)
./src/funcs.c:143:5: warning: excess elements in scalar initializer
143 | {"", 0, 0}
| ^
./src/funcs.c:143:5: note: (near initialization for intros)
./src/funcs.c:146:12: error: storage class specified for parameter nbOfFuncs
146 | static int nbOfFuncs = sizeof(intros)/sizeof(struct FuncIntro);
| ^~~~~~~~~
./src/funcs.c:146:1: error: parameter nbOfFuncs is initialized
146 | static int nbOfFuncs = sizeof(intros)/sizeof(struct FuncIntro);
| ^~~~~~
./src/funcs.c:146:30: warning: sizeof on array function parameter intros will return size of struct FuncIntro * [-Wsizeof-array-argument]
146 | static int nbOfFuncs = sizeof(intros)/sizeof(struct FuncIntro);
| ^
./src/funcs.c:129:18: note: declared here
129 | struct FuncIntro intros[] = {
| ^~~~~~
./src/funcs.c:152:1: error: expected =, ,, ;, asm or __attribute__ before { token
152 | {
| ^
./src/funcs.c:162:1: error: expected =, ,, ;, asm or __attribute__ before { token
162 | {
| ^
./src/funcs.c:51:1: warning: type of sqrt defaults to int [-Wimplicit-int]
51 | SIMPLE_FUNC_BINDING(sqrt)
| ^~~~~~~~~~~~~~~~~~~
./src/funcs.c:146:12: error: declaration for parameter nbOfFuncs but no such parameter
146 | static int nbOfFuncs = sizeof(intros)/sizeof(struct FuncIntro);
| ^~~~~~~~~
./src/funcs.c:129:18: error: declaration for parameter intros but no such parameter
129 | struct FuncIntro intros[] = {
| ^~~~~~
./src/funcs.c:196: error: expected { at end of input
./src/funcs.c:51:1: warning: unused parameter sqrt [-Wunused-parameter]
51 | SIMPLE_FUNC_BINDING(sqrt)
| ^~~~~~~~~~~~~~~~~~~
./src/funcs.c:146:12: warning: unused parameter nbOfFuncs [-Wunused-parameter]
146 | static int nbOfFuncs = sizeof(intros)/sizeof(struct FuncIntro);
| ^~~~~~~~~
./src/funcs.c:196: warning: control reaches end of non-void function [-Wreturn-type]
./src/number_parsing.c: In function parse_clean_positive_integer:
./src/number_parsing.c:21:29: warning: binary constants are a C2X feature or GCC extension
21 | (numeralIndex & 0b001111)
| ^~~~~~~~
make: *** [Makefile:11: test] Error 1

View file

@ -1,19 +1,39 @@
// #include <stdio.h>
// #include "./src/types.h"
// #include "./src/list.h"
// #include "./src/number_parsing.h"
// #include "./src/funcs.h"
// #include "./src/utils.h"
// #include "./src/var_store.h"
// #include "./src/line_processing.h"
// #include "./src/state.h"
// #include <stdlib.h>
// #include <sys/time.h>
// #include <stddef.h>
#include <stdio.h> #include <stdio.h>
#include "./src/types.h"
#include "./src/list.h" // #define printf_wrap(f_, ...) \
#include "./src/number_parsing.h" // { \
#include "./src/funcs.h" // printf_wrap("T=%d \t", (unsigned) time(NULL)); \
#include "./src/utils.h" // printf_wrap((f_), ##__VA_ARGS__); \
#include "./src/var_store.h" // };
#include "./src/line_processing.h"
#include "./src/state.h" #define eprintf_wrap(template, ...) printf_wrap(template, ##__VA_ARGS__);
#include <stdlib.h>
int main () { int main () {
struct VariableStore* store = var_store_init();
printf("%d", var_store_hash_name(store, "var")); eprintf_wrap("Hello %d %s \n", 13, "World");
// struct VariableStore* store = var_store_init();
// printf_wrap("%d", var_store_hash_name(store, "print_number index"));
// int i = -1;
// if (i < 0) {
// printf_wrap("lol jpp \n");
// }
return 0; return 0;
// struct List l1; //struct List l1;
// short val = 17; // short val = 17;
// list_set(&l1, 0, TYPE_VAR_NAME, &val); // list_set(&l1, 0, TYPE_VAR_NAME, &val);
@ -24,32 +44,32 @@ int main () {
// int yes = 1234; // int yes = 1234;
// int dst = 0; // int dst = 0;
// memcpy(&dst, &yes, 4); // memcpy(&dst, &yes, 4);
// printf("yes: %d \n", dst); // printf_wrap("yes: %d \n", dst);
//struct VariableStore* store = var_store_init(); //struct VariableStore* store = var_store_init();
// int hashRes = var_store_hash_name(store, "HelloWorld++"); // int hashRes = var_store_hash_name(store, "HelloWorld++");
// printf("hashRes: %d \n", hashRes); // printf_wrap("hashRes: %d \n", hashRes);
// int val = 1234; // int val = 1234;
// var_store_set(store, "foo", TYPE_INT, &val); // var_store_set(store, "foo", TYPE_INT, &val);
// var_store_get_key(store, "while i < 10 then"); // var_store_get_key(store, "while i < 10 then");
//printf("Pos of var: %d \n", var_store_get_pos(store, "foo")); //printf_wrap("Pos of var: %d \n", var_store_get_pos(store, "foo"));
//byte type = var_store_get_type(store, "foo"); //byte type = var_store_get_type(store, "foo");
//printf("Type of var: %d \n", type); //printf_wrap("Type of var: %d \n", type);
//int key = var_store_get_pos(store, "foo"); //int key = var_store_get_pos(store, "foo");
//printf("size of type %d \n", get_size_of_type(store->container[key].type)); //printf_wrap("size of type %d \n", get_size_of_type(store->container[key].type));
//printf("%d \n", *((int*) store->container[key].dataPtr)); //printf_wrap("%d \n", *((int*) store->container[key].dataPtr));
// int val2 = 0; // int val2 = 0;
// var_store_copy(store, "foo", &val2); // var_store_copy(store, "foo", &val2);
// printf("Value of var: %d \n", val2); // printf_wrap("Value of var: %d \n", val2);
// printf("==== \n"); // printf_wrap("==== \n");
// printf("==== \n"); // printf_wrap("==== \n");
// char* lines = "# hello world\n" // char* lines = "# hello world\n"
// "set x to 5\n" // "set x to 5\n"
@ -59,17 +79,17 @@ int main () {
// "end\n" // "end\n"
// "\n"; // "\n";
char* lines1 = "set x to 5\n" // char* lines1 = "set x to 5\n"
"set y to 1\n" // "set y to 1\n"
"if !(x+y = 6) then\n" // "if !(x+y = 6) then\n"
" print_number(x+y)\n" // " print_number(x+y)\n"
"end\n" // "end\n"
"\n"; // "\n";
printf("%s", lines1); // printf_wrap("%s", lines1);
struct StateContainer* state = state_init(); // struct StateContainer* state = state_init();
process_script(state, lines1); // process_script(state, lines1);
// struct List l1; // struct List l1;
@ -91,20 +111,20 @@ int main () {
// void* ptr = &res; // void* ptr = &res;
// printf("%d\n", sizeof(ptr)); // printf_wrap("%d\n", sizeof(ptr));
// int found = identify_func_name("ABS"); // int found = identify_func_name("ABS");
// printf("found: %d \n", found); // printf_wrap("found: %d \n", found);
// unsigned char argsType[1] = { TYPE_FLOAT }; // unsigned char argsType[1] = { TYPE_FLOAT };
// int argsVals[1] = { get_int_rep_from_float(-3.145) }; // int argsVals[1] = { get_int_rep_from_float(-3.145) };
// int resVal = 0; // int resVal = 0;
// unsigned char resType = 0; // unsigned char resType = 0;
// execute_func(found, 1, argsType, argsVals, &resVal, &resType); // execute_func(found, 1, argsType, argsVals, &resVal, &resType);
// printf("func res type: %d \n", resType); // printf_wrap("func res type: %d \n", resType);
// printf("func res: %f \n", get_float_from_int_rep(resVal)); // printf_wrap("func res: %f \n", get_float_from_int_rep(resVal));
// int stat = parse_float("1052.254", &res); // int stat = parse_float("1052.254", &res);
// printf("float parsing stat: %d \n", stat); // printf_wrap("float parsing stat: %d \n", stat);
// printf("final float: %f \n", res); // printf_wrap("final float: %f \n", res);
} }

View file

@ -1,6 +1,57 @@
#include "./config_env.h"
//#define printf_wrap(template,...) printf_wrap(template, ##__VA_ARGS__);
#define getline_wrap(...) getline(__VA_ARGS__);
#ifndef G_CONFIG_H_ #ifndef G_CONFIG_H_
#define G_CONFIG_H_ #define G_CONFIG_H_
#define G_DEBUG_LEVEL 0 #define PRINT_METHOD_CLASSIC 0
#define PRINT_METHOD_WASM 1
// #define CONFIG_PRINT_METHOD
#define PRESET_ENGLISH 0
#define PRESET_FRENCH 1
// 0: no logs; 1: medium debug; 2: full debug
#define G_DEBUG_LEVEL 2
#define SYNTAX_PRESET PRESET_ENGLISH
// Define your own custom syntax here
#if SYNTAX_PRESET == PRESET_ENGLISH
#define SYNTAX_END "end"
#define SYNTAX_EXIT "exit"
#define SYNTAX_SET_START "set"
#define SYNTAX_SET_STOP "to"
#define SYNTAX_IF_START "if"
#define SYNTAX_IF_STOP "then"
#define SYNTAX_WHILE_START "while"
#define SYNTAX_WHILE_STOP "do"
#define SYNTAX_CONTINUE "continue"
#define SYNTAX_BREAK "break"
#endif
#if SYNTAX_PRESET == PRESET_FRENCH
#define SYNTAX_END "fin"
#define SYNTAX_EXIT "sortir"
#define SYNTAX_SET_START "definir"
#define SYNTAX_SET_STOP "comme"
#define SYNTAX_IF_START "si"
#define SYNTAX_IF_STOP "alors"
#define SYNTAX_WHILE_START "tant que"
#define SYNTAX_WHILE_STOP "faire"
#define SYNTAX_CONTINUE "continuer"
// JPP
#define SYNTAX_BREAK "casser"
#endif
#endif #endif

2
src/config_env.h Normal file
View file

@ -0,0 +1,2 @@
// the config file for main and test
#define PRINT_MODE 0

2
src/config_env_main.h Normal file
View file

@ -0,0 +1,2 @@
// the config file for main and test
#define PRINT_MODE 0

View file

@ -49,7 +49,7 @@ int evaluator_reduce_operator_pattern(struct List* evalList) {
if (operateStatus != 0) { if (operateStatus != 0) {
// the pattern that matched, did not worked as expected // the pattern that matched, did not worked as expected
// this is a failure // this is a failure
printf("ERR Evaluator: cannot operate \n"); printf_wrap("ERR Evaluator: cannot operate \n");
return 400; return 400;
} }
@ -64,7 +64,7 @@ int evaluator_reduce_operator_pattern(struct List* evalList) {
list_delete(evalList, patternPos+1); list_delete(evalList, patternPos+1);
list_delete(evalList, patternPos+1); list_delete(evalList, patternPos+1);
//printf("END OF THE FIRST OPERATION \n"); //printf_wrap("END OF THE FIRST OPERATION \n");
//list_print(&evalList); //list_print(&evalList);
// so we reduced an expression, return 0 // so we reduced an expression, return 0
@ -105,7 +105,7 @@ int evaluator_reduce_minus_pattern(struct List* evalList) {
unsigned char typeRes = 0; unsigned char typeRes = 0;
int operateStatus = operate('*', TYPE_INT, -1, type, val, &typeRes, &res); int operateStatus = operate('*', TYPE_INT, -1, type, val, &typeRes, &res);
if (operateStatus != 0) { if (operateStatus != 0) {
printf("ERR Evaluator: cannot operate \n"); printf_wrap("ERR Evaluator: cannot operate \n");
return 400; return 400;
} }
@ -148,7 +148,7 @@ int evaluator_reduce_not_pattern(struct List* evalList) {
byte typeRes = 0; byte typeRes = 0;
int operateStatus = operate('!', 0, 0, type, val, &typeRes, &res); int operateStatus = operate('!', 0, 0, type, val, &typeRes, &res);
if (operateStatus != 0) { if (operateStatus != 0) {
printf("ERR Evaluator: cannot operate \n"); printf_wrap("ERR Evaluator: cannot operate \n");
return 400; return 400;
} }
@ -170,7 +170,7 @@ int evaluator_reduce_parenthesis_pattern(struct List* evalList) {
if ( if (
((i >= 1 && list_get_type(evalList, i-1) != TYPE_FUNC_NAME) || (i == 0)) && ((i >= 1 && list_get_type(evalList, i-1) != TYPE_FUNC_NAME) || (i == 0)) &&
list_get_type(evalList, i) == TYPE_OPEN_PARENTHESIS && list_get_type(evalList, i) == TYPE_OPEN_PARENTHESIS &&
is_type_number(list_get_type(evalList, i+1)) && is_type_literal(list_get_type(evalList, i+1)) &&
list_get_type(evalList, i+2) == TYPE_CLOSE_PARENTHESIS list_get_type(evalList, i+2) == TYPE_CLOSE_PARENTHESIS
) { ) {
patternPos = i; patternPos = i;
@ -208,7 +208,7 @@ int evaluator_reduce_var(struct StateContainer* state, struct List* evalList) {
byte type = var_store_get_type_from_key(state->varStore, varKey); byte type = var_store_get_type_from_key(state->varStore, varKey);
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("Going to reduce var key %d at pos %d\n", patternPos); if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("Going to reduce var key %d at pos %d\n", varKey, patternPos);
byte varVal[get_size_of_type(type)]; byte varVal[get_size_of_type(type)];
var_store_copy_from_key(state->varStore, varKey, &varVal); var_store_copy_from_key(state->varStore, varKey, &varVal);
@ -268,7 +268,7 @@ int evaluator_reduce_function_call(struct List* evalList, int initialPosition) {
// two case: either we have another arguments or we have a closing parenthesis // two case: either we have another arguments or we have a closing parenthesis
while (1) { while (1) {
if (argsLen > 16) { if (argsLen > 16) {
printf("ERR Evaluator: too many arguments passed to func (max out the limit) \n"); printf_wrap("ERR Evaluator: too many arguments passed to func (max out the limit) \n");
return 100; return 100;
} }
if ( if (
@ -288,7 +288,7 @@ int evaluator_reduce_function_call(struct List* evalList, int initialPosition) {
} }
if ( if (
is_type_number(list_get_type(evalList, pos)) && is_type_literal(list_get_type(evalList, pos)) &&
list_get_type(evalList, pos+1) == TYPE_COMMA list_get_type(evalList, pos+1) == TYPE_COMMA
) { ) {
// this is a new argument // this is a new argument
@ -297,7 +297,7 @@ int evaluator_reduce_function_call(struct List* evalList, int initialPosition) {
continue; continue;
} }
if ( if (
is_type_number(list_get_type(evalList, pos)) && is_type_literal(list_get_type(evalList, pos)) &&
list_get_type(evalList, pos+1) == TYPE_CLOSE_PARENTHESIS list_get_type(evalList, pos+1) == TYPE_CLOSE_PARENTHESIS
) { ) {
// we didn't match the last pattern so it's the last argument // we didn't match the last pattern so it's the last argument
@ -335,16 +335,16 @@ int evaluator_reduce_function_call(struct List* evalList, int initialPosition) {
// now we can delete in the list from pos+1 patternPos to pos // now we can delete in the list from pos+1 patternPos to pos
// just delete N-1 times where N is the number of components in the func call // just delete N-1 times where N is the number of components in the func call
//printf("start: %d, end: %d \n", patternPos, pos); //printf_wrap("start: %d, end: %d \n", patternPos, pos);
//printf("patternPos: %d, pos: %d \n", patternPos, pos); //printf_wrap("patternPos: %d, pos: %d \n", patternPos, pos);
for (int j = 0; j < (pos-patternPos); j++) { for (int j = 0; j < (pos-patternPos); j++) {
list_delete(evalList, patternPos); list_delete(evalList, patternPos);
} }
//printf("list report after deleting after applying a func \n"); //printf_wrap("list report after deleting after applying a func \n");
//list_print(evalList); //list_print(evalList);
//printf("patternPos: %d, resType: %d \n", patternPos, resType); //printf_wrap("patternPos: %d, resType: %d \n", patternPos, resType);
list_set(evalList, patternPos, resType, &resVal); list_set(evalList, patternPos, resType, &resVal);
@ -402,12 +402,12 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
// display the partition // display the partition
if (EVALUATOR_DEBUG_LEVEL >= 2) { if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("partitionPtr: %d \n", partitionPtr); printf_wrap("partitionPtr: %d \n", partitionPtr);
} }
for (int j = 0; j < partitionPtr; j++) { for (int j = 0; j < partitionPtr; j++) {
if (EVALUATOR_DEBUG_LEVEL >= 2) { if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("start %d ", partitionStartPos[j]); printf_wrap("start %d ", partitionStartPos[j]);
printf("stop %d ", partitionStopPos[j]); printf_wrap("stop %d ", partitionStopPos[j]);
} }
int len = partitionStopPos[j] - partitionStartPos[j]; int len = partitionStopPos[j] - partitionStartPos[j];
@ -419,7 +419,7 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
} }
buff[len] = 0; buff[len] = 0;
if (EVALUATOR_DEBUG_LEVEL >= 2) { if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("content %s \n", buff); printf_wrap("content %s \n", buff);
} }
} }
@ -441,29 +441,29 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
parenthesisCount--; parenthesisCount--;
} }
if (parenthesisCount < 0) { if (parenthesisCount < 0) {
printf("ERR Evaluator: bad parenthesizing \n"); printf_wrap("ERR Evaluator: bad parenthesizing \n");
return 100; return 100;
} }
} }
if (parenthesisCount > 0) { if (parenthesisCount > 0) {
// there is an open parenthesis, so it's an error // there is an open parenthesis, so it's an error
printf("ERR Evaluator: invalid parenthesis stack \n"); printf_wrap("ERR Evaluator: invalid parenthesis stack \n");
return 100; return 100;
} }
struct List evalList; struct List evalList;
// NOTICE: for some reason the struct don't reset after a usage // NOTICE: for some reason the struct don't reset after a usage
list_reset(&evalList); list_reset(&evalList);
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("\n - constructing list \n"); if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("\n - constructing list \n");
// initializing the evaluation list // initializing the evaluation list
for (int j = 0; j < partitionPtr; j++) { for (int j = 0; j < partitionPtr; j++) {
int startPos = partitionStartPos[j]; int startPos = partitionStartPos[j];
int stopPos = partitionStopPos[j]; int stopPos = partitionStopPos[j];
if (EVALUATOR_DEBUG_LEVEL >= 2) { if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("=== %d\n", j); printf_wrap("=== %d\n", j);
printf("startPos %d, stopPos %d\n", startPos, stopPos); printf_wrap("startPos %d, stopPos %d\n", startPos, stopPos);
} }
int len = stopPos - startPos; int len = stopPos - startPos;
@ -471,15 +471,11 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
int startTrimOffset = 0; int startTrimOffset = 0;
int stopTrimOffset = 0; int stopTrimOffset = 0;
for (int z = 0; z < len; z++) { for (int z = 0; z < len; z++) {
if (inputStr[startPos+z] != ' ') { if (inputStr[startPos+z] != ' ') break;
break;
}
startTrimOffset++; startTrimOffset++;
} }
for (int z = 1; z < len; z++) { for (int z = 1; z < len; z++) {
if (inputStr[stopPos-z] != ' ') { if (inputStr[stopPos-z] != ' ') break;
break;
}
stopTrimOffset++; stopTrimOffset++;
} }
startPos += startTrimOffset; startPos += startTrimOffset;
@ -496,13 +492,11 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
buff[len] = 0; // terminate the buff buff[len] = 0; // terminate the buff
// TODO: SPLIT INTO A FUNCTION "identify_token(char* str)" // TODO: SPLIT INTO A FUNCTION "identify_token(char* str)"
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("buff: '%s' \n", buff); if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("buff: '%s' \n", buff);
char dumbValue = (char) 0; char dumbValue = (char) 0;
if (buff[0] == '\0') { if (buff[0] == '\0') continue;
continue;
}
if (len == 1 && buff[0] == '(') { if (len == 1 && buff[0] == '(') {
list_set(&evalList, evalList.num_elements, TYPE_OPEN_PARENTHESIS, &dumbValue); list_set(&evalList, evalList.num_elements, TYPE_OPEN_PARENTHESIS, &dumbValue);
continue; continue;
@ -516,7 +510,7 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
continue; continue;
} }
if (len == 1 && is_operator(buff[0])) { if (len == 1 && is_operator(buff[0])) {
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("found op\n"); if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("found op\n");
char opValue = buff[0]; char opValue = buff[0];
list_set(&evalList, evalList.num_elements, TYPE_OPERATOR, &opValue); list_set(&evalList, evalList.num_elements, TYPE_OPERATOR, &opValue);
continue; continue;
@ -526,7 +520,7 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
int st = parse_int(buff, &res); int st = parse_int(buff, &res);
if (st == 0) { if (st == 0) {
// parse int success // parse int success
//printf("Content aftr parsing %d %d \n", st, res); //printf_wrap("Content aftr parsing %d %d \n", st, res);
list_set(&evalList, evalList.num_elements, TYPE_INT, &res); list_set(&evalList, evalList.num_elements, TYPE_INT, &res);
} }
if (st != 0) { if (st != 0) {
@ -538,21 +532,23 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
} }
} }
// FIXME: refactor to better branching
if (st != 0) { if (st != 0) {
// identify token // identify token
// first try a variable then a func name // first try a variable then a func name
// not a float, check if this is a common function name // not a float, check if this is a common function name
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("now going to identify token '%s' \n", buff); if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("now going to identify token '%s' \n", buff);
if (EVALUATOR_DEBUG_LEVEL >= 2) var_store_print(state->varStore); if (EVALUATOR_DEBUG_LEVEL >= 2) var_store_print(state->varStore);
int varKey = (int) var_store_get_key(state->varStore, buff); int varKey = (int) var_store_get_key(state->varStore, buff);
if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("got var key '%d' \n", varKey);
if (varKey == -1) { if (varKey == -1) {
// did not find the var name // did not find the var name
short funcID = identify_func_name(buff); short funcID = identify_func_name(buff);
if (funcID == -1) { if (funcID == -1) {
// did not find the func name // did not find the func name
printf("ERR Evaluator: could not identify token \"%s\" \n", buff); printf_wrap("ERR Evaluator: could not identify token \"%s\" \n", buff);
return 200; return 200;
} }
if (funcID >= 0) { if (funcID >= 0) {
@ -563,16 +559,16 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
list_set(&evalList, evalList.num_elements, TYPE_VAR_NAME, &varKey); list_set(&evalList, evalList.num_elements, TYPE_VAR_NAME, &varKey);
} }
} }
if (EVALUATOR_DEBUG_LEVEL >= 2) printf("end of a token identification\n"); if (EVALUATOR_DEBUG_LEVEL >= 2) printf_wrap("end of a token identification\n");
} }
// check the content of this thing // check the content of this thing
if (EVALUATOR_DEBUG_LEVEL >= 2) { if (EVALUATOR_DEBUG_LEVEL >= 2) {
list_print(&evalList); list_print(&evalList);
printf("Now going to actually evaluate...\n"); printf_wrap("Now going to actually evaluate...\n");
} }
while (evalList.num_elements > 1 || !is_type_number(list_get_type(&evalList, 0))) { while (evalList.num_elements > 1 || !is_type_literal(list_get_type(&evalList, 0))) {
if (EVALUATOR_DEBUG_LEVEL >= 2) list_print(&evalList); if (EVALUATOR_DEBUG_LEVEL >= 2) list_print(&evalList);
// int reduceVarOpStat = evaluator_reduce_var(state, &evalList); // int reduceVarOpStat = evaluator_reduce_var(state, &evalList);
@ -599,9 +595,9 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
if (m == 4) stat = evaluator_reduce_operator_pattern(&evalList); if (m == 4) stat = evaluator_reduce_operator_pattern(&evalList);
if (m == 5) stat = evaluator_reduce_parenthesis_pattern(&evalList); if (m == 5) stat = evaluator_reduce_parenthesis_pattern(&evalList);
if (stat > 0) { if (stat > 0) {
printf("ERR Evaluator: mode %d reducing failed \n", m); printf_wrap("ERR Evaluator: mode %d reducing failed \n", m);
if (EVALUATOR_DEBUG_LEVEL >= 2) { if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("dumping evalList: \n"); printf_wrap("dumping evalList: \n");
list_print(&evalList); list_print(&evalList);
} }
} }
@ -611,9 +607,9 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
if (!didReduced) { if (!didReduced) {
// all scans failed to find things to reduce // all scans failed to find things to reduce
// this is actually a failure because we can't do anything to get down to 1 element in the eval list // this is actually a failure because we can't do anything to get down to 1 element in the eval list
printf("ERR Evaluator: could not reduce more \n"); printf_wrap("ERR Evaluator: could not reduce more \n");
if (EVALUATOR_DEBUG_LEVEL >= 2) { if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf("dumping evalList: \n"); printf_wrap("dumping evalList: \n");
list_print(&evalList); list_print(&evalList);
} }
return 400; return 400;
@ -623,6 +619,10 @@ int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsig
int typeRes = list_get_type(&evalList, 0); int typeRes = list_get_type(&evalList, 0);
*typePtr = typeRes; *typePtr = typeRes;
list_get(&evalList, 0, resultPtr); list_get(&evalList, 0, resultPtr);
if (EVALUATOR_DEBUG_LEVEL >= 2) {
printf_wrap("End of evaluation, dumping evalList: \n");
list_print(&evalList);
}
return 0; return 0;
} }

View file

@ -2,7 +2,7 @@
#ifndef EVALUATOR_H_ #ifndef EVALUATOR_H_
#define EVALUATOR_H_ #define EVALUATOR_H_
#define EVALUATOR_DEBUG_LEVEL 0 #define EVALUATOR_DEBUG_LEVEL (G_DEBUG_LEVEL)
int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsigned char* typePtr); int evaluate(struct StateContainer* state, char* inputStr, int* resultPtr, unsigned char* typePtr);

View file

@ -5,6 +5,35 @@
#include "./config.h" #include "./config.h"
#include "./types.h" #include "./types.h"
#include "./utils.h" #include "./utils.h"
#include "./number_parsing.h"
// just return the type id of a variable
int type_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
{
UNUSED(args);
*resType = TYPE_INT;
*res = types[0];
return 0;
}
int is_null_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
{
UNUSED(args);
*resType = TYPE_INT;
*res = types[0] == TYPE_NULL;
return 0;
}
int is_number_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
{
UNUSED(args);
*resType = TYPE_INT;
*res = is_type_number(types[0]);
return 0;
}
int abs_impl(int* res, unsigned char* resType, unsigned char* types, int* args) int abs_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
{ {
@ -28,6 +57,33 @@ int abs_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
return 1; return 1;
} }
int floor_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
{
*resType = TYPE_INT;
if (types[0] == TYPE_INT) {
*res = args[0];
return 0;
}
if (types[0] == TYPE_FLOAT) {
float val = get_float_from_int_rep(args[0]);
*res = (int) val;
return 0;
}
return 1;
}
int ceil_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
{
int resInterm = 0;
if (floor_impl(&resInterm, resType, types, args)) {
return 1;
}
resInterm += 1;
*res = resInterm;
return 0;
}
int print_number_impl(int* res, unsigned char* resType, unsigned char* types, int* args) int print_number_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
{ {
*resType = TYPE_INT; *resType = TYPE_INT;
@ -36,15 +92,15 @@ int print_number_impl(int* res, unsigned char* resType, unsigned char* types, in
return 1; return 1;
} }
if (G_DEBUG_LEVEL >= 1) { if (G_DEBUG_LEVEL >= 1) {
printf("REAL_PRINT: "); printf_wrap("REAL_PRINT: ");
} }
if (types[0] == TYPE_INT) { if (types[0] == TYPE_INT) {
int val = args[0]; int val = args[0];
printf("%d\n", val); printf_wrap("%d\n", val);
} }
if (types[0] == TYPE_FLOAT) { if (types[0] == TYPE_FLOAT) {
float val = get_float_from_int_rep(args[0]); float val = get_float_from_int_rep(args[0]);
printf("%f\n", val); printf_wrap("%f\n", val);
} }
*res = 1; *res = 1;
return 0; return 0;
@ -66,16 +122,55 @@ int print_ascii_impl(int* res, unsigned char* resType, unsigned char* types, int
charVal = (int) get_float_from_int_rep(args[0]); charVal = (int) get_float_from_int_rep(args[0]);
} }
printf("%c", *((char*) &charVal)); printf_wrap("%c", *((char*) &charVal));
*res = 1; *res = 1;
return 0; return 0;
} }
int print_newline_impl(int* res, unsigned char* resType, unsigned char* types, int* args) int print_newline_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
{ {
UNUSED(types);
UNUSED(args);
*resType = TYPE_INT; *resType = TYPE_INT;
*res = 1; *res = 1;
printf("\n"); printf_wrap("\n");
return 0;
}
int input_number_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
{
UNUSED(types);
UNUSED(args);
printf_wrap("? ");
char* line;
size_t len = 0;
size_t lineSize = 0;
lineSize = getline_wrap(&line, &len, stdin);
// printf_wrap("len=%d, lineSize=%d '%s' \n", len, lineSize, line);
char toParse[lineSize+1];
str_extract((char*) toParse, line, 0, lineSize-1);
int st = parse_int((char*) &toParse, res);
if (st == 0) {
*resType = TYPE_INT;
return 0;
}
if (st != 0) {
st = parse_float((char*) &toParse, (float*) res);
if (st == 0) {
*resType = TYPE_FLOAT;
return 0;
}
}
// we didn't manage to parse the number
*resType = TYPE_INT;
*res = 0;
return 0; return 0;
} }
@ -187,6 +282,8 @@ int max_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
int get_pi_impl(int* res, unsigned char* resType, unsigned char* types, int* args) int get_pi_impl(int* res, unsigned char* resType, unsigned char* types, int* args)
{ {
UNUSED(args);
UNUSED(types);
float val = CST_PI; float val = CST_PI;
*res = *(int *)(&val); *res = *(int *)(&val);
*resType = TYPE_FLOAT; *resType = TYPE_FLOAT;
@ -233,6 +330,10 @@ struct FuncIntro {
// void* are actually long! // void* are actually long!
struct FuncIntro intros[] = { struct FuncIntro intros[] = {
{"type", &type_impl, 1},
{"is_null", &is_null_impl, 1},
{"is_number", &is_number_impl, 1},
{"abs", &abs_impl, 1}, {"abs", &abs_impl, 1},
{"sqrt", &sqrt_impl, 1}, {"sqrt", &sqrt_impl, 1},
@ -247,11 +348,14 @@ struct FuncIntro intros[] = {
{"random_int", &random_int_impl, 2}, {"random_int", &random_int_impl, 2},
{"max", &max_impl, 2}, {"max", &max_impl, 2},
{"floor", &floor_impl, 1},
{"ceil", &ceil_impl, 1},
{"get_pi", &get_pi_impl, 0}, {"get_pi", &get_pi_impl, 0},
{"print_number", &print_number_impl, 1}, {"print_number", &print_number_impl, 1},
{"print_ascii", &print_ascii_impl, 1}, {"print_ascii", &print_ascii_impl, 1},
{"print_newline", &print_newline_impl, 0}, {"print_newline", &print_newline_impl, 0},
{"input_number", &input_number_impl, 0},
{"", 0, 0} {"", 0, 0}
}; };
@ -273,22 +377,22 @@ short identify_func_name(char* candidate)
int execute_func(short funcID, short argsLen, unsigned char* argsTypes, int* argsValues, int* resPtr, unsigned char* resTypePtr) int execute_func(short funcID, short argsLen, unsigned char* argsTypes, int* argsValues, int* resPtr, unsigned char* resTypePtr)
{ {
if (funcID >= nbOfFuncs) { if (funcID >= nbOfFuncs) {
printf("ERR: Invalid func with index: %d \n", funcID); printf_wrap("ERR: Invalid func with index: %d \n", funcID);
return 1; return 1;
} }
int (*impl)(int*, unsigned char*, unsigned char*, int*) = intros[funcID].implementation; int (*impl)(int*, unsigned char*, unsigned char*, int*) = intros[funcID].implementation;
if (impl == 0) { if (impl == 0) {
printf("ERR: No implementation for func with index: %d \n", funcID); printf_wrap("ERR: No implementation for func with index: %d \n", funcID);
return 1; return 1;
} }
char* name = intros[funcID].name; char* name = intros[funcID].name;
if (G_DEBUG_LEVEL >= 2) printf("Executing func '%s' \n", name); if (G_DEBUG_LEVEL >= 2) printf_wrap("Executing func '%s' \n", name);
if (argsLen < intros[funcID].nbArgs) { if (argsLen < intros[funcID].nbArgs) {
printf("ERR: Too few arguments for func call '%s' \n", name); printf_wrap("ERR: Too few arguments for func call '%s' \n", name);
return 1; return 1;
} }
if (argsLen > intros[funcID].nbArgs) { if (argsLen > intros[funcID].nbArgs) {
printf("ERR: Too many arguments for func call '%s' \n", name); printf_wrap("ERR: Too many arguments for func call '%s' \n", name);
return 1; return 1;
} }
@ -296,7 +400,7 @@ int execute_func(short funcID, short argsLen, unsigned char* argsTypes, int* arg
// first cast the function ptr // first cast the function ptr
impl(resPtr, resTypePtr, argsTypes, argsValues); impl(resPtr, resTypePtr, argsTypes, argsValues);
if (G_DEBUG_LEVEL >= 2) printf("Got %s \n", get_repr(*resTypePtr, resPtr)); if (G_DEBUG_LEVEL >= 2) printf_wrap("Got %s \n", get_repr(*resTypePtr, resPtr));
return 0; return 0;
} }

View file

@ -1,3 +1,5 @@
#include "./config.h"
#include "./types.h"
#include "./utils.h" #include "./utils.h"
#include "./line_processing.h" #include "./line_processing.h"
#include "./stack.h" #include "./stack.h"
@ -32,9 +34,7 @@ int recognize_comment_statement(char* lineStr)
mode = 2; mode = 2;
continue; continue;
} }
if (lineStr[i] != ' ') { if (lineStr[i] != ' ') break;
break;
}
} }
i++; i++;
} }
@ -76,8 +76,8 @@ int recognize_termination_keyword(char* needle, char* subject, int from)
// recognize "set VAR_NAME to EVALUATION" // recognize "set VAR_NAME to EVALUATION"
int recognize_set_statement(char* lineStr, struct SetStatement* res) int recognize_set_statement(char* lineStr, struct SetStatement* res)
{ {
static char setStatementStartKeyword[] = "set"; static char setStatementStartKeyword[] = SYNTAX_SET_START;
static char setStatementStopKeyword[] = "to"; static char setStatementStopKeyword[] = SYNTAX_SET_STOP;
int i = 0; int i = 0;
int mode = 1; int mode = 1;
@ -155,8 +155,8 @@ int recognize_set_statement(char* lineStr, struct SetStatement* res)
// FIXME: allow for multiline if statement // FIXME: allow for multiline if statement
int recognize_if_statement(char* lineStr, struct IfStatement* res) int recognize_if_statement(char* lineStr, struct IfStatement* res)
{ {
static char ifStatementStartKeyword[] = "if"; static char ifStatementStartKeyword[] = SYNTAX_IF_START;
static char ifStatementStopKeyword[] = "then"; static char ifStatementStopKeyword[] = SYNTAX_IF_STOP;
size_t len = strlen(lineStr); size_t len = strlen(lineStr);
if (len < strlen(ifStatementStartKeyword) + 1 + strlen(ifStatementStopKeyword)) return 0; if (len < strlen(ifStatementStartKeyword) + 1 + strlen(ifStatementStopKeyword)) return 0;
@ -222,8 +222,8 @@ int recognize_if_statement(char* lineStr, struct IfStatement* res)
// recognize "while EXPRESSION then \n begin (...) \n end" // recognize "while EXPRESSION then \n begin (...) \n end"
int recognize_while_statement(char* lineStr, struct WhileStatement* res) int recognize_while_statement(char* lineStr, struct WhileStatement* res)
{ {
static char whileStatementStartKeyword[] = "while"; static char whileStatementStartKeyword[] = SYNTAX_WHILE_START;
static char whileStatementStopKeyword[] = "do"; static char whileStatementStopKeyword[] = SYNTAX_WHILE_STOP;
size_t len = strlen(lineStr); size_t len = strlen(lineStr);
if (len < strlen(whileStatementStartKeyword) + 1 + strlen(whileStatementStopKeyword)) return 0; if (len < strlen(whileStatementStartKeyword) + 1 + strlen(whileStatementStopKeyword)) return 0;
@ -309,34 +309,12 @@ int process_line(struct StateContainer* state, char* str)
{ {
if (LINE_PROCESSING_DEBUG_LEVEL >= 1) printf("\n ======= PROCESSING LINE '%s' =======\n", str); if (LINE_PROCESSING_DEBUG_LEVEL >= 1) printf("\n ======= PROCESSING LINE '%s' =======\n", str);
if (LINE_PROCESSING_DEBUG_LEVEL >= 2) printf("skipping: %d, blockStackLen: %d \n", state->skipping, state->blockStack->length); if (LINE_PROCESSING_DEBUG_LEVEL >= 2) printf("skipping: %d, blockStackLen: %d \n", state->skipping, state->blockStack->length);
// process
state->lastEvaluationType = TYPE_NULL;
state->lastEvaluationResult = 0;
int len = strlen(str); int len = strlen(str);
// int startPos = 0;
// int stopPos = len-1;
// // modifiy the start and stop pos to trim spaces
// int startTrimOffset = 0;
// int stopTrimOffset = 0;
// for (int z = 0; z < len; z++) {
// if (inputStr[startPos+z] != ' ') {
// break;
// }
// startTrimOffset++;
// }
// for (int z = 1; z < len; z++) {
// if (inputStr[stopPos-z] != ' ') {
// break;
// }
// stopTrimOffset++;
// }
// startPos += startTrimOffset;
// stopPos -= stopTrimOffset;
// check for comment
// if (str[startPos] == '#') {
// return;
// }
//int stat = 0;
if (recognize_comment_statement(str)) { if (recognize_comment_statement(str)) {
if (LINE_PROCESSING_DEBUG_LEVEL >= 2) printf("Comment recognized \n"); if (LINE_PROCESSING_DEBUG_LEVEL >= 2) printf("Comment recognized \n");
state->linePtr++; state->linePtr++;
@ -347,9 +325,9 @@ int process_line(struct StateContainer* state, char* str)
return 1; return 1;
} }
if (recognize_word(str, "end")) { if (recognize_word(str, SYNTAX_END)) {
byte lastBlockType; int lastBlockType;
int_stack_pop(state->blockStack, (int*) &lastBlockType); // FIXME: use a stack with size byte instead of int int_stack_pop(state->blockStack, &lastBlockType); // FIXME: use a stack with size byte instead of int
if (!state->skipping && lastBlockType == BLOCK_WHILE) { if (!state->skipping && lastBlockType == BLOCK_WHILE) {
int lastLoopLine; int lastLoopLine;
int_stack_pop(state->loopStack, &lastLoopLine); int_stack_pop(state->loopStack, &lastLoopLine);
@ -425,10 +403,8 @@ int process_line(struct StateContainer* state, char* str)
int res; int res;
byte resType; byte resType;
int evalStat = evaluate(state, (char*) &dest, &res, &resType); int evalStat = evaluate(state, (char*) &dest, &res, &resType);
if (evalStat != 0) { if (evalStat != 0) return 0;
printf("Syntax error for line \"%s\"\n", str);
return 0;
}
byte doFollow = convert_to_bool(resType, res); byte doFollow = convert_to_bool(resType, res);
if (LINE_PROCESSING_DEBUG_LEVEL >= 2) printf("Got %s, doFollow: %d \n", get_repr(resType, &res), doFollow); if (LINE_PROCESSING_DEBUG_LEVEL >= 2) printf("Got %s, doFollow: %d \n", get_repr(resType, &res), doFollow);
@ -450,29 +426,37 @@ int process_line(struct StateContainer* state, char* str)
return 1; return 1;
} }
if (recognize_word(str, "continue")) { if (recognize_word(str, SYNTAX_EXIT)) {
// exit the whole script
state->running = 0;
return 1;
}
if (recognize_word(str, SYNTAX_CONTINUE)) {
int lastLoopLine; int lastLoopLine;
if (!int_stack_pop(state->loopStack, &lastLoopLine)) { if (!int_stack_pop(state->loopStack, &lastLoopLine)) {
printf("Syntax error: unexpected continue, not in a loop \n"); printf("Syntax error: unexpected continue, not in a loop.\n");
return 0; return 0;
} }
state->linePtr = lastLoopLine; state->linePtr = lastLoopLine;
// find the last while if the block stack and pop blocks up to that point // find the last while if the block stack and pop blocks up to that point
byte lastBlockType; int lastBlockType;
while (lastBlockType != BLOCK_WHILE) { while (lastBlockType != BLOCK_WHILE) {
if (!int_stack_pop(state->blockStack, &lastBlockType)) { if (!int_stack_pop(state->blockStack, &lastBlockType)) {
printf("Syntax error: unexpected continue \n"); printf("Syntax error: unexpected continue.\n");
return 0;
} }
} }
int_stack_pop(state->blockStack, &lastBlockType); int_stack_pop(state->blockStack, &lastBlockType);
return 1; return 1;
} }
if (recognize_word(str, "break")) {
if (recognize_word(str, SYNTAX_BREAK)) {
int lastLoopLine; int lastLoopLine;
if (!int_stack_pop(state->loopStack, &lastLoopLine)) { if (!int_stack_pop(state->loopStack, &lastLoopLine)) {
printf("Syntax error: unexpected break, not in a loop \n"); printf("Syntax error: unexpected break, not in a loop.\n");
return 0; return 0;
} }
@ -517,7 +501,7 @@ int process_line(struct StateContainer* state, char* str)
int evalStat = evaluate(state, (char*) &express, &res, &resType); int evalStat = evaluate(state, (char*) &express, &res, &resType);
if (evalStat != 0) { if (evalStat != 0) {
printf("Syntax error for line \"%s\"\n", str); printf("Error: could not evaluate the expression associated with the content of the variable to set \"%s\".\n", str);
return 0; return 0;
} }
@ -528,14 +512,17 @@ int process_line(struct StateContainer* state, char* str)
return 1; return 1;
} }
// we evaluate but we dont care about the result // we evaluate the expression and we register it in the state in case of a REPL that want to get the result of the expression
int res; int res;
byte resType; byte resType;
int evalStat = evaluate(state, str, &res, &resType); int evalStat = evaluate(state, str, &res, &resType);
if (evalStat != 0) { if (evalStat != 0) {
printf("Syntax error for line \"%s\"\n", str); printf("Error: could not evaluate expression \"%s\".\n", str);
return 0; return 0;
} }
state->lastEvaluationType = resType;
state->lastEvaluationResult = res;
state->linePtr++; state->linePtr++;
return 1; return 1;
} }
@ -587,7 +574,7 @@ int process_script(struct StateContainer* state, char* script)
while (state->running && state->linePtr != lineCount) { while (state->running && state->linePtr != lineCount) {
if (state->linePtr >= lineCount) { if (state->linePtr >= lineCount) {
printf("Invalid line %d \n", state->linePtr); printf("Error: Invalid line %d \n.", state->linePtr);
break; break;
} }
int lineLen = (lineEnds[state->linePtr] - lineStarts[state->linePtr]); int lineLen = (lineEnds[state->linePtr] - lineStarts[state->linePtr]);
@ -596,10 +583,17 @@ int process_script(struct StateContainer* state, char* script)
int stat = process_line(state, line); int stat = process_line(state, line);
if (!stat) { if (!stat) {
printf("Abnormal end of run at line %d: '%s' \n", state->linePtr, line); printf("Error: Abnormal end of run at line %d: '%s'.\n", state->linePtr, line);
return 0; return 0;
} }
} }
if (LINE_PROCESSING_DEBUG_LEVEL >= 1) {
// end of run
printf("End of run dumping var_store \n");
var_store_print(state->varStore);
printf("=== end of dump\n");
}
return 1; return 1;
} }

View file

@ -2,7 +2,7 @@
#ifndef LINE_PROCESSING_H_ #ifndef LINE_PROCESSING_H_
#define LINE_PROCESSING_H_ #define LINE_PROCESSING_H_
#define LINE_PROCESSING_DEBUG_LEVEL 0 #define LINE_PROCESSING_DEBUG_LEVEL (G_DEBUG_LEVEL)
#define BLOCK_IF 2 #define BLOCK_IF 2
#define BLOCK_WHILE 3 #define BLOCK_WHILE 3

View file

@ -185,51 +185,15 @@ int list_append_char(struct List* list, char value)
void list_print(struct List* list) void list_print(struct List* list)
{ {
printf("=== LIST REPORT === \n"); printf_wrap("=== LIST REPORT === \n");
printf("num of elements: %d \n", list->num_elements); printf_wrap("num of elements: %d \n", list->num_elements);
for (int i = 0; i < list->num_elements; i++) { for (int i = 0; i < list->num_elements; i++) {
printf("- i: %d, ", i);
int type = list_get_type(list, i); int type = list_get_type(list, i);
if (type == TYPE_INT) { int data = 0;
int d = 0; list_get(list, i, &data);
list_get(list, i, &d);
printf("type: INT, val: %d", d); printf_wrap("- i: %d, %s \n", i, get_repr(type, (void*) &data));
}
if (type == TYPE_FLOAT) {
float d = 0;
list_get(list, i, &d);
printf("type: FLOAT, val: %f", d);
}
if (type == TYPE_OPERATOR) {
char d = 0;
list_get(list, i, &d);
printf("type: OPERATOR, val: %d '%c'", d, d);
}
if (type == TYPE_FUNC_NAME) {
short d = 0;
list_get(list, i, &d);
printf("type: FUNC_NAME, val: %d", d);
}
if (type == TYPE_VAR_NAME) {
short d = 0;
list_get(list, i, &d);
printf("type: VAR_NAME, val: %d", d);
}
if (type == TYPE_OPEN_PARENTHESIS) {
printf("type: OPEN_PARENTHESIS");
}
if (type == TYPE_COMMA) {
printf("type: COMMA");
}
if (type == TYPE_CLOSE_PARENTHESIS) {
printf("type: CLOSE_PARENTHESIS");
}
printf("\n");
} }
printf("=== END === \n"); printf_wrap("=== END === \n");
} }

View file

@ -1,9 +1,12 @@
#include <assert.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <string.h> #include <string.h>
#include "./config.h" #include "./config.h"
#include "./types.h"
#include "./utils.h" #include "./utils.h"
#include "./types.h"
#include "./stack.h" #include "./stack.h"
#include "./list.h" #include "./list.h"
#include "./number_parsing.h" #include "./number_parsing.h"
@ -12,6 +15,11 @@
#include "./var_store.h" #include "./var_store.h"
#include "./line_processing.h" #include "./line_processing.h"
/**
This is the binding of the interpreter to a CLI
The interpreter should be uncoupled from the rest of the code
*/
#define HELP_FLAG 1 #define HELP_FLAG 1
#define VERSION_FLAG 4 #define VERSION_FLAG 4
#define INTERACTIVE_FLAG 8 #define INTERACTIVE_FLAG 8
@ -23,51 +31,104 @@ int help_mode(char* cmdName) {
" -v --version print version information and exit\n" " -v --version print version information and exit\n"
" -i --interactive force interactive mode\n" " -i --interactive force interactive mode\n"
" -e --stdin-expression evaluate expression from stdin\n"; " -e --stdin-expression evaluate expression from stdin\n";
printf(helpStr, cmdName); printf_wrap(helpStr, cmdName);
return 0; return 0;
} }
int version_mode() { int version_mode() {
char* helpStr = "Langatator 0.0.1\n"; char* helpStr = "Langatator 0.0.1\n";
printf(helpStr); printf_wrap(helpStr);
return 0; return 0;
} }
int interactive_mode() { int interactive_mode() {
printf("Interactive not implemented yet ¯\\_(ツ)_/¯ \n"); struct StateContainer* state = state_init();
return 1;
while (state->running) {
printf_wrap("? ");
char* line;
size_t len = 0;
size_t lineSize = 0;
lineSize = getline(&line, &len, stdin);
if (lineSize == (size_t) -1) {
// we received some kind of interrupt?
printf_wrap("\n");
return EXIT_SUCCESS;
}
char toEvaluate[lineSize+1];
// remove the new line at the end
str_extract((char*) toEvaluate, line, 0, lineSize-1);
int stat = process_line(state, toEvaluate);
if (!stat) {
printf_wrap("Processing that line failed.\n");
}
if (state->lastEvaluationType != TYPE_NULL) {
printf_wrap("%s\n", get_repr(state->lastEvaluationType, &state->lastEvaluationResult));
}
}
return EXIT_SUCCESS;
} }
int stdin_expression_mode() { int stdin_expression_mode() {
printf("This mode is not implemented yet ¯\\_(ツ)_/¯ \n"); printf_wrap("This mode is not implemented yet ¯\\_(ツ)_/¯ \n");
return 1; return 1;
} }
int file_mode(char* fileName) {
FILE* f = fopen(fileName, "rb");
if (!f) { char* slurp_file(char* filePath, size_t* size) {
fprintf(stderr, "Cannot load file '%s' status: %d\n", fileName, (int) f); char* buffer = NULL;
return 1;
} FILE* f = fopen(filePath, "rb");
fseek(f, 0, SEEK_END); if (f == NULL) goto error;
long length = ftell(f);
fseek(f, 0, SEEK_SET); if (fseek(f, 0, SEEK_END) < 0) goto error;
long m = ftell(f);
if (m < 0) goto error;
buffer = malloc(sizeof(char) * m);
if (buffer == NULL) goto error;
if (fseek(f, 0, SEEK_SET) < 0) goto error;
size_t n = fread(buffer, 1, m, f);
assert(n == (size_t) m);
if (ferror(f)) goto error;
if (size) *size = n;
char* buff = (char*) malloc(length);
if (!buff) {
fprintf(stderr, "Could not allocate buffer to process file content\n");
return 1;
}
if (buff) {
fread(buff, 1, length, f);
}
fclose(f); fclose(f);
return buffer;
error:
if (f) fclose(f);
if (buffer) free(buffer);
return NULL;
}
int file_mode(char* fileName) {
// printf_wrap("Open file mode...\n");
size_t size;
char* buff = slurp_file(fileName, &size);
if (!buff) {
fprintf(stderr, "Error: Cannot load file '%s' errno: %d '%s'.\n", fileName, errno, strerror(errno));
return EXIT_FAILURE;
}
struct StateContainer* state = state_init(); struct StateContainer* state = state_init();
process_script(state, buff); process_script(state, buff);
return 0; return EXIT_SUCCESS;
} }
int main (int argc, char** argv) { int main (int argc, char** argv) {
@ -97,7 +158,7 @@ int main (int argc, char** argv) {
// no flag match // no flag match
if (str_starts_with("--", argv[i])) { if (str_starts_with("--", argv[i])) {
fprintf(stderr, "Invalid flag '%s'\n", argv[i]); fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
return 1; return EXIT_FAILURE;
} }
nonFlagArgumentCount++; nonFlagArgumentCount++;
nonFlagArgumentPos = i; nonFlagArgumentPos = i;
@ -110,5 +171,5 @@ int main (int argc, char** argv) {
if (flags & STDIN_EXP_FLAG) return stdin_expression_mode(); if (flags & STDIN_EXP_FLAG) return stdin_expression_mode();
help_mode(cmdName); help_mode(cmdName);
return 1; return EXIT_FAILURE;
} }

View file

@ -22,7 +22,7 @@ int parse_clean_positive_integer(int inputStrLen, char* inputStr, int* result) {
); );
i++; i++;
} }
//printf("parseclean %d \n", value); //printf_wrap("parseclean %d \n", value);
*result = value; *result = value;
@ -31,7 +31,7 @@ int parse_clean_positive_integer(int inputStrLen, char* inputStr, int* result) {
int parse_int(char* inputStr, int* resultPtr) { int parse_int(char* inputStr, int* resultPtr) {
int i = 0; int i = 0;
char cleanStr[strlen(inputStr)]; char cleanStr[strlen(inputStr)+1];
int cleanStrLen = 0; int cleanStrLen = 0;
int hasNegSign = 0; int hasNegSign = 0;
while (inputStr[i] != 0) { while (inputStr[i] != 0) {
@ -58,10 +58,14 @@ int parse_int(char* inputStr, int* resultPtr) {
i++; i++;
} }
cleanStr[cleanStrLen] = 0; cleanStr[cleanStrLen] = 0;
//printf("clean str: %s/ \n", cleanStr); //printf_wrap("clean str: %s/ \n", cleanStr);
int inter = 0; int inter = 0;
parse_clean_positive_integer(cleanStrLen, cleanStr, &inter); byte stat = parse_clean_positive_integer(cleanStrLen, cleanStr, &inter);
if (NB_PARSING_DEBUG_LEVEL >= 2) {
printf_wrap("Parse clean positive integer stat: %d\n", stat);
printf_wrap("Got value: %d\n", inter);
}
*resultPtr = inter; *resultPtr = inter;
if (hasNegSign) { if (hasNegSign) {
@ -72,11 +76,12 @@ int parse_int(char* inputStr, int* resultPtr) {
} }
int parse_float(char* inputStr, float* resultPtr) { int parse_float(char* inputStr, float* resultPtr) {
if (NB_PARSING_DEBUG_LEVEL >= 2) printf_wrap("Parsing as float: '%s'\n", inputStr);
int i = 0; int i = 0;
char cleanStrIntPart[strlen(inputStr)]; char cleanStrIntPart[strlen(inputStr)+1];
int cleanStrIntPartLen = 0; int cleanStrIntPartLen = 0;
char cleanStrFloatPart[strlen(inputStr)]; char cleanStrFloatPart[strlen(inputStr)+1];
int cleanStrFloatPartLen = 0; int cleanStrFloatPartLen = 0;
int part = 0; // 0 for first part, 1 for snd part int part = 0; // 0 for first part, 1 for snd part
@ -130,8 +135,8 @@ int parse_float(char* inputStr, float* resultPtr) {
} }
cleanStrIntPart[cleanStrIntPartLen] = 0; cleanStrIntPart[cleanStrIntPartLen] = 0;
cleanStrFloatPart[cleanStrFloatPartLen] = 0; cleanStrFloatPart[cleanStrFloatPartLen] = 0;
// printf("clean str int part: /%s/ \n", cleanStrIntPart); // printf_wrap("clean str int part: /%s/ \n", cleanStrIntPart);
// printf("clean str float part: /%s/ \n", cleanStrFloatPart); // printf_wrap("clean str float part: /%s/ \n", cleanStrFloatPart);
int intPart = 0; int intPart = 0;
parse_clean_positive_integer(cleanStrIntPartLen, cleanStrIntPart, &intPart); parse_clean_positive_integer(cleanStrIntPartLen, cleanStrIntPart, &intPart);

View file

@ -1,6 +1,8 @@
#ifndef NB_PARSING_H_ #ifndef NB_PARSING_H_
#define NB_PARSING_H_ #define NB_PARSING_H_
#define NB_PARSING_DEBUG_LEVEL 0
int is_char_numeral(char candidate); int is_char_numeral(char candidate);
int integer_pow(int base, int exponent); int integer_pow(int base, int exponent);
int parse_clean_positive_integer(int inputStrLen, char* inputStr, int* result); int parse_clean_positive_integer(int inputStrLen, char* inputStr, int* result);

View file

@ -72,7 +72,7 @@ int operate(
a = convert_to_float(typeA, aRepr); a = convert_to_float(typeA, aRepr);
b = convert_to_float(typeB, bRepr); b = convert_to_float(typeB, bRepr);
if (OPERATE_DEBUG_LEVEL) printf("Appling operation: %f %c %f \n", a, operator, b); if (OPERATE_DEBUG_LEVEL) printf_wrap("Appling operation: %f %c %f \n", a, operator, b);
if (operator == '+') { if (operator == '+') {
res = a+b; res = a+b;
@ -95,13 +95,13 @@ int operate(
} else { } else {
return 2; return 2;
} }
if (OPERATE_DEBUG_LEVEL) printf("Got float: %f \n", res); if (OPERATE_DEBUG_LEVEL) printf_wrap("Got float: %f \n", res);
// get int representation of float // get int representation of float
*resPtr = *(int *)(&res); *resPtr = *(int *)(&res);
return 0; return 0;
} }
if (typeA == TYPE_INT && typeB == TYPE_INT) { if (typeA == TYPE_INT && typeB == TYPE_INT) {
if (OPERATE_DEBUG_LEVEL) printf("Appling operation %d %c %d \n", aRepr, operator, bRepr); if (OPERATE_DEBUG_LEVEL) printf_wrap("Appling operation %d %c %d \n", aRepr, operator, bRepr);
*typeRes = TYPE_INT; *typeRes = TYPE_INT;
int res = 0; int res = 0;
if (operator == '+') { if (operator == '+') {

View file

@ -1,3 +1,63 @@
/*
#include "./utils.h"
#include "./stack.h"
#include <stdio.h>
#include <stdlib.h>
struct Stack* int_stack_init(byte unitSize)
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
stack->unitSize = unitSize;
stack->length = 0;
stack->allocated = 8;
stack->data = (int*) malloc(stack->allocated * stack->unitSize);
return stack;
}
byte stack_push(struct Stack* stack, void* valueToPush)
{
if (stack->length == stack->allocated) {
stack->allocated *= 2;
stack->data = realloc(stack->data, stack->allocated * stack->unitSize);
}
memcpy(stack->data[stack->length], valueToPush, stack->unitSize);
stack->length++;
return 1;
}
byte stack_pop(struct Stack* stack, void* valuePtr)
{
if (stack->length == 0) {
// error, nothing to pop
return 0;
}
memcpy(valuePtr, stack->data[stack->length-1], stack->unitSize);
stack->length--;
return 1;
}
int int_stack_length(struct Stack* stack)
{
return stack->length;
}
void int_stack_print(struct Stack* stack)
{
printf_wrap("= STACK REPORT \n");
for (int i = 0; i < stack->length; i++) {
printf_wrap("%d; ", stack->data[i]);
}
printf_wrap("\n");
}
*/
#include "./utils.h" #include "./utils.h"
#include "./stack.h" #include "./stack.h"
#include <stdio.h> #include <stdio.h>
@ -53,3 +113,4 @@ void int_stack_print(struct IntStack* stack)
} }
printf("\n"); printf("\n");
} }

View file

@ -2,6 +2,24 @@
#ifndef STACK_H_ #ifndef STACK_H_
#define STACK_H_ #define STACK_H_
// struct Stack {
// byte unitSize;
// int length;
// int allocated;
// int* data;
// };
// struct Stack* stack_init();
// byte stack_push(struct Stack* stack, void* valueToPush);
// byte stack_pop(struct Stack* stack, void* valuePtr);
// byte stack_get(struct Stack* stack, int index, void* valuePtr);
// int stack_length(struct Stack* stack);
// void stack_print(struct Stack* stack);
struct IntStack { struct IntStack {
int length; int length;
int allocated; int allocated;
@ -18,4 +36,5 @@ int int_stack_length(struct IntStack* stack);
void int_stack_print(struct IntStack* stack); void int_stack_print(struct IntStack* stack);
#endif #endif

View file

@ -18,5 +18,8 @@ struct StateContainer* state_init()
ptr->running = 1; ptr->running = 1;
ptr->lastEvaluationType = TYPE_NULL;
ptr->lastEvaluationResult = 0;
return ptr; return ptr;
} }

View file

@ -32,6 +32,9 @@ struct StateContainer {
// struct FunctionStore* funcStore; // struct FunctionStore* funcStore;
// struct StringStore* strStore ?? // struct StringStore* strStore ??
int lastEvaluationResult;
byte lastEvaluationType;
}; };
struct StateContainer* state_init(); struct StateContainer* state_init();

View file

@ -3,6 +3,11 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int is_type_literal(byte type)
{
return is_type_number(type) || type == TYPE_NULL;
}
int is_type_number(byte type) int is_type_number(byte type)
{ {
return type == TYPE_INT || type == TYPE_FLOAT; return type == TYPE_INT || type == TYPE_FLOAT;
@ -25,6 +30,7 @@ int get_size_of_type(byte type)
return 1; return 1;
} }
if ( if (
t == TYPE_NULL ||
t == TYPE_OPEN_PARENTHESIS || t == TYPE_OPEN_PARENTHESIS ||
t == TYPE_CLOSE_PARENTHESIS || t == TYPE_CLOSE_PARENTHESIS ||
t == TYPE_COMMA t == TYPE_COMMA
@ -36,25 +42,36 @@ int get_size_of_type(byte type)
char* get_repr(byte type, void* valPtr) char* get_repr(byte type, void* valPtr)
{ {
char* res= (char*) malloc(sizeof(char)*32); char* res = (char*) malloc(sizeof(char)*32);
if (res == 0) return 0;
if (type == 0) { if (type == 0) {
sprintf(res, "NO_TYPE");
} else if (type == TYPE_NULL) {
sprintf(res, "NULL"); sprintf(res, "NULL");
return res; } else if (type == TYPE_INT) {
}
if (type == TYPE_INT) {
sprintf(res, "INT(%d)", *((int*) valPtr)); sprintf(res, "INT(%d)", *((int*) valPtr));
return res; } else if (type == TYPE_FLOAT) {
}
if (type == TYPE_FLOAT) {
sprintf(res, "FLOAT(%f)", *((float*) valPtr)); sprintf(res, "FLOAT(%f)", *((float*) valPtr));
return res; } else if (type == TYPE_OPEN_PARENTHESIS) {
sprintf(res, "OPEN_PARENTHESIS");
} else if (type == TYPE_CLOSE_PARENTHESIS) {
sprintf(res, "CLOSE_PARENTHESIS");
} else if (type == TYPE_COMMA) {
sprintf(res, "COMMA");
} else if (type == TYPE_OPERATOR) {
sprintf(res, "OPERATOR(%c)", *((char*) valPtr));
} else if (type == TYPE_VAR_NAME) {
sprintf(res, "VAR_NAME(ref: %d)", *((int*) valPtr));
} else if (type == TYPE_FUNC_NAME) {
sprintf(res, "FUNC_NAME(ref: %d)", *((int*) valPtr));
} else {
sprintf(res, "UNKNOWN type=%d", type);
} }
sprintf(res, "UNKNOWN type=%d", type);
return res; return res;
} }
int convert_to_int(byte type, int repr) { int convert_to_int(byte type, int repr) {
if (type == TYPE_NULL) return 0;
if (type == TYPE_FLOAT) return (int) *((int*) &repr); if (type == TYPE_FLOAT) return (int) *((int*) &repr);
return repr; return repr;
} }

View file

@ -2,6 +2,7 @@
#ifndef TYPES_H_ #ifndef TYPES_H_
#define TYPES_H_ #define TYPES_H_
#define TYPE_NULL 1
#define TYPE_INT 2 #define TYPE_INT 2
#define TYPE_FLOAT 3 #define TYPE_FLOAT 3
#define TYPE_OPERATOR 32 #define TYPE_OPERATOR 32
@ -11,10 +12,15 @@
#define TYPE_OPEN_PARENTHESIS 64 #define TYPE_OPEN_PARENTHESIS 64
#define TYPE_CLOSE_PARENTHESIS 65 #define TYPE_CLOSE_PARENTHESIS 65
int is_type_literal(byte type);
int is_type_number(byte type); int is_type_number(byte type);
int get_size_of_type(byte type); int get_size_of_type(byte type);
// get short string representation of a type
// usefull when printing a report
char* get_repr(byte type, void* data); char* get_repr(byte type, void* data);
byte convert_to_bool(byte type, int repr); byte convert_to_bool(byte type, int repr);

View file

@ -2,6 +2,17 @@
#include <string.h> #include <string.h>
#include "./utils.h" #include "./utils.h"
#include <stdarg.h>
#if PRINT_MODE == 0
int printf_wrap(const char* format, ...) {
va_list args;
va_start(args, format);
vprintf(format, args);
va_end( args );
}
#endif
int get_int_rep_from_float(float ft) int get_int_rep_from_float(float ft)
{ {
return *(int *)(&ft); return *(int *)(&ft);
@ -21,7 +32,7 @@ float get_float_from_int_rep(int representation)
int get_int_rep_from_char(char c) int get_int_rep_from_char(char c)
{ {
return *(int *)(&c); return (int) c;
} }
int is_char_numeral(char candidate) int is_char_numeral(char candidate)
@ -194,10 +205,10 @@ float m_tan(float x)
// return ((func(a+h)-func(a))/h); // return ((func(a+h)-func(a))/h);
// } // }
// euler method in one dimension // newton method in one dimension
// takes a function and find one of the root // takes a function and find one of the root
// return the status 0 if success >0 if error // return the status 0 if success >0 if error
int m_euler_method(float (*func)(float, float), float param, float startsAt, float* resPtr) int m_newton_method(float (*func)(float, float), float param, float startsAt, float* resPtr)
{ {
// (x-b)f'(b)+f(b) = 0 // (x-b)f'(b)+f(b) = 0
// xf'(b)-bf'(b)+f(b) = 0 // xf'(b)-bf'(b)+f(b) = 0
@ -217,7 +228,7 @@ int m_euler_method(float (*func)(float, float), float param, float startsAt, flo
return 0; return 0;
} }
if (runs > 100) { if (runs > 100) {
printf("ERR: euler methods failed, coup dur pour euler \n"); printf_wrap("ERR: newton methods failed, coup dur pour newton \n");
return 100; return 100;
} }
cursor = newCursor; cursor = newCursor;
@ -235,7 +246,7 @@ float m_sqrt_equation(float x, float y)
float m_sqrt(float x) float m_sqrt(float x)
{ {
float res = 0; float res = 0;
m_euler_method(&m_sqrt_equation, x, 4, &res); m_newton_method(&m_sqrt_equation, x, 4, &res);
return res; return res;
} }
@ -248,7 +259,7 @@ float m_ln_equation(float x, float y)
float m_ln(float x) float m_ln(float x)
{ {
float res = 0; float res = 0;
m_euler_method(&m_ln_equation, x, 4, &res); m_newton_method(&m_ln_equation, x, 4, &res);
return res; return res;
} }

View file

@ -3,11 +3,17 @@
#ifndef UTILS_H_ #ifndef UTILS_H_
#define UTILS_H_ #define UTILS_H_
int printf_wrap(const char* format, ...);
// useful to silent warning of gcc of uunused parameters in functions
#define UNUSED(x) (void)(x)
#define CST_PI 3.1415926535 #define CST_PI 3.1415926535
// define custom type (unsigned char) // define custom type (unsigned char)
typedef unsigned char byte; typedef unsigned char byte;
int get_int_rep_from_float(float ft); int get_int_rep_from_float(float ft);
float get_float_from_int_rep(int representation); float get_float_from_int_rep(int representation);
@ -24,6 +30,9 @@ float m_float_modulus(float a, float mod);
int m_factorial(int x); int m_factorial(int x);
int m_newton_method(float (*func)(float, float), float param, float startsAt, float* resPtr);
float m_float_pow(float base, int exponent); float m_float_pow(float base, int exponent);
float m_sqrt(float x); float m_sqrt(float x);
@ -45,6 +54,7 @@ int is_full_of_space(char* str);
void str_extract(char* res, char* subject, int initial, int length); void str_extract(char* res, char* subject, int initial, int length);
byte str_needle_at_pos(char* needle, char* subject, int pos); byte str_needle_at_pos(char* needle, char* subject, int pos);
byte str_starts_with(char* needle, char* subject); byte str_starts_with(char* needle, char* subject);
void trim_space(char* dst, char* subject); void trim_space(char* dst, char* subject);

View file

@ -4,53 +4,64 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#define MAX_INTEGER 2147483647-1
struct VariableStore* var_store_init() struct VariableStore* var_store_init()
{ {
struct VariableStore* store = (struct VariableStore*) malloc(sizeof(struct VariableStore)); struct VariableStore* store = (struct VariableStore*) malloc(sizeof(struct VariableStore));
if (store == NULL) { if (store == NULL) {
printf("[ERR] VARSTORE: malloc failed for variable store \n"); printf_wrap("[ERR] VARSTORE: malloc failed for variable store \n");
return NULL; return NULL;
} }
store->allocatedLength = VAR_STORE_INITIAL_ALLOC_LENGTH; store->allocatedLength = VAR_STORE_INITIAL_ALLOC_LENGTH;
store->length = 0; store->length = 0;
store->container = (struct VariableContainer*) malloc(sizeof(struct VariableContainer) * store->allocatedLength); store->container = (struct VariableContainer*) malloc(sizeof(struct VariableContainer) * store->allocatedLength);
if (store->container == NULL) { if (store->container == NULL) {
printf("[ERR] VARSTORE: malloc failed for first variable container \n"); printf_wrap("[ERR] VARSTORE: malloc failed for first variable container \n");
return NULL; return NULL;
} }
for (int i = 0; i < store->allocatedLength; i++) { for (int i = 0; i < store->allocatedLength; i++) {
store->container[i].type = 0; store->container[i].type = 0;
} }
var_store_add_constants(store);
return store; return store;
} }
#define MAX_INTEGER 47797852 void var_store_add_constants(struct VariableStore* store)
{
// NULL constant
var_store_set(store, "NULL", TYPE_NULL, 0);
}
int var_store_hash_name(struct VariableStore* store, char* varName) int var_store_hash_name(struct VariableStore* store, char* varName)
{ {
int hash = 0; int hash = 0;
int i = 0; int i = 0;
while (varName[i] != '\0') { while (varName[i] != '\0') {
hash += (get_int_rep_from_char(varName[i])*integer_pow(9, i)) % MAX_INTEGER; int num = get_int_rep_from_char(varName[i])|integer_pow(9, i);
hash += num;
i++; i++;
} }
// FIXME: when reallocating, we should copy all variables to their new key // FIXME: when reallocating, we should copy all variables to their new key
// because we use modulus operator, the hash will change whenever we reallocated the table // because we use modulus operator, the hash will change whenever we reallocated the table
return hash % store->allocatedLength; hash = (hash < 0 ? -hash : hash) % store->allocatedLength;
//printf_wrap("Compute a hash for '%s' , allocatd: %d; %d\n", varName, store->allocatedLength, hash);
return hash;
} }
byte var_store_set(struct VariableStore* store, char* varName, byte type, void* valuePtr) byte var_store_set(struct VariableStore* store, char* varName, byte type, void* valuePtr)
{ {
//printf("set variable at var name: '%s' \n", varName); //printf_wrap("set variable at var name: '%s' \n", varName);
if (!(type == TYPE_FLOAT || type == TYPE_INT)) { if (!(type == TYPE_FLOAT || type == TYPE_INT || type == TYPE_NULL)) {
printf("[ERR] VARSTORE: unsupported type, cannot store type %d\n", type); printf_wrap("[ERR] VARSTORE: unsupported type, cannot store type %d\n", type);
return 0; return 0;
} }
void* dataPtr; void* dataPtr;
if (type == TYPE_FLOAT || type == TYPE_INT) { if (type == TYPE_FLOAT || type == TYPE_INT) {
dataPtr = malloc(sizeof(int)); dataPtr = malloc(sizeof(int));
if (dataPtr == NULL) { if (dataPtr == NULL) {
printf("[ERR] VARSTORE: malloc failed for data\n"); printf_wrap("[ERR] VARSTORE: malloc failed for data\n");
return 1; return 1;
} }
@ -61,7 +72,7 @@ byte var_store_set(struct VariableStore* store, char* varName, byte type, void*
char* namePtr = (char*) malloc(strlen(varName)); char* namePtr = (char*) malloc(strlen(varName));
if (namePtr == NULL) { if (namePtr == NULL) {
printf("[ERR] VARSTORE: malloc failed for var name\n"); printf_wrap("[ERR] VARSTORE: malloc failed for var name\n");
return 1; return 1;
} }
strcpy(namePtr, varName); strcpy(namePtr, varName);
@ -73,7 +84,7 @@ byte var_store_set(struct VariableStore* store, char* varName, byte type, void*
{ {
if (store->container[key].type == 0) { if (store->container[key].type == 0) {
// we finally found an empty space, but we didn't found a variable with the same name // we finally found an empty space, but we didn't found a variable with the same name
// we have a new variable // so we have a new variable
store->length++; store->length++;
break; break;
} }
@ -84,24 +95,25 @@ byte var_store_set(struct VariableStore* store, char* varName, byte type, void*
key = (key+1) % store->allocatedLength; key = (key+1) % store->allocatedLength;
if (key == originalKey) { if (key == originalKey) {
// end the search to avoid endless loop // end the search to avoid endless loop
printf("[ERR] VARSTORE: cannot set variable, not enough containers \n"); printf_wrap("[ERR] VARSTORE: cannot set variable, not enough containers \n");
return 1; return 1;
} }
} }
//printf("set variable at key: %d \n", key); //printf_wrap("set variable at key: %d \n", key);
store->container[key].type = type; store->container[key].type = type;
store->container[key].namePtr = namePtr; store->container[key].namePtr = namePtr;
store->container[key].dataPtr = dataPtr; store->container[key].dataPtr = dataPtr;
if (2*store->length >= store->allocatedLength) { if (2*store->length >= store->allocatedLength) {
printf_wrap("REALLOCATING THE FUCKING VAR STORE\n");
// do smth to double the store->allocatedLength // do smth to double the store->allocatedLength
// e.g reallocate the store->container // e.g reallocate the store->container
// FIXME: copy all variables to their new keys // FIXME: copy all variables to their new keys
store->allocatedLength = 2*store->allocatedLength; store->allocatedLength = 2*store->allocatedLength;
store->container = (struct VariableContainer*) realloc(store->container, sizeof(struct VariableContainer) * store->allocatedLength); store->container = (struct VariableContainer*) realloc(store->container, sizeof(struct VariableContainer) * store->allocatedLength);
if (store->container == NULL) { if (store->container == NULL) {
printf("[ERR] VARSTORE: relloc failed for container \n"); printf_wrap("[ERR] VARSTORE: relloc failed for container \n");
return 1; return 1;
} }
} }
@ -113,24 +125,21 @@ byte var_store_set(struct VariableStore* store, char* varName, byte type, void*
// return -1 if no pos are found // return -1 if no pos are found
int var_store_get_key(struct VariableStore* store, char* varName) int var_store_get_key(struct VariableStore* store, char* varName)
{ {
//printf("get key for %s \n", varName); //printf_wrap("get key for %s \n", varName);
int originalKey = var_store_hash_name(store, varName); int originalKey = var_store_hash_name(store, varName);
//printf_wrap("got hash for get key: %d\n", originalKey);
int key = originalKey; int key = originalKey;
// handle collision, walk along the array // handle collision, walk along the array
while (1) while (1) {
{ //printf_wrap("inter key: %d %d \n", key, store->container[key].type);
//printf("inter key: %d %d \n", key, store->container[key].type); if (store->container[key].type == 0) return -1;
if (store->container[key].type == 0) {
return -1; // check if we found the position
} if (strcmp(store->container[key].namePtr, varName) == 0) return key;
if (strcmp(store->container[key].namePtr, varName) == 0) {
// we found the position
return key;
}
key = (key+1) % store->allocatedLength; key = (key+1) % store->allocatedLength;
if (key == originalKey) {
return -1; if (key == originalKey) return -1;
}
} }
} }
@ -159,13 +168,15 @@ byte var_store_copy_from_key(struct VariableStore* store, int key, void* dst)
if (key < 0) { if (key < 0) {
return 1; return 1;
} }
//printf_wrap("Var store: copy from key %d \n", key);
memcpy(dst, store->container[key].dataPtr, (size_t) get_size_of_type(store->container[key].type)); memcpy(dst, store->container[key].dataPtr, (size_t) get_size_of_type(store->container[key].type));
return 0; return 0;
} }
byte var_store_copy(struct VariableStore* store, char* varName, void* dst) byte var_store_copy(struct VariableStore* store, char* varName, void* dst)
{ {
return var_store_copy_from_key(store, var_store_get_key(store, varName), dst); int key = var_store_get_key(store, varName);
return var_store_copy_from_key(store, key, dst);
} }
int var_store_get_int(struct VariableStore* store, char* varName) int var_store_get_int(struct VariableStore* store, char* varName)
@ -190,10 +201,10 @@ float var_store_get_float(struct VariableStore* store, char* varName)
void var_store_print(struct VariableStore* store) void var_store_print(struct VariableStore* store)
{ {
printf("== VarStore report (%d items) ==\n", store->length); printf_wrap("== VarStore report (%d items) ==\n", store->length);
for (int i = 0; i < store->allocatedLength; i++) { for (int i = 0; i < store->allocatedLength; i++) {
if (store->container[i].type != 0) { if (store->container[i].type != 0) {
printf( printf_wrap(
"key: %d, '%s' = %s; ", "key: %d, '%s' = %s; ",
i, i,
store->container[i].namePtr, store->container[i].namePtr,
@ -201,5 +212,5 @@ void var_store_print(struct VariableStore* store)
); );
} }
} }
printf("== end of report\n"); printf_wrap("== end of report\n");
} }

View file

@ -3,7 +3,8 @@
#ifndef VAR_STORE_H_ #ifndef VAR_STORE_H_
#define VAR_STORE_H_ #define VAR_STORE_H_
#define VAR_STORE_INITIAL_ALLOC_LENGTH 32 #define VAR_STORE_DEBUG_LEVEL (G_DEBUG_LEVEL)
#define VAR_STORE_INITIAL_ALLOC_LENGTH 64
/** /**
@ -32,6 +33,9 @@ struct VariableStore {
struct VariableStore* var_store_init(); struct VariableStore* var_store_init();
// add to the store some useful constants (like NULL constructor)
void var_store_add_constants(struct VariableStore* store);
int var_store_hash_name(struct VariableStore* store, char* varName); int var_store_hash_name(struct VariableStore* store, char* varName);
// get a pointer to the area of memory where is store the variable // get a pointer to the area of memory where is store the variable

View file

@ -1,3 +1,5 @@
#include "../src/config.h"
#include "../src/utils.h"
#include "./test_utils.h" #include "./test_utils.h"
#include "./test_evaluation.h" #include "./test_evaluation.h"
#include "./test_line_processing.h" #include "./test_line_processing.h"
@ -7,8 +9,10 @@
int main() int main()
{ {
printf("== UNIT TESTS == \n"); int var1 = 0x34;
printf_wrap("== UNIT TESTS == \n");
test_utils(); test_utils();
printf_wrap("ça commence à faire chier jpp\n");
test_var_store(); test_var_store();
test_stack(); test_stack();
test_evaluation(); test_evaluation();

View file

@ -9,7 +9,7 @@
void test_evaluation() void test_evaluation()
{ {
printf("== test evaluation == \n"); printf_wrap("== test evaluation == \n");
struct StateContainer* state = state_init(); struct StateContainer* state = state_init();
@ -21,6 +21,14 @@ void test_evaluation()
assert(resType == TYPE_INT); assert(resType == TYPE_INT);
assert(-4 == resVal); assert(-4 == resVal);
evaluate(state, " - 6 ", &resVal, &resType);
assert(resType == TYPE_INT);
assert(-6 == resVal);
evaluate(state, " 1+ (- 45 ) ", &resVal, &resType);
assert(resType == TYPE_INT);
assert(-44 == resVal);
evaluate(state, "-(4+9)+1", &resVal, &resType); evaluate(state, "-(4+9)+1", &resVal, &resType);
assert(resType == TYPE_INT); assert(resType == TYPE_INT);
assert(-12 == resVal); assert(-12 == resVal);
@ -53,6 +61,8 @@ void test_evaluation()
assert(resType == TYPE_FLOAT); assert(resType == TYPE_FLOAT);
assert(float_almost_equal(-0.4, get_float_from_int_rep(resVal))); assert(float_almost_equal(-0.4, get_float_from_int_rep(resVal)));
/* FUNCTIONS */
evaluate(state, "sqrt(2)-1", &resVal, &resType); evaluate(state, "sqrt(2)-1", &resVal, &resType);
assert(resType == TYPE_FLOAT); assert(resType == TYPE_FLOAT);
assert(float_almost_equal(0.41421, get_float_from_int_rep(resVal))); assert(float_almost_equal(0.41421, get_float_from_int_rep(resVal)));
@ -69,19 +79,48 @@ void test_evaluation()
assert(resType == TYPE_FLOAT); assert(resType == TYPE_FLOAT);
assert(float_almost_equal(1, get_float_from_int_rep(resVal))); assert(float_almost_equal(1, get_float_from_int_rep(resVal)));
evaluate(state, "ceil(1.5)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(2 == resVal);
evaluate(state, "floor(1.5)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(1 == resVal);
evaluate(state, "floor(1.001)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(1 == resVal);
evaluate(state, "random_int(1, 100)", &resVal, &resType); evaluate(state, "random_int(1, 100)", &resVal, &resType);
assert(resType == TYPE_INT); assert(resType == TYPE_INT);
printf(" - random int: %d \n", resVal); printf_wrap(" - random int: %d \n", resVal);
evaluate(state, "abs(2)+abs(-2)", &resVal, &resType); evaluate(state, "abs(2)+abs(-2)", &resVal, &resType);
assert(resType == TYPE_INT); assert(resType == TYPE_INT);
assert(4 == resVal); assert(4 == resVal);
evaluate(state, "max(25, 4)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(25 == resVal);
evaluate(state, "max(-25, 42)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(42 == resVal);
evaluate(state, "max( (1+1)^(6+1-1) , 4+2)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(64 == resVal);
evaluate(state, "max(floor(exp(1))^(4+1) , -2)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(32 == resVal);
// testing function composition is important // testing function composition is important
evaluate(state, "abs(abs(-2))", &resVal, &resType); evaluate(state, "abs(abs(-2))", &resVal, &resType);
assert(resType == TYPE_INT); assert(resType == TYPE_INT);
assert(2 == resVal); assert(2 == resVal);
/* COMPARAISON OPERATORS */
evaluate(state, "2 = 2", &resVal, &resType); evaluate(state, "2 = 2", &resVal, &resType);
assert(resType == TYPE_INT); assert(resType == TYPE_INT);
assert(1 == resVal); assert(1 == resVal);
@ -142,6 +181,7 @@ void test_evaluation()
assert(resType == TYPE_FLOAT); assert(resType == TYPE_FLOAT);
assert(float_almost_equal(5.3, get_float_from_int_rep(resVal))); assert(float_almost_equal(5.3, get_float_from_int_rep(resVal)));
/* VARIABLES */
int ex = 43; int ex = 43;
var_store_set(state->varStore, "var", TYPE_INT, (void*) &ex); var_store_set(state->varStore, "var", TYPE_INT, (void*) &ex);
evaluate(state, "var", &resVal, &resType); evaluate(state, "var", &resVal, &resType);
@ -161,6 +201,27 @@ void test_evaluation()
evaluate(state, "abs((var2^2)-((var-41)^2))+2", &resVal, &resType); evaluate(state, "abs((var2^2)-((var-41)^2))+2", &resVal, &resType);
assert(resType == TYPE_INT); assert(resType == TYPE_INT);
printf("actually got: %d \n", resVal); printf_wrap("actually got: %d \n", resVal);
assert(7 == resVal); assert(7 == resVal);
/* TYPE FUNCS */
evaluate(state, "is_number(123)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(resVal);
evaluate(state, "is_number(-25.5)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(resVal);
evaluate(state, "is_number(NULL)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(!resVal);
evaluate(state, "is_null(NULL)", &resVal, &resType);
assert(resType == TYPE_INT);
assert(resVal);
evaluate(state, "(is_null(NULL) & is_number(42)) | 0", &resVal, &resType);
assert(resType == TYPE_INT);
assert(resVal);
} }

View file

@ -11,7 +11,7 @@
void test_line_processing() void test_line_processing()
{ {
printf("== test line processing == \n"); printf_wrap("== test line processing == \n");
// test string manipulation // test string manipulation
assert(!recognize_word("", "hello")); assert(!recognize_word("", "hello"));
@ -49,7 +49,7 @@ void test_line_processing()
assert(process_line(state1, "#")); assert(process_line(state1, "#"));
assert(process_line(state1, "# some random comment")); assert(process_line(state1, "# some random comment"));
assert(process_line(state1, "set VAR_A to 8.5")); assert(process_line(state1, "set VAR_A to 8.5"));
printf("%d \n", var_store_get_int(state1->varStore, "VAR_A")); printf_wrap("%d \n", var_store_get_int(state1->varStore, "VAR_A"));
assert(float_almost_equal(8.5, var_store_get_float(state1->varStore, "VAR_A"))); assert(float_almost_equal(8.5, var_store_get_float(state1->varStore, "VAR_A")));
assert(process_line(state1, "set VAR_B to 1.5")); assert(process_line(state1, "set VAR_B to 1.5"));
@ -113,7 +113,7 @@ void test_line_processing()
process_script(state2, lines4); process_script(state2, lines4);
assert(!state2->skipping); assert(!state2->skipping);
printf("got i: %d \n", var_store_get_int(state2->varStore, "i")); printf_wrap("got i: %d \n", var_store_get_int(state2->varStore, "i"));
assert(9 == var_store_get_int(state2->varStore, "i")); assert(9 == var_store_get_int(state2->varStore, "i"));
// test break keyword // test break keyword
@ -127,7 +127,7 @@ void test_line_processing()
process_script(state2, lines5); process_script(state2, lines5);
assert(!state2->skipping); assert(!state2->skipping);
printf("got i: %d \n", var_store_get_int(state2->varStore, "i")); printf_wrap("got i: %d \n", var_store_get_int(state2->varStore, "i"));
assert(10 == var_store_get_int(state2->varStore, "i")); assert(10 == var_store_get_int(state2->varStore, "i"));
// test continue keyword // test continue keyword

View file

@ -6,7 +6,7 @@
void test_stack() void test_stack()
{ {
printf("== test stack == \n"); printf_wrap("== test stack == \n");
int res; int res;
struct IntStack* stack1 = int_stack_init(); struct IntStack* stack1 = int_stack_init();
@ -28,7 +28,7 @@ void test_stack()
assert(int_stack_push(stack1, 2025)); assert(int_stack_push(stack1, 2025));
assert(int_stack_push(stack1, 2026)); assert(int_stack_push(stack1, 2026));
assert(16 == stack1->allocated); assert(16 == stack1->allocated);
printf("%d \n", int_stack_length(stack1)); printf_wrap("%d \n", int_stack_length(stack1));
assert(9 == int_stack_length(stack1)); assert(9 == int_stack_length(stack1));
int_stack_print(stack1); int_stack_print(stack1);

View file

@ -6,7 +6,7 @@
void test_utils() void test_utils()
{ {
printf("== test utils == \n"); printf_wrap("== test utils == \n");
// test int parsing // test int parsing
char test1[] = "151087"; char test1[] = "151087";

View file

@ -5,10 +5,40 @@
void test_var_store() void test_var_store()
{ {
printf("== test var store == \n"); printf_wrap("== test var store == \n");
struct VariableStore* store = var_store_init(); struct VariableStore* store = var_store_init();
// hash function test
int hash1, hash2, hash3 = 0;
hash1 = var_store_hash_name(store, "a");
hash2 = var_store_hash_name(store, "a");
hash3 = var_store_hash_name(store, "a");
assert(hash1 == hash2);
assert(hash2 == hash3);
assert(hash1 == hash3);
hash1 = var_store_hash_name(store, "i");
hash2 = var_store_hash_name(store, "i");
hash3 = var_store_hash_name(store, "i");
assert(hash1 == hash2);
assert(hash2 == hash3);
assert(hash1 == hash3);
var_store_print(store);
int originalLength = store->length;
int varEx = 42;
int originalHash = var_store_hash_name(store, "i");
var_store_set(store, "i", TYPE_INT, &varEx);
assert(originalHash == var_store_hash_name(store, "i"));
assert(TYPE_INT == var_store_get_type(store, "i"));
assert(originalLength+1 == store->length);
assert(42 == var_store_get_int(store, "i"));
// sequential assignement
int iDest = 0; int iDest = 0;
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
var_store_set(store, "i", TYPE_INT, &i); var_store_set(store, "i", TYPE_INT, &i);

1
wasm.sh Normal file
View file

@ -0,0 +1 @@
clang -Os -fno-builtin -Wall -Wextra -Wswitch-enum --target=wasm32 --no-standard-libraries -Wl,--export=wasm_info -Wl,--no-entry -Wl,--allow-undefined -o wasm/langatator.wasm ./wasm/wasm.c

2
wasm/config_env_wasm.h Normal file
View file

@ -0,0 +1,2 @@
// the config file for wasm
#define PRINT_MODE 1

81
wasm/emscripten.c Normal file
View file

@ -0,0 +1,81 @@
#include "emscripten.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
EM_JS(void, log_to_js, (char* buff, size_t len), {
log_intake(buff, len);
});
int printf_wrap(const char* format, ...) {
va_list args;
va_start(args, format);
char* out;
vsprintf(out, format, args);
char* sharedPos = (char*) malloc(strlen(out) * sizeof(char));
strcpy(sharedPos, out);
log_to_js((void*) sharedPos, strlen(out));
va_end(args);
return 1;
}
#include "../src/config.h"
#include "../src/utils.h"
#include "../src/types.h"
#include "../src/state.h"
#include "../src/line_processing.h"
struct Result {
byte type;
int data;
};
EMSCRIPTEN_KEEPALIVE
void* wasm_init_state()
{
struct StateContainer* ptr = state_init();
return (void*) ptr;
}
EMSCRIPTEN_KEEPALIVE
void* wasm_process_line(void* state, char* line)
{
struct Result* res = malloc(sizeof(struct Result));
process_line(state, line);
res->type = ((struct StateContainer*) state)->lastEvaluationType;
res->data = ((struct StateContainer*) state)->lastEvaluationResult;
return (void*) res;
}
EMSCRIPTEN_KEEPALIVE
void wasm_process_script(char* scriptLines)
{
printf_wrap("Will process script \"%s\" \n", scriptLines);
struct StateContainer* state = state_init();
process_script(state, scriptLines);
}
// very dangerous indeed
EMSCRIPTEN_KEEPALIVE
int wasm_get_type_from_ref(void* ref) {
return ((struct Result*) ref)->type;
}
EMSCRIPTEN_KEEPALIVE
int wasm_get_int_from_ref(void* ref) {
return ((struct Result*) ref)->data;
}
// EMSCRIPTEN_KEEPALIVE
// int wasm_info(char* lines)
// {
// struct StateContainer* state = state_init();
// process_script(state, lines);
// return state->lastEvaluationResult;
// }

1
wasm/emscripten_raw.html Normal file

File diff suppressed because one or more lines are too long

1
wasm/emscripten_raw.js Normal file

File diff suppressed because one or more lines are too long

BIN
wasm/emscripten_raw.wasm Executable file

Binary file not shown.

69
wasm/index.html Normal file
View file

@ -0,0 +1,69 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Langatator demo</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css">
<style>
* {
box-sizing: border-box;
}
.container {
width: 90%;
margin: 0 auto;
}
.form {
width: 100%;
margin-top: 1em;
}
#script-input {
width: 100%;
min-width: 100%;
max-width: 100%;
display: block;
min-height: 20em;
}
.submit-btn {
margin-top: 1em;
}
</style>
</head>
<body>
<div class="container">
<h1>Langatator demo</h1>
<a href="https://gitlab.com/lefuturiste/langatator">The git repository</a>
<div class="form">
<textarea id="script-input"></textarea>
<button
class="submit-btn"
onclick="submitScript()"
>
Process script!
</button>
</div>
<div class="console">
<pre id="console-output">
</pre>
</div>
</div>
<script>
// const oldLog = console.log;
// console.log = function (message) {
// oldLog.apply(console, ['captured', ...arguments]);
// };
</script>
<script src="./langatator_adapter.js"></script>
<script src="./script.js"></script>
</body>
</html>

File diff suppressed because one or more lines are too long

BIN
wasm/langatator_adapter.wasm Executable file

Binary file not shown.

93
wasm/script.js Normal file
View file

@ -0,0 +1,93 @@
'use strict';
// let app = document.getElementById("app");
// let wasm = null;
// let iota = 0;
// function cstrlen(mem, ptr) {
// let len = 0;
// while (mem[ptr] != 0) {
// len++;
// ptr++;
// }
// return len;
// }
// function cstr_by_ptr(mem_buffer, ptr) {
// const mem = new Uint8Array(mem_buffer);
// const len = cstrlen(mem, ptr);
// const bytes = new Uint8Array(mem_buffer, ptr, len);
// return new TextDecoder().decode(bytes);
// }
// function platform_panic(file_path_ptr, line, message_ptr) {
// const buffer = wasm.instance.exports.memory.buffer;
// const file_path = cstr_by_ptr(buffer, file_path_ptr);
// const message = cstr_by_ptr(buffer, message_ptr);
// console.error(file_path+":"+line+": "+message);
// }
// function platform_log(message_ptr) {
// const buffer = wasm.instance.exports.memory.buffer;
// const message = cstr_by_ptr(buffer, message_ptr);
// console.log(message);
// }
// WebAssembly.instantiateStreaming(fetch('langatator.wasm'), {
// env: {
// platform_panic,
// platform_log
// }
// }).then((w) => {
// wasm = w;
// console.log(wasm.instance.exports.wasm_info());
// //const buffer = wasm.instance.exports.memory.buffer;
// });
const consoleOutput = document.getElementById('console-output')
function log_intake(ptr, len) {
let line = ""
for (var i = 0; i < len; i++) {
let val = Module.getValue(ptr+i, 'i8')
line = line + String.fromCharCode(val)
}
console.log('Got line', line)
// const pre= document.createElement('pre')
// consoleOutput.appendChild(pre)
}
Module.onRuntimeInitialized = async _ => {
const api = {
init: Module.cwrap('wasm_init_state', 'number', []),
processLine: Module.cwrap('wasm_process_line', 'number', ['number', 'string']),
getTypeFromRef: Module.cwrap('wasm_get_type_from_ref', 'number', ['number']),
getIntFromRef: Module.cwrap('wasm_get_int_from_ref', 'number', ['number']),
// standalone (integrated state initialization)
processScript: Module.cwrap('wasm_process_script', 'number', ['string']),
};
console.log(api);
// const ref = api.init();
// console.log(`Got ref: ${ref}`);
window.processLine = (line) => {
const resultRef = api.processLine(ref, line);
console.log(`Got result ref: ${resultRef}`);
console.log(api.getTypeFromRef(resultRef));
console.log(api.getIntFromRef(resultRef));
}
window.submitScript = () => {
const textarea = document.getElementById('script-input')
api.processScript(textarea.value)
}
};

0
wasm/style.css Normal file
View file

44
wasm/wasm.c Normal file
View file

@ -0,0 +1,44 @@
#include <stdlib.h>
#include "../src/config.h"
#define CONFIG_PRINT_METHOD PRINT_METHOD_WASM
#include "../src/utils.h"
#include "../src/types.h"
#include "../src/state.h"
#include "../src/line_processing.h"
void* wasm_init_state()
{
struct StateContainer* ptr = state_init();
return (void*) ptr;
}
void* wasm_process_line(void* state, char* line)
{
struct Result* res = malloc(sizeof(struct Result));
process_line(state, line);
res->type = ((struct StateContainer*) state)->lastEvaluationType;
res->data = ((struct StateContainer*) state)->lastEvaluationResult;
return (void*) res;
}
// very dangerous indeed
int wasm_get_type_from_ref(void* ref) {
return ((struct Result*) ref)->type;
}
int wasm_get_int_from_ref(void* ref) {
return ((struct Result*) ref)->data;
}
// EMSCRIPTEN_KEEPALIVE
// int wasm_info(char* lines)
// {
// struct StateContainer* state = state_init();
// process_script(state, lines);
// return state->lastEvaluationResult;
// }