├── .github
└── workflows
│ └── build.yml
├── .gitignore
├── .idea
├── CustomInspectionsConfig.xml
├── inspectionProfiles
│ └── Project_Default.xml
├── misc.xml
├── remote-targets.xml
└── vcs.xml
├── CHANGES.md
├── Cargo.lock
├── Cargo.toml
├── LICENSE.md
├── README.md
├── examples
├── caluc
│ ├── common.rat
│ ├── interpreter.rat
│ ├── lexer.rat
│ ├── main.rat
│ └── parser.rat
├── decorator.rat
├── linked_list.rat
└── rock_paper_scissors.rat
├── src
├── ast.rs
├── common.rs
├── error.rs
├── interpreter
│ ├── builtin.rs
│ ├── mod.rs
│ ├── random.rs
│ └── value.rs
├── lexer.rs
├── main.rs
├── parser.rs
├── repl.rs
└── token.rs
├── std
├── array.rat
├── collection.rat
├── math.rat
├── random.rat
└── string.rat
└── tests
├── bad
├── addition.rat
├── assert.rat
├── class_function_without_self.rat
├── comment.rat
├── function_same_name_arguments.rat
├── no_argument_class_function.rat
└── uninitialized_variable_assignment.rat
├── good
├── arrow_return.rat
├── binary_logic.rat
├── binaryops.rat
├── builtins.rat
├── class.rat
├── class_inheritance.rat
├── class_instance_is_instance_of.rat
├── closures.rat
├── dictionaries.rat
├── fib.rat
├── field_access_duplicate_run.rat
├── first_argument_variadic.rat
├── function_consuming_endline.rat
├── if.rat
├── if_statement_expression_body.rat
├── import.rat
├── import_test.rat
├── index_assignment.rat
├── lambda.rat
├── list_comprehension.rat
├── lists_tuples.rat
├── multiple_assignment.rat
├── mutation_assignment.rat
├── namespaces.rat
├── number_bases.rat
├── postfix.rat
├── prefix_postfix_mutation.rat
├── range_with_field_access.rat
├── short_circut.rat
├── star_expressions.rat
├── static_fields.rat
├── std_lib.rat
├── string_multiplication.rat
├── while.rat
└── wildcard_import.rat
└── test.py
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Tests
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | test_ubuntu:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@v2
10 | - name: Installing Rust toolchain
11 | uses: actions-rs/toolchain@v1
12 | with:
13 | toolchain: stable
14 | override: true
15 | - name: Running tests
16 | run: |
17 | cd ${{ github.workspace }}
18 | python3 -m pip install colorama
19 | python3 ./tests/test.py -i release
20 | test_windows:
21 | runs-on: windows-latest
22 | steps:
23 | - uses: actions/checkout@v2
24 | - name: Installing Rust toolchain
25 | uses: actions-rs/toolchain@v1
26 | with:
27 | toolchain: stable
28 | override: true
29 | - name: Running tests
30 | run: |
31 | cd ${{ github.workspace }}
32 | python -m pip install colorama
33 | python ./tests/test.py -i release
34 | test_macos:
35 | runs-on: macos-latest
36 | steps:
37 | - uses: actions/checkout@v2
38 | - name: Installing Rust toolchain
39 | uses: actions-rs/toolchain@v1
40 | with:
41 | toolchain: stable
42 | override: true
43 | - name: Running tests
44 | run: |
45 | cd ${{ github.workspace }}
46 | python3 -m pip install colorama
47 | python3 ./tests/test.py -i release
48 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Personal ignores
2 | /local
3 | /*test*.*
4 |
5 | # Generated by Cargo
6 | # will have compiled files and executables
7 | debug/
8 | target/
9 |
10 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
11 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
12 | Cargo.lock
13 |
14 | # These are backup files generated by rustfmt
15 | **/*.rs.bk
16 |
17 | # MSVC Windows builds of rustc generate these, which store debugging information
18 | *.pdb
19 |
20 | # Byte-compiled / optimized / DLL files
21 | __pycache__/
22 | *.py[cod]
23 | *$py.class
24 |
25 | # C extensions
26 | *.so
27 |
28 | # Distribution / packaging
29 | .Python
30 | build/
31 | develop-eggs/
32 | dist/
33 | downloads/
34 | eggs/
35 | .eggs/
36 | lib/
37 | lib64/
38 | parts/
39 | sdist/
40 | var/
41 | wheels/
42 | share/python-wheels/
43 | *.egg-info/
44 | .installed.cfg
45 | *.egg
46 | MANIFEST
47 |
48 | # PyInstaller
49 | # Usually these files are written by a python script from a template
50 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
51 | *.manifest
52 | *.spec
53 |
54 | # Installer logs
55 | pip-log.txt
56 | pip-delete-this-directory.txt
57 |
58 | # Unit test / coverage reports
59 | htmlcov/
60 | .tox/
61 | .nox/
62 | .coverage
63 | .coverage.*
64 | .cache
65 | nosetests.xml
66 | coverage.xml
67 | *.cover
68 | *.py,cover
69 | .hypothesis/
70 | .pytest_cache/
71 | cover/
72 |
73 | # Translations
74 | *.mo
75 | *.pot
76 |
77 | # Django stuff:
78 | *.log
79 | local_settings.py
80 | db.sqlite3
81 | db.sqlite3-journal
82 |
83 | # Flask stuff:
84 | instance/
85 | .webassets-cache
86 |
87 | # Scrapy stuff:
88 | .scrapy
89 |
90 | # Sphinx documentation
91 | docs/_build/
92 |
93 | # PyBuilder
94 | .pybuilder/
95 |
96 | # Jupyter Notebook
97 | .ipynb_checkpoints
98 |
99 | # IPython
100 | profile_default/
101 | ipython_config.py
102 |
103 | # pyenv
104 | # For a library or package, you might want to ignore these files since the code is
105 | # intended to run in multiple environments; otherwise, check them in:
106 | # .python-version
107 |
108 | # pipenv
109 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
110 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
111 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
112 | # install all needed dependencies.
113 | #Pipfile.lock
114 |
115 | # poetry
116 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
117 | # This is especially recommended for binary packages to ensure reproducibility, and is more
118 | # commonly ignored for libraries.
119 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
120 | #poetry.lock
121 |
122 | # pdm
123 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
124 | #pdm.lock
125 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
126 | # in version control.
127 | # https://pdm.fming.dev/#use-with-ide
128 | .pdm.toml
129 |
130 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
131 | __pypackages__/
132 |
133 | # Celery stuff
134 | celerybeat-schedule
135 | celerybeat.pid
136 |
137 | # SageMath parsed files
138 | *.sage.py
139 |
140 | # Environments
141 | .env
142 | .venv
143 | env/
144 | venv/
145 | ENV/
146 | env.bak/
147 | venv.bak/
148 |
149 | # Spyder project settings
150 | .spyderproject
151 | .spyproject
152 |
153 | # Rope project settings
154 | .ropeproject
155 |
156 | # mkdocs documentation
157 | /site
158 |
159 | # mypy
160 | .mypy_cache/
161 | .dmypy.json
162 | dmypy.json
163 |
164 | # Pyre type checker
165 | .pyre/
166 |
167 | # pytype static type analyzer
168 | .pytype/
169 |
170 | # Cython debug symbols
171 | cython_debug/
172 |
173 | # PyCharm
174 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
175 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
176 | # and can be added to the global gitignore or merged into this file. For a more nuclear
177 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
178 | #.idea/
179 |
180 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
181 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
182 |
183 | # User-specific stuff
184 | .idea/**/workspace.xml
185 | .idea/**/tasks.xml
186 | .idea/**/usage.statistics.xml
187 | .idea/**/dictionaries
188 | .idea/**/shelf
189 |
190 | # AWS User-specific
191 | .idea/**/aws.xml
192 |
193 | # Generated files
194 | .idea/**/contentModel.xml
195 |
196 | # Sensitive or high-churn files
197 | .idea/**/dataSources/
198 | .idea/**/dataSources.ids
199 | .idea/**/dataSources.local.xml
200 | .idea/**/sqlDataSources.xml
201 | .idea/**/dynamic.xml
202 | .idea/**/uiDesigner.xml
203 | .idea/**/dbnavigator.xml
204 |
205 | # Gradle
206 | .idea/**/gradle.xml
207 | .idea/**/libraries
208 |
209 | # Gradle and Maven with auto-import
210 | # When using Gradle or Maven with auto-import, you should exclude module files,
211 | # since they will be recreated, and may cause churn. Uncomment if using
212 | # auto-import.
213 | # .idea/artifacts
214 | # .idea/compiler.xml
215 | # .idea/jarRepositories.xml
216 | # .idea/modules.xml
217 | # .idea/*.iml
218 | # .idea/modules
219 | # *.iml
220 | # *.ipr
221 |
222 | # CMake
223 | cmake-build-*/
224 |
225 | # Mongo Explorer plugin
226 | .idea/**/mongoSettings.xml
227 |
228 | # File-based project format
229 | *.iws
230 |
231 | # IntelliJ
232 | out/
233 |
234 | # mpeltonen/sbt-idea plugin
235 | .idea_modules/
236 |
237 | # JIRA plugin
238 | atlassian-ide-plugin.xml
239 |
240 | # Cursive Clojure plugin
241 | .idea/replstate.xml
242 |
243 | # SonarLint plugin
244 | .idea/sonarlint/
245 |
246 | # Crashlytics plugin (for Android Studio and IntelliJ)
247 | com_crashlytics_export_strings.xml
248 | crashlytics.properties
249 | crashlytics-build.properties
250 | fabric.properties
251 |
252 | # Editor-based Rest Client
253 | .idea/httpRequests
254 |
255 | # Android studio 3.1+ serialized cache file
256 | .idea/caches/build_file_checksums.ser
257 |
258 | .vscode/*
259 | !.vscode/settings.json
260 | !.vscode/tasks.json
261 | !.vscode/launch.json
262 | !.vscode/extensions.json
263 | !.vscode/*.code-snippets
264 |
265 | # Local History for Visual Studio Code
266 | .history/
267 |
268 | # Built Visual Studio Code Extensions
269 | *.vsix
270 |
--------------------------------------------------------------------------------
/.idea/CustomInspectionsConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Just do not write this.
7 | Forbidden (\w+)
8 | Allowed $1
9 | Warning
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
18 |
19 |
20 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/remote-targets.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CHANGES.md:
--------------------------------------------------------------------------------
1 | ## Added
2 | - wildcard imports `from module import *`
3 | - dump function `dump()`
4 | - in operator `x in y`
5 | - short-circuiting `and` and `or` operators
6 | - if statement bodies can now be an expression or block
7 | - example folder and Caluc example program
8 | - default argument for `dict.get()` function
9 | - array std lib module
10 | - `any` `all` `max` `sum` `min`
11 | - collection std lib module
12 | - `Counter` `OrderedDict`
13 | - string std lib module
14 | - `is_alpha` `is_digit` `is_space` `is_alnum`
15 | ## Changed
16 | - class instances now hold a reference to their main parent class
17 | - class instances can no longer create new fields outside of `new()`
18 | - `==` operator can now compare a class to a class instance and will return `true` if the class instance is an instance of the class
19 | - It is worth noting that this is likely temporary and will be changed to a more explicit method in the future.
20 |
21 | ## Removed
22 | - json stdlib module
23 |
--------------------------------------------------------------------------------
/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "rattlescript"
7 | version = "0.2.2"
8 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rattlescript"
3 | version = "0.2.2"
4 | edition = "2021"
5 | authors = ["Haven Selph "]
6 | description = "A simple scripting language written in Rust."
7 | keywords = ["scripting", "language", "rust", "rattlescript"]
8 | repository = "https://github.com/HavenSelph/rattlescript"
9 | license-file = "./LICENSE.md"
10 | readme = "./README.md"
11 |
12 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
13 |
14 | [dependencies]
15 | # None!
16 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | # GNU GENERAL PUBLIC LICENSE
2 |
3 | Version 3, 29 June 2007
4 |
5 | Copyright (C) 2007 Free Software Foundation, Inc.
6 |
7 |
8 | Everyone is permitted to copy and distribute verbatim copies of this
9 | license document, but changing it is not allowed.
10 |
11 | ## Preamble
12 |
13 | The GNU General Public License is a free, copyleft license for
14 | software and other kinds of works.
15 |
16 | The licenses for most software and other practical works are designed
17 | to take away your freedom to share and change the works. By contrast,
18 | the GNU General Public License is intended to guarantee your freedom
19 | to share and change all versions of a program--to make sure it remains
20 | free software for all its users. We, the Free Software Foundation, use
21 | the GNU General Public License for most of our software; it applies
22 | also to any other work released this way by its authors. You can apply
23 | it to your programs, too.
24 |
25 | When we speak of free software, we are referring to freedom, not
26 | price. Our General Public Licenses are designed to make sure that you
27 | have the freedom to distribute copies of free software (and charge for
28 | them if you wish), that you receive source code or can get it if you
29 | want it, that you can change the software or use pieces of it in new
30 | free programs, and that you know you can do these things.
31 |
32 | To protect your rights, we need to prevent others from denying you
33 | these rights or asking you to surrender the rights. Therefore, you
34 | have certain responsibilities if you distribute copies of the
35 | software, or if you modify it: responsibilities to respect the freedom
36 | of others.
37 |
38 | For example, if you distribute copies of such a program, whether
39 | gratis or for a fee, you must pass on to the recipients the same
40 | freedoms that you received. You must make sure that they, too, receive
41 | or can get the source code. And you must show them these terms so they
42 | know their rights.
43 |
44 | Developers that use the GNU GPL protect your rights with two steps:
45 | (1) assert copyright on the software, and (2) offer you this License
46 | giving you legal permission to copy, distribute and/or modify it.
47 |
48 | For the developers' and authors' protection, the GPL clearly explains
49 | that there is no warranty for this free software. For both users' and
50 | authors' sake, the GPL requires that modified versions be marked as
51 | changed, so that their problems will not be attributed erroneously to
52 | authors of previous versions.
53 |
54 | Some devices are designed to deny users access to install or run
55 | modified versions of the software inside them, although the
56 | manufacturer can do so. This is fundamentally incompatible with the
57 | aim of protecting users' freedom to change the software. The
58 | systematic pattern of such abuse occurs in the area of products for
59 | individuals to use, which is precisely where it is most unacceptable.
60 | Therefore, we have designed this version of the GPL to prohibit the
61 | practice for those products. If such problems arise substantially in
62 | other domains, we stand ready to extend this provision to those
63 | domains in future versions of the GPL, as needed to protect the
64 | freedom of users.
65 |
66 | Finally, every program is threatened constantly by software patents.
67 | States should not allow patents to restrict development and use of
68 | software on general-purpose computers, but in those that do, we wish
69 | to avoid the special danger that patents applied to a free program
70 | could make it effectively proprietary. To prevent this, the GPL
71 | assures that patents cannot be used to render the program non-free.
72 |
73 | The precise terms and conditions for copying, distribution and
74 | modification follow.
75 |
76 | ## TERMS AND CONDITIONS
77 |
78 | ### 0. Definitions.
79 |
80 | "This License" refers to version 3 of the GNU General Public License.
81 |
82 | "Copyright" also means copyright-like laws that apply to other kinds
83 | of works, such as semiconductor masks.
84 |
85 | "The Program" refers to any copyrightable work licensed under this
86 | License. Each licensee is addressed as "you". "Licensees" and
87 | "recipients" may be individuals or organizations.
88 |
89 | To "modify" a work means to copy from or adapt all or part of the work
90 | in a fashion requiring copyright permission, other than the making of
91 | an exact copy. The resulting work is called a "modified version" of
92 | the earlier work or a work "based on" the earlier work.
93 |
94 | A "covered work" means either the unmodified Program or a work based
95 | on the Program.
96 |
97 | To "propagate" a work means to do anything with it that, without
98 | permission, would make you directly or secondarily liable for
99 | infringement under applicable copyright law, except executing it on a
100 | computer or modifying a private copy. Propagation includes copying,
101 | distribution (with or without modification), making available to the
102 | public, and in some countries other activities as well.
103 |
104 | To "convey" a work means any kind of propagation that enables other
105 | parties to make or receive copies. Mere interaction with a user
106 | through a computer network, with no transfer of a copy, is not
107 | conveying.
108 |
109 | An interactive user interface displays "Appropriate Legal Notices" to
110 | the extent that it includes a convenient and prominently visible
111 | feature that (1) displays an appropriate copyright notice, and (2)
112 | tells the user that there is no warranty for the work (except to the
113 | extent that warranties are provided), that licensees may convey the
114 | work under this License, and how to view a copy of this License. If
115 | the interface presents a list of user commands or options, such as a
116 | menu, a prominent item in the list meets this criterion.
117 |
118 | ### 1. Source Code.
119 |
120 | The "source code" for a work means the preferred form of the work for
121 | making modifications to it. "Object code" means any non-source form of
122 | a work.
123 |
124 | A "Standard Interface" means an interface that either is an official
125 | standard defined by a recognized standards body, or, in the case of
126 | interfaces specified for a particular programming language, one that
127 | is widely used among developers working in that language.
128 |
129 | The "System Libraries" of an executable work include anything, other
130 | than the work as a whole, that (a) is included in the normal form of
131 | packaging a Major Component, but which is not part of that Major
132 | Component, and (b) serves only to enable use of the work with that
133 | Major Component, or to implement a Standard Interface for which an
134 | implementation is available to the public in source code form. A
135 | "Major Component", in this context, means a major essential component
136 | (kernel, window system, and so on) of the specific operating system
137 | (if any) on which the executable work runs, or a compiler used to
138 | produce the work, or an object code interpreter used to run it.
139 |
140 | The "Corresponding Source" for a work in object code form means all
141 | the source code needed to generate, install, and (for an executable
142 | work) run the object code and to modify the work, including scripts to
143 | control those activities. However, it does not include the work's
144 | System Libraries, or general-purpose tools or generally available free
145 | programs which are used unmodified in performing those activities but
146 | which are not part of the work. For example, Corresponding Source
147 | includes interface definition files associated with source files for
148 | the work, and the source code for shared libraries and dynamically
149 | linked subprograms that the work is specifically designed to require,
150 | such as by intimate data communication or control flow between those
151 | subprograms and other parts of the work.
152 |
153 | The Corresponding Source need not include anything that users can
154 | regenerate automatically from other parts of the Corresponding Source.
155 |
156 | The Corresponding Source for a work in source code form is that same
157 | work.
158 |
159 | ### 2. Basic Permissions.
160 |
161 | All rights granted under this License are granted for the term of
162 | copyright on the Program, and are irrevocable provided the stated
163 | conditions are met. This License explicitly affirms your unlimited
164 | permission to run the unmodified Program. The output from running a
165 | covered work is covered by this License only if the output, given its
166 | content, constitutes a covered work. This License acknowledges your
167 | rights of fair use or other equivalent, as provided by copyright law.
168 |
169 | You may make, run and propagate covered works that you do not convey,
170 | without conditions so long as your license otherwise remains in force.
171 | You may convey covered works to others for the sole purpose of having
172 | them make modifications exclusively for you, or provide you with
173 | facilities for running those works, provided that you comply with the
174 | terms of this License in conveying all material for which you do not
175 | control copyright. Those thus making or running the covered works for
176 | you must do so exclusively on your behalf, under your direction and
177 | control, on terms that prohibit them from making any copies of your
178 | copyrighted material outside their relationship with you.
179 |
180 | Conveying under any other circumstances is permitted solely under the
181 | conditions stated below. Sublicensing is not allowed; section 10 makes
182 | it unnecessary.
183 |
184 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
185 |
186 | No covered work shall be deemed part of an effective technological
187 | measure under any applicable law fulfilling obligations under article
188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
189 | similar laws prohibiting or restricting circumvention of such
190 | measures.
191 |
192 | When you convey a covered work, you waive any legal power to forbid
193 | circumvention of technological measures to the extent such
194 | circumvention is effected by exercising rights under this License with
195 | respect to the covered work, and you disclaim any intention to limit
196 | operation or modification of the work as a means of enforcing, against
197 | the work's users, your or third parties' legal rights to forbid
198 | circumvention of technological measures.
199 |
200 | ### 4. Conveying Verbatim Copies.
201 |
202 | You may convey verbatim copies of the Program's source code as you
203 | receive it, in any medium, provided that you conspicuously and
204 | appropriately publish on each copy an appropriate copyright notice;
205 | keep intact all notices stating that this License and any
206 | non-permissive terms added in accord with section 7 apply to the code;
207 | keep intact all notices of the absence of any warranty; and give all
208 | recipients a copy of this License along with the Program.
209 |
210 | You may charge any price or no price for each copy that you convey,
211 | and you may offer support or warranty protection for a fee.
212 |
213 | ### 5. Conveying Modified Source Versions.
214 |
215 | You may convey a work based on the Program, or the modifications to
216 | produce it from the Program, in the form of source code under the
217 | terms of section 4, provided that you also meet all of these
218 | conditions:
219 |
220 | - a) The work must carry prominent notices stating that you modified
221 | it, and giving a relevant date.
222 | - b) The work must carry prominent notices stating that it is
223 | released under this License and any conditions added under
224 | section 7. This requirement modifies the requirement in section 4
225 | to "keep intact all notices".
226 | - c) You must license the entire work, as a whole, under this
227 | License to anyone who comes into possession of a copy. This
228 | License will therefore apply, along with any applicable section 7
229 | additional terms, to the whole of the work, and all its parts,
230 | regardless of how they are packaged. This License gives no
231 | permission to license the work in any other way, but it does not
232 | invalidate such permission if you have separately received it.
233 | - d) If the work has interactive user interfaces, each must display
234 | Appropriate Legal Notices; however, if the Program has interactive
235 | interfaces that do not display Appropriate Legal Notices, your
236 | work need not make them do so.
237 |
238 | A compilation of a covered work with other separate and independent
239 | works, which are not by their nature extensions of the covered work,
240 | and which are not combined with it such as to form a larger program,
241 | in or on a volume of a storage or distribution medium, is called an
242 | "aggregate" if the compilation and its resulting copyright are not
243 | used to limit the access or legal rights of the compilation's users
244 | beyond what the individual works permit. Inclusion of a covered work
245 | in an aggregate does not cause this License to apply to the other
246 | parts of the aggregate.
247 |
248 | ### 6. Conveying Non-Source Forms.
249 |
250 | You may convey a covered work in object code form under the terms of
251 | sections 4 and 5, provided that you also convey the machine-readable
252 | Corresponding Source under the terms of this License, in one of these
253 | ways:
254 |
255 | - a) Convey the object code in, or embodied in, a physical product
256 | (including a physical distribution medium), accompanied by the
257 | Corresponding Source fixed on a durable physical medium
258 | customarily used for software interchange.
259 | - b) Convey the object code in, or embodied in, a physical product
260 | (including a physical distribution medium), accompanied by a
261 | written offer, valid for at least three years and valid for as
262 | long as you offer spare parts or customer support for that product
263 | model, to give anyone who possesses the object code either (1) a
264 | copy of the Corresponding Source for all the software in the
265 | product that is covered by this License, on a durable physical
266 | medium customarily used for software interchange, for a price no
267 | more than your reasonable cost of physically performing this
268 | conveying of source, or (2) access to copy the Corresponding
269 | Source from a network server at no charge.
270 | - c) Convey individual copies of the object code with a copy of the
271 | written offer to provide the Corresponding Source. This
272 | alternative is allowed only occasionally and noncommercially, and
273 | only if you received the object code with such an offer, in accord
274 | with subsection 6b.
275 | - d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 | - e) Convey the object code using peer-to-peer transmission,
288 | provided you inform other peers where the object code and
289 | Corresponding Source of the work are being offered to the general
290 | public at no charge under subsection 6d.
291 |
292 | A separable portion of the object code, whose source code is excluded
293 | from the Corresponding Source as a System Library, need not be
294 | included in conveying the object code work.
295 |
296 | A "User Product" is either (1) a "consumer product", which means any
297 | tangible personal property which is normally used for personal,
298 | family, or household purposes, or (2) anything designed or sold for
299 | incorporation into a dwelling. In determining whether a product is a
300 | consumer product, doubtful cases shall be resolved in favor of
301 | coverage. For a particular product received by a particular user,
302 | "normally used" refers to a typical or common use of that class of
303 | product, regardless of the status of the particular user or of the way
304 | in which the particular user actually uses, or expects or is expected
305 | to use, the product. A product is a consumer product regardless of
306 | whether the product has substantial commercial, industrial or
307 | non-consumer uses, unless such uses represent the only significant
308 | mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to
312 | install and execute modified versions of a covered work in that User
313 | Product from a modified version of its Corresponding Source. The
314 | information must suffice to ensure that the continued functioning of
315 | the modified object code is in no case prevented or interfered with
316 | solely because modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or
331 | updates for a work that has been modified or installed by the
332 | recipient, or for the User Product in which it has been modified or
333 | installed. Access to a network may be denied when the modification
334 | itself materially and adversely affects the operation of the network
335 | or violates the rules and protocols for communication across the
336 | network.
337 |
338 | Corresponding Source conveyed, and Installation Information provided,
339 | in accord with this section must be in a format that is publicly
340 | documented (and with an implementation available to the public in
341 | source code form), and must require no special password or key for
342 | unpacking, reading or copying.
343 |
344 | ### 7. Additional Terms.
345 |
346 | "Additional permissions" are terms that supplement the terms of this
347 | License by making exceptions from one or more of its conditions.
348 | Additional permissions that are applicable to the entire Program shall
349 | be treated as though they were included in this License, to the extent
350 | that they are valid under applicable law. If additional permissions
351 | apply only to part of the Program, that part may be used separately
352 | under those permissions, but the entire Program remains governed by
353 | this License without regard to the additional permissions.
354 |
355 | When you convey a copy of a covered work, you may at your option
356 | remove any additional permissions from that copy, or from any part of
357 | it. (Additional permissions may be written to require their own
358 | removal in certain cases when you modify the work.) You may place
359 | additional permissions on material, added by you to a covered work,
360 | for which you have or can give appropriate copyright permission.
361 |
362 | Notwithstanding any other provision of this License, for material you
363 | add to a covered work, you may (if authorized by the copyright holders
364 | of that material) supplement the terms of this License with terms:
365 |
366 | - a) Disclaiming warranty or limiting liability differently from the
367 | terms of sections 15 and 16 of this License; or
368 | - b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 | - c) Prohibiting misrepresentation of the origin of that material,
372 | or requiring that modified versions of such material be marked in
373 | reasonable ways as different from the original version; or
374 | - d) Limiting the use for publicity purposes of names of licensors
375 | or authors of the material; or
376 | - e) Declining to grant rights under trademark law for use of some
377 | trade names, trademarks, or service marks; or
378 | - f) Requiring indemnification of licensors and authors of that
379 | material by anyone who conveys the material (or modified versions
380 | of it) with contractual assumptions of liability to the recipient,
381 | for any liability that these contractual assumptions directly
382 | impose on those licensors and authors.
383 |
384 | All other non-permissive additional terms are considered "further
385 | restrictions" within the meaning of section 10. If the Program as you
386 | received it, or any part of it, contains a notice stating that it is
387 | governed by this License along with a term that is a further
388 | restriction, you may remove that term. If a license document contains
389 | a further restriction but permits relicensing or conveying under this
390 | License, you may add to a covered work material governed by the terms
391 | of that license document, provided that the further restriction does
392 | not survive such relicensing or conveying.
393 |
394 | If you add terms to a covered work in accord with this section, you
395 | must place, in the relevant source files, a statement of the
396 | additional terms that apply to those files, or a notice indicating
397 | where to find the applicable terms.
398 |
399 | Additional terms, permissive or non-permissive, may be stated in the
400 | form of a separately written license, or stated as exceptions; the
401 | above requirements apply either way.
402 |
403 | ### 8. Termination.
404 |
405 | You may not propagate or modify a covered work except as expressly
406 | provided under this License. Any attempt otherwise to propagate or
407 | modify it is void, and will automatically terminate your rights under
408 | this License (including any patent licenses granted under the third
409 | paragraph of section 11).
410 |
411 | However, if you cease all violation of this License, then your license
412 | from a particular copyright holder is reinstated (a) provisionally,
413 | unless and until the copyright holder explicitly and finally
414 | terminates your license, and (b) permanently, if the copyright holder
415 | fails to notify you of the violation by some reasonable means prior to
416 | 60 days after the cessation.
417 |
418 | Moreover, your license from a particular copyright holder is
419 | reinstated permanently if the copyright holder notifies you of the
420 | violation by some reasonable means, this is the first time you have
421 | received notice of violation of this License (for any work) from that
422 | copyright holder, and you cure the violation prior to 30 days after
423 | your receipt of the notice.
424 |
425 | Termination of your rights under this section does not terminate the
426 | licenses of parties who have received copies or rights from you under
427 | this License. If your rights have been terminated and not permanently
428 | reinstated, you do not qualify to receive new licenses for the same
429 | material under section 10.
430 |
431 | ### 9. Acceptance Not Required for Having Copies.
432 |
433 | You are not required to accept this License in order to receive or run
434 | a copy of the Program. Ancillary propagation of a covered work
435 | occurring solely as a consequence of using peer-to-peer transmission
436 | to receive a copy likewise does not require acceptance. However,
437 | nothing other than this License grants you permission to propagate or
438 | modify any covered work. These actions infringe copyright if you do
439 | not accept this License. Therefore, by modifying or propagating a
440 | covered work, you indicate your acceptance of this License to do so.
441 |
442 | ### 10. Automatic Licensing of Downstream Recipients.
443 |
444 | Each time you convey a covered work, the recipient automatically
445 | receives a license from the original licensors, to run, modify and
446 | propagate that work, subject to this License. You are not responsible
447 | for enforcing compliance by third parties with this License.
448 |
449 | An "entity transaction" is a transaction transferring control of an
450 | organization, or substantially all assets of one, or subdividing an
451 | organization, or merging organizations. If propagation of a covered
452 | work results from an entity transaction, each party to that
453 | transaction who receives a copy of the work also receives whatever
454 | licenses to the work the party's predecessor in interest had or could
455 | give under the previous paragraph, plus a right to possession of the
456 | Corresponding Source of the work from the predecessor in interest, if
457 | the predecessor has it or can get it with reasonable efforts.
458 |
459 | You may not impose any further restrictions on the exercise of the
460 | rights granted or affirmed under this License. For example, you may
461 | not impose a license fee, royalty, or other charge for exercise of
462 | rights granted under this License, and you may not initiate litigation
463 | (including a cross-claim or counterclaim in a lawsuit) alleging that
464 | any patent claim is infringed by making, using, selling, offering for
465 | sale, or importing the Program or any portion of it.
466 |
467 | ### 11. Patents.
468 |
469 | A "contributor" is a copyright holder who authorizes use under this
470 | License of the Program or a work on which the Program is based. The
471 | work thus licensed is called the contributor's "contributor version".
472 |
473 | A contributor's "essential patent claims" are all patent claims owned
474 | or controlled by the contributor, whether already acquired or
475 | hereafter acquired, that would be infringed by some manner, permitted
476 | by this License, of making, using, or selling its contributor version,
477 | but do not include claims that would be infringed only as a
478 | consequence of further modification of the contributor version. For
479 | purposes of this definition, "control" includes the right to grant
480 | patent sublicenses in a manner consistent with the requirements of
481 | this License.
482 |
483 | Each contributor grants you a non-exclusive, worldwide, royalty-free
484 | patent license under the contributor's essential patent claims, to
485 | make, use, sell, offer for sale, import and otherwise run, modify and
486 | propagate the contents of its contributor version.
487 |
488 | In the following three paragraphs, a "patent license" is any express
489 | agreement or commitment, however denominated, not to enforce a patent
490 | (such as an express permission to practice a patent or covenant not to
491 | sue for patent infringement). To "grant" such a patent license to a
492 | party means to make such an agreement or commitment not to enforce a
493 | patent against the party.
494 |
495 | If you convey a covered work, knowingly relying on a patent license,
496 | and the Corresponding Source of the work is not available for anyone
497 | to copy, free of charge and under the terms of this License, through a
498 | publicly available network server or other readily accessible means,
499 | then you must either (1) cause the Corresponding Source to be so
500 | available, or (2) arrange to deprive yourself of the benefit of the
501 | patent license for this particular work, or (3) arrange, in a manner
502 | consistent with the requirements of this License, to extend the patent
503 | license to downstream recipients. "Knowingly relying" means you have
504 | actual knowledge that, but for the patent license, your conveying the
505 | covered work in a country, or your recipient's use of the covered work
506 | in a country, would infringe one or more identifiable patents in that
507 | country that you have reason to believe are valid.
508 |
509 | If, pursuant to or in connection with a single transaction or
510 | arrangement, you convey, or propagate by procuring conveyance of, a
511 | covered work, and grant a patent license to some of the parties
512 | receiving the covered work authorizing them to use, propagate, modify
513 | or convey a specific copy of the covered work, then the patent license
514 | you grant is automatically extended to all recipients of the covered
515 | work and works based on it.
516 |
517 | A patent license is "discriminatory" if it does not include within the
518 | scope of its coverage, prohibits the exercise of, or is conditioned on
519 | the non-exercise of one or more of the rights that are specifically
520 | granted under this License. You may not convey a covered work if you
521 | are a party to an arrangement with a third party that is in the
522 | business of distributing software, under which you make payment to the
523 | third party based on the extent of your activity of conveying the
524 | work, and under which the third party grants, to any of the parties
525 | who would receive the covered work from you, a discriminatory patent
526 | license (a) in connection with copies of the covered work conveyed by
527 | you (or copies made from those copies), or (b) primarily for and in
528 | connection with specific products or compilations that contain the
529 | covered work, unless you entered into that arrangement, or that patent
530 | license was granted, prior to 28 March 2007.
531 |
532 | Nothing in this License shall be construed as excluding or limiting
533 | any implied license or other defenses to infringement that may
534 | otherwise be available to you under applicable patent law.
535 |
536 | ### 12. No Surrender of Others' Freedom.
537 |
538 | If conditions are imposed on you (whether by court order, agreement or
539 | otherwise) that contradict the conditions of this License, they do not
540 | excuse you from the conditions of this License. If you cannot convey a
541 | covered work so as to satisfy simultaneously your obligations under
542 | this License and any other pertinent obligations, then as a
543 | consequence you may not convey it at all. For example, if you agree to
544 | terms that obligate you to collect a royalty for further conveying
545 | from those to whom you convey the Program, the only way you could
546 | satisfy both those terms and this License would be to refrain entirely
547 | from conveying the Program.
548 |
549 | ### 13. Use with the GNU Affero General Public License.
550 |
551 | Notwithstanding any other provision of this License, you have
552 | permission to link or combine any covered work with a work licensed
553 | under version 3 of the GNU Affero General Public License into a single
554 | combined work, and to convey the resulting work. The terms of this
555 | License will continue to apply to the part which is the covered work,
556 | but the special requirements of the GNU Affero General Public License,
557 | section 13, concerning interaction through a network will apply to the
558 | combination as such.
559 |
560 | ### 14. Revised Versions of this License.
561 |
562 | The Free Software Foundation may publish revised and/or new versions
563 | of the GNU General Public License from time to time. Such new versions
564 | will be similar in spirit to the present version, but may differ in
565 | detail to address new problems or concerns.
566 |
567 | Each version is given a distinguishing version number. If the Program
568 | specifies that a certain numbered version of the GNU General Public
569 | License "or any later version" applies to it, you have the option of
570 | following the terms and conditions either of that numbered version or
571 | of any later version published by the Free Software Foundation. If the
572 | Program does not specify a version number of the GNU General Public
573 | License, you may choose any version ever published by the Free
574 | Software Foundation.
575 |
576 | If the Program specifies that a proxy can decide which future versions
577 | of the GNU General Public License can be used, that proxy's public
578 | statement of acceptance of a version permanently authorizes you to
579 | choose that version for the Program.
580 |
581 | Later license versions may give you additional or different
582 | permissions. However, no additional obligations are imposed on any
583 | author or copyright holder as a result of your choosing to follow a
584 | later version.
585 |
586 | ### 15. Disclaimer of Warranty.
587 |
588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
596 | CORRECTION.
597 |
598 | ### 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
609 |
610 | ### 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | ## How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these
626 | terms.
627 |
628 | To do so, attach the following notices to the program. It is safest to
629 | attach them to the start of each source file to most effectively state
630 | the exclusion of warranty; and each file should have at least the
631 | "copyright" line and a pointer to where the full notice is found.
632 |
633 | Rattlescript is a dynamically typed, interpreted programming language written in Rust.
634 | Copyright (C) 2023 Haven Selph
635 |
636 | This program is free software: you can redistribute it and/or modify
637 | it under the terms of the GNU General Public License as published by
638 | the Free Software Foundation, either version 3 of the License, or
639 | (at your option) any later version.
640 |
641 | This program is distributed in the hope that it will be useful,
642 | but WITHOUT ANY WARRANTY; without even the implied warranty of
643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
644 | GNU General Public License for more details.
645 |
646 | You should have received a copy of the GNU General Public License
647 | along with this program. If not, see .
648 |
649 | Also add information on how to contact you by electronic and paper
650 | mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Rattlescript Copyright (C) 2023 Haven Selph
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands \`show w' and \`show c' should show the
661 | appropriate parts of the General Public License. Of course, your
662 | program's commands might be different; for a GUI interface, you would
663 | use an "about box".
664 |
665 | You should also get your employer (if you work as a programmer) or
666 | school, if any, to sign a "copyright disclaimer" for the program, if
667 | necessary. For more information on this, and how to apply and follow
668 | the GNU GPL, see .
669 |
670 | The GNU General Public License does not permit incorporating your
671 | program into proprietary programs. If your program is a subroutine
672 | library, you may consider it more useful to permit linking proprietary
673 | applications with the library. If this is what you want to do, use the
674 | GNU Lesser General Public License instead of this License. But first,
675 | please read .
676 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # RattleScript is...
4 | An interpreted, dynamic, and expressive programming language written in Rust! It started as a small development project with a friend of mine, but has quickly turned into a passion! I hope to continue working on this project and one day host a whole standard library of functions and modules for people to use. Every week the feature list grows, and I'm excited to see where this project ends up!
5 |
6 | RattleScript is licensed under the [GNU General Public License v3.0]().
7 |
8 | # Contributing
9 | Want to contribute? That's awesome! Go ahead and fork the repository and make a pull request! I'll be sure to review it as soon as I can. However, please make sure to make sure your contribution...
10 | - is NOT a formatting change. I will not accept changes that are unsubstantial.
11 | - either fixes, improves, or adds a feature to the language.
12 | - does not break any existing features. GitHub Actions will automatically run tests on your code, but please make sure to test your code yourself before submitting a pull request.
13 | - does not add any new dependencies. I understand that you may want to add a feature, but don't want to spend time reinventing the wheel. However, I want to keep this project independent of any external crates.
14 | - is not changing more than 1 feature at once. I want to keep pull requests on the small side and easy to review.
15 |
16 | If your change is large or requires a rewrite of many parts, please make sure to open an issue first, so we can discuss it. I would hate to waste your time for me to not merge it in because of too many conflicts. Furthermore, please be sure to either document your code, or describe what it does in the pull request. If your change is large enough to permit it, please consider adding tests for common issues you had to prevent regression. I hate fixing things I've already fixed before, or that someone else has fixed before. The testing framework is very simple, and you can find examples of it in the `./tests` directory. The script that handles testing is `./test.py`.
17 |
18 | # Building
19 | Since there are no dependencies, you need nothing more than the Rust compiler itself. Just run the following command:
20 | `cargo build --release`
21 |
22 | # Using
23 | RattleScript has two main ways of being run. You can either open a REPL or run a single file. To open a REPL, simply pass no arguments to the executable. To run a file, pass the path to the file as an argument. For example, to run the file `./test.rat` you would pass the argument `./test.rat` to the interpreter. For more information, run the interpreter with the `--help` or `-h` flag.
24 |
25 | # Planned Language Features
26 | - Import system
27 | - Sets
28 | - Match statements
29 | - Switch statements (like match, but don't stop on first match)
30 | - Loop returns
31 | - Enums
32 | - Structs (maybe)
33 | - Better error messages (hints, possible solutions, pointing to the exact location of the problem instead of the statement)
34 |
35 | # Planned Backend Features
36 | - More file related functions
37 | - Better system for builtins
38 |
39 | # Features
40 | ### Variables and expressions
41 | ```javascript
42 | let x = 10
43 | let y = 2
44 | let z = x + y // Will evaluate to 12
45 | ```
46 | ### Functions and Lambdas
47 | ```javascript
48 | def add(a, b) {
49 | return a + b
50 | }
51 |
52 | let multiply = |a, b| => a * b
53 | ```
54 | ### Python-like Variadics and Defaults
55 | ```javascript
56 | def add(a, *b, c: 10, **d) => (a, b, c, d)
57 |
58 | add(1,2,3,c:10,k:12) // Will evaluate to (1, [2,3], 10, {k:12})
59 | ```
60 | ### Comprehensions
61 | ```javascript
62 | let a = [1, 2, 3, 4, 5]
63 | [print(x) for x in a] // Prints each element in the list
64 | [print(x) for x in a if x % 2 == 0] // Prints each even element in the list
65 | ```
66 | ### Closure Scoping and Decorators
67 | ```js
68 | def deco(msg) {
69 | def inner(func) {
70 | def wrapper(*args, **kwargs) {
71 | print(msg, "input: ", args, kwargs)
72 | return func(*args, **kwargs)
73 | }
74 | }
75 | }
76 |
77 | @deco("addition")
78 | def add(a, b) { // We can decorate functions with python's @ syntax
79 | return a + b
80 | }
81 |
82 | def sub(a, b) {
83 | return a - b
84 | }
85 |
86 | sub = deco("subtraction")(sub) // Or we can do it the old fashioned way
87 |
88 |
89 | add(3, 4) // Will print "addition input 3 4"
90 | sub(5, 6) // Will print "subtraction input 5 6"
91 | ```
92 | ### Classes and Inheritance
93 | ```javascript
94 | class ClassA {
95 | def new(self, name) {
96 | self.name = name
97 | }
98 |
99 | def print_name(self) {
100 | print(self.name)
101 | }
102 | }
103 |
104 | class ClassB(ClassA) {} // ClassB inherits from ClassA
105 | // This means that ClassB will have all of ClassA's methods and (static) variables
106 | // You can also inherit from more than one class at a time.
107 |
108 | let a = ClassB
109 | class ClassC(a) // This is valid too!
110 | ```
111 | ### Namespaces
112 | ```javascript
113 | namespace Math {
114 | def add(a, b) => a+b
115 |
116 | def sub(a, b) => a-b
117 |
118 | let pi = 3.141592653589793
119 | }
120 |
121 | Math.add(1, 2)
122 | Math.pi
123 | ```
124 |
125 | ### Datatypes
126 | ```javascript
127 | let a = 10 // Integers
128 | let b = 10.0 // Floats
129 | let c = 0b101 // Binary
130 | let d = 0o67 // Octal
131 | let e = 0x22B // Hexadecimal
132 | let f = "Hello World!" // Strings
133 | let g = true // Booleans
134 | let h = [1, 2, 3] // Lists
135 | let i = {a: 1, b: 2, c: 3} // Dictionaries
136 | let j = (1, 2, 3) // Tuples
137 | let k = nothing // Nothing (equivalent to null or None)
138 |
139 | // Since rattlescript is dynamic, everything is an object! You can
140 | // call methods on most datatypes!
141 |
142 | [1,2,3,4].iter().map(print) // This will print each element in the list
143 | "123".int() // This will convert the string to an integer
144 | 123.str() // This will convert the integer to a string
145 |
146 |
147 | def add(a, b) {
148 | return a + b
149 | }
150 |
151 | let add_var = add // Functions are objects too!
152 |
153 | // Even ranges are objects!
154 | let range = 0..10
155 | for x in range {
156 | print(x)
157 | }
158 | ```
159 | ### Control Flow
160 | ```javascript
161 | let boo = true
162 | let two = false
163 |
164 | if boo {
165 | // Do something
166 | } else if two {
167 | // Do something
168 | }
169 |
170 | while boo {
171 | // Do something
172 | if two {
173 | break
174 | } else {
175 | continue
176 | }
177 | }
178 | ```
179 |
--------------------------------------------------------------------------------
/examples/caluc/common.rat:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Check the LICENSE file for more information.
4 | */
5 |
6 | class Token {
7 | def new(self, type, data) {
8 | self.type = type
9 | self.data = data
10 | }
11 |
12 | def repr(self) => `Token({self.type}, {self.data})`
13 | }
14 |
15 | namespace TokenType {
16 | // This is a hack to kind of emulate an enum
17 | let Identifier = 0
18 | let Number = 1
19 | let String = 2
20 |
21 | let Plus = 3
22 | let Minus = 4
23 | let Star = 5
24 | let Slash = 6
25 | let Caret = 7
26 |
27 | let LParen = 8
28 | let RParen = 9
29 | let Equals = 10
30 |
31 | let EOF = 11
32 | }
33 |
34 | let chars = {
35 | "+":TokenType.Plus,
36 | "-":TokenType.Minus,
37 | "*":TokenType.Star,
38 | "/":TokenType.Slash,
39 | "^":TokenType.Caret,
40 | "=":TokenType.Equals,
41 | "(":TokenType.LParen,
42 | ")":TokenType.RParen
43 | }
44 |
--------------------------------------------------------------------------------
/examples/caluc/interpreter.rat:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Check the LICENSE file for more information.
4 | */
5 |
6 | class VariableAssignment {
7 | def new(self, name, expr) {
8 | self.name = name
9 | self.expr = expr
10 | }
11 |
12 | def run(self, ctx) {
13 | let val = self.expr.run(ctx)
14 | ctx[self.name] = val
15 | return val
16 | }
17 | }
18 |
19 | class Variable {
20 | def new(self, name) {
21 | self.name = name
22 | }
23 |
24 | def run(self, ctx) {
25 | return ctx[self.name]
26 | }
27 | }
28 |
29 | class Number {
30 | def new(self, value) {
31 | self.value = value
32 | }
33 |
34 | def run(self, ctx) {
35 | return self.value
36 | }
37 | }
38 |
39 | class BinaryOp {
40 | def new(self, left, right) {
41 | self.left = left
42 | self.right = right
43 | }
44 |
45 | def run(self, ctx) {
46 | print(`run not implemented on {self}`)
47 | exit(1)
48 | }
49 | }
50 |
51 | class Add(BinaryOp) {
52 | def run(self, ctx) {
53 | return self.left.run(ctx) + self.right.run(ctx)
54 | }
55 | }
56 |
57 | class Subtract(BinaryOp) {
58 | def run(self, ctx) {
59 | return self.left.run(ctx) - self.right.run(ctx)
60 | }
61 | }
62 |
63 | class Multiply(BinaryOp) {
64 | def run(self, ctx) {
65 | return self.left.run(ctx) * self.right.run(ctx)
66 | }
67 | }
68 |
69 | class Divide(BinaryOp) {
70 | def run(self, ctx) {
71 | return self.left.run(ctx) / self.right.run(ctx)
72 | }
73 | }
74 |
75 | class Power(BinaryOp) {
76 | def run(self, ctx) {
77 | return self.left.run(ctx) ** self.right.run(ctx)
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/examples/caluc/lexer.rat:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Check the LICENSE file for more information.
4 |
5 | This file contains the Lexer. The Lexer is responsible for
6 | converting a string into a list of tokens. The tokens are
7 | then passed to the Parser, which converts the tokens into
8 | an AST.
9 |
10 | This Lexer is extremely simple. It only supports words,
11 | numbers, and operators.
12 |
13 | The Lexer will return a LexerResponse object. This object
14 | contains a list of tokens and a message. The message is
15 | used to indicate whether or not the lexing was successful.
16 | */
17 |
18 | import std.string
19 | from common import (chars, Token, TokenType)
20 |
21 |
22 | class LexerResponse {
23 | // LexerResponse is a workaround since Rattlescript currently doesn't have
24 | // error handling.
25 | def new(self, tokens, msg="success") {
26 | self.msg = msg
27 | self.tokens = tokens
28 | }
29 | }
30 |
31 | class Lexer {
32 | def new(self, source) {
33 | self.source = source
34 | self.index = 0
35 | }
36 |
37 | def next(self) {
38 | self.index += 1
39 | return self.cur()
40 | }
41 |
42 | def cur(self) {
43 | if (self.index >= self.source.len()) {
44 | return nothing
45 | }
46 | return self.source[self.index]
47 | }
48 |
49 |
50 | def lex(self) {
51 | let tokens = []
52 | while self.cur() != nothing {
53 | if string.is_space(self.cur()) {
54 | self.index += 1
55 | continue
56 | } else if string.is_alpha(self.cur()) {
57 | tokens.push(self.lex_word())
58 | } else if string.is_digit(self.cur()) {
59 | tokens.push(self.lex_number())
60 | } else if self.cur() in chars {
61 | tokens.push(Token(chars[self.cur()], self.cur()))
62 | self.next()
63 | } else {
64 | // FixMe: Defaults cannot be used as positional arguments
65 | // Due to a bug, I have to prefix the message parameter with msg:
66 | // This behavior is likely due to my argument parser not keeping track
67 | // of the current parameter that an argument should be pushed to.
68 | return LexerResponse(nothing, msg:`Unexpected character: {self.cur()}`)
69 | }
70 | }
71 |
72 | // Insert EOF token
73 | tokens.push(Token(TokenType.EOF, nothing))
74 | return LexerResponse(tokens)
75 | }
76 |
77 | def lex_word(self) {
78 | let word = ""
79 | while self.cur() != nothing and (string.is_alnum(self.cur()) or self.cur() == "_") {
80 | word += self.cur()
81 | self.next()
82 | }
83 | return Token(TokenType.Identifier, word)
84 | }
85 |
86 | def lex_number(self) {
87 | let number = self.lex_int()
88 | if self.cur() == "." {
89 | number += "."
90 | self.next()
91 | number += self.lex_int()
92 | }
93 | return Token(TokenType.Number, number.float())
94 | }
95 |
96 | def lex_int(self) {
97 | let number = ""
98 | while self.cur() != nothing and string.is_digit(self.cur()) {
99 | number += self.cur()
100 | self.next()
101 | }
102 | return number
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/examples/caluc/main.rat:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Check the LICENSE file for more information.
4 |
5 | This file is the REPL for Caluc. It is a simple calculator that
6 | can be used to evaluate expressions. It is not meant to be
7 | a programming language, but rather an interesting example
8 | of what Rattlescript can do.
9 |
10 | Usage:
11 | Caluc uses a REPL (Read-Eval-Print Loop) interface. To use it, simply
12 | run this file using the Rattlescript interpreter. You can then type
13 | in expressions and have them evaluated. To exit, type "exit" and press
14 | enter.
15 |
16 | Features:
17 | Arithmetic operations: +, -, *, /, %
18 | Variables: x = 5
19 | */
20 | // Imports
21 | from lexer import Lexer
22 | from parser import Parser
23 |
24 | // REPL
25 | let header = "Caluc REPL | Type 'exit' to exit."
26 | print(header)
27 |
28 | def parse_until_complete() {
29 | let inp = ""
30 | let prompt = "Caluc >>> "
31 | let ast = nothing
32 | while ast == nothing {
33 | let temp = input(prompt)
34 | prompt = "Caluc ... "
35 | inp += temp + "\n"
36 | if inp == "exit" {
37 | exit()
38 | }
39 |
40 | // Lex the input
41 | let lexer = Lexer(inp)
42 | let lex_response = lexer.lex()
43 | if lex_response.tokens == nothing {
44 | print(`Lexer error: {lex_response.msg}`)
45 | return nothing
46 | }
47 | let tokens = lex_response.tokens
48 |
49 | // Parse the tokens, if error is recoverable, continue
50 | // if parser fails, and temp == "", print error and return
51 | let parser = Parser(tokens)
52 | let ast = parser.parse() // Will return a ParserResponse object
53 | if ast.ast == nothing {
54 | if ast.recoverable == false or temp == "" {
55 | print(`Parser error: {ast.msg}`)
56 | return nothing
57 | }
58 | continue
59 | }
60 | return ast.ast
61 | }
62 | }
63 | let context = {"last":0}
64 | while true {
65 | // Lex and parse the input
66 | let ast = parse_until_complete()
67 | if ast == nothing {
68 | continue
69 | }
70 |
71 | // Evaluate the AST
72 | let val = ast.run(context)
73 | context["last"] = val
74 | print(val)
75 | }
76 |
--------------------------------------------------------------------------------
/examples/caluc/parser.rat:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Check the LICENSE file for more information.
4 |
5 | This file contains the parser for the calculator. It takes
6 | a list of tokens and turns it into an AST.
7 |
8 | The parser is a recursive descent parser, and returns
9 | a ParserResponse object. This object contains the AST
10 | or an error message if there was an error.
11 | */
12 | import interpreter
13 | from common import TokenType
14 |
15 |
16 | class ParserResponse {
17 | def new(self, ast, msg=nothing, recoverable=false) {
18 | self.ast = ast
19 | self.msg = msg
20 | self.recoverable = recoverable
21 | }
22 | }
23 |
24 | class Parser {
25 | def new(self, tokens) {
26 | self.tokens = tokens
27 | self.pos = 0
28 | self.cur = self.tokens[0]
29 | self.error = nothing
30 | self.error_recoverable = false
31 | }
32 |
33 | def next(self) {
34 | if self.cur.type != TokenType.EOF {
35 | self.pos += 1
36 | }
37 | self.cur = self.tokens[self.pos]
38 | }
39 |
40 | def parse(self) {
41 | let ast = self.parse_expression()
42 | if ast == nothing {
43 | return ParserResponse(nothing, msg:self.error, recoverable:self.error_recoverable)
44 | }
45 | return ParserResponse(ast)
46 | }
47 |
48 | def parse_expression(self) {
49 | return self.parse_assignment()
50 | }
51 |
52 | def parse_assignment(self) {
53 | let left = self.parse_addition()
54 | if left == nothing return left
55 | if self.cur != nothing and self.cur.type == TokenType.Equals {
56 | self.next()
57 | let right = self.parse_assignment()
58 | if right == nothing return right
59 | if left != interpreter.Variable {
60 | self.error = "Left side of assignment must be a variable"
61 | return nothing
62 | }
63 | if left.name == "last" {
64 | self.error = "Cannot assign to last, it is reserved for the last result"
65 | return nothing
66 | }
67 | left = interpreter.VariableAssignment(left.name, right)
68 | }
69 | return left
70 | }
71 |
72 | def parse_addition(self) {
73 | let left = self.parse_multiplication()
74 | if left == nothing return left
75 | while self.cur != nothing and self.cur.type in [TokenType.Plus, TokenType.Minus] {
76 | let op = self.cur.type
77 | self.next()
78 | let right = self.parse_multiplication()
79 | if right == nothing return right
80 | if op == TokenType.Plus {
81 | left = interpreter.Add(left, right)
82 | } else {
83 | left = interpreter.Subtract(left, right)
84 | }
85 | }
86 | return left
87 | }
88 |
89 | def parse_multiplication(self) {
90 | let left = self.parse_power()
91 | if left == nothing return left
92 | while self.cur != nothing and self.cur.type in [TokenType.Star, TokenType.Slash] {
93 | let op = self.cur.type
94 | self.next()
95 | let right = self.parse_power()
96 | if right == nothing return right
97 | if op == TokenType.Star {
98 | left = interpreter.Multiply(left, right)
99 | } else {
100 | left = interpreter.Divide(left, right)
101 | }
102 | }
103 | return left
104 | }
105 |
106 | def parse_power(self) {
107 | let left = self.parse_atom()
108 | if left == nothing return left
109 | while self.cur != nothing and self.cur.type == TokenType.Caret {
110 | self.next()
111 | let right = self.parse_power()
112 | if right == nothing return right
113 | left = interpreter.Power(left, right)
114 | }
115 | return left
116 | }
117 |
118 | def parse_atom(self) {
119 | if self.cur.type == TokenType.Number {
120 | let num = interpreter.Number(self.cur.data)
121 | self.next()
122 | return num
123 | } else if self.cur.type == TokenType.Identifier {
124 | let name = interpreter.Variable(self.cur.data)
125 | self.next()
126 | return name
127 | } else if self.cur.type == TokenType.LParen {
128 | self.next()
129 | let expr = self.parse_expression()
130 | if expr == nothing return expr
131 | if self.cur == nothing or self.cur.type != TokenType.RParen {
132 | self.error = "Expected closing parenthesis"
133 | self.error_recoverable = true
134 | return nothing
135 | }
136 | self.next()
137 | return expr
138 | } else if self.cur.type == TokenType.EOF {
139 | self.error = "Unexpected end of input"
140 | self.error_recoverable = true
141 | return nothing
142 | }
143 | self.error = `Unexpected token {self.cur.type}`
144 | return nothing
145 | }
146 | }
147 |
--------------------------------------------------------------------------------
/examples/decorator.rat:
--------------------------------------------------------------------------------
1 |
2 |
3 | def message(before, after=nothing) {
4 | def inner(fn) {
5 | def wrapper(*args, **kwargs) {
6 | print(before)
7 | fn(*args, **kwargs)
8 | if (after != nothing) print(after)
9 | }
10 | return wrapper
11 | }
12 | return inner
13 | }
14 |
15 |
16 | @message("adding", after:"added")
17 | def adder(a, b) {
18 | return a + b
19 | }
20 |
21 | adder(1, 2)
22 |
--------------------------------------------------------------------------------
/examples/linked_list.rat:
--------------------------------------------------------------------------------
1 |
2 |
3 | class LinkedList {
4 | static class Node {
5 | def new(self, val, next=nothing) {
6 | self.next = next
7 | self.val = val
8 | }
9 | }
10 |
11 | def new(self) {
12 | self.head = nothing
13 | self.len = 0
14 | }
15 |
16 | def get(self, idx) {
17 | if idx > self.len or 0 > idx {
18 | print(`Index '{idx}' out of bounds`)
19 | exit(1)
20 | }
21 | let cur = self.head
22 | let i = 0
23 | while i != idx {
24 | cur = cur.next
25 | i++
26 | }
27 | return cur
28 | }
29 |
30 | def push(self, val) {
31 | if self.head == nothing {
32 | self.head = Node(val)
33 | } else {
34 | let cur = self.head
35 | self.head = self.Node(val, next:cur)
36 | }
37 | self.len++
38 | }
39 |
40 | def push_many(self, *vals) {
41 | for val in vals {
42 | self.push(val)
43 | }
44 | }
45 |
46 | def push_at(self, idx, val) {
47 | if idx == 0 {
48 | self.push(val)
49 | return nothing
50 | }
51 | if idx > self.len or 0 > idx {
52 | print(`Index '{idx}' out of bounds`)
53 | exit(1)
54 | }
55 | let node = self.get(idx-1)
56 | let cur = node.next
57 | node.next = self.Node(val, next:cur)
58 | self.len++
59 | }
60 |
61 | def pop(self) {
62 | if self.len == 0 {
63 | print("Cannot pop on an empty linked list.")
64 | exit(1)
65 | }
66 | self.head = self.head.next
67 | self.len--
68 | return self.head
69 | }
70 |
71 | def pop_at(self, idx) {
72 | if idx == 0 {
73 | return self.pop()
74 | }
75 | if idx > self.len or 0 > idx {
76 | print(`Index '{idx}' out of bounds`)
77 | exit(1)
78 | }
79 | let node = self.get(idx-1)
80 | let popped = node.next
81 | node.next = popped.next
82 | self.len--
83 | return popped
84 | }
85 |
86 | def print(self) {
87 | let out = "Linked list: "
88 | let cur = self.head
89 | while cur != nothing {
90 | out += repr(cur.val)
91 | if cur.next != nothing {
92 | out += " -> "
93 | }
94 | cur = cur.next
95 | }
96 | print(out)
97 | }
98 | }
99 |
100 | let ll = LinkedList()
101 | print("Pushing 1,2,3,4,5")
102 | ll.push_many(1,2,3,4,5)
103 | ll.print()
104 | print("Popping")
105 | ll.pop()
106 | ll.print()
107 | print("Pushing 23 at index 2")
108 | ll.push_at(2,23)
109 | ll.print()
110 | print("Popping at index 4")
111 | ll.pop_at(4)
112 | ll.print()
113 |
--------------------------------------------------------------------------------
/examples/rock_paper_scissors.rat:
--------------------------------------------------------------------------------
1 | let random_state = new_random_state()
2 | let states = {1: "You tied!", 2: "You lost!", 3: "You won!"}
3 | while true {
4 | let inp = input("[R]ock | [P]aper | [S]cissors | [Q]uit >>> ")
5 | let pc_choice = random_state.rand_i(0,3)
6 | if inp.lower() in ["q", "quit"] {
7 | break
8 | } else if not (inp.lower() in ["r", "p", "s", "rock", "paper", "scissors"]) {
9 | print("Invalid input!")
10 | } else {
11 | print(states[pc_choice])
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/ast.rs:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Copyright (C) 2023 Mustafa Quraish
4 | Check the LICENSE file for more information.
5 | */
6 |
7 | use crate::common::Span;
8 | use std::collections::HashMap;
9 | use std::rc::Rc;
10 |
11 | #[derive(Debug, Clone, Copy, Eq, PartialEq)]
12 | pub enum ArgumentType {
13 | Positional,
14 | Variadic,
15 | Keyword,
16 | VariadicKeyword,
17 | }
18 |
19 | impl std::fmt::Display for ArgumentType {
20 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
21 | match self {
22 | ArgumentType::Positional => write!(f, "positional"),
23 | ArgumentType::Variadic => write!(f, "positional variadic"),
24 | ArgumentType::Keyword => write!(f, "keyword"),
25 | ArgumentType::VariadicKeyword => write!(f, "keyword variadic"),
26 | }
27 | }
28 | }
29 |
30 | pub type FunctionArgs = Vec<(String, Option>, ArgumentType)>;
31 | pub type CallArgs = Vec<(Option, Rc)>;
32 | pub type ImportObject = (Vec<(String, Option)>, Span);
33 |
34 | #[derive(Debug)]
35 | pub enum AST {
36 | And(Span, Rc, Rc),
37 | Assert(Span, Rc, Option),
38 | Assignment(Span, Rc, Rc),
39 | Block(Span, Vec>),
40 | Class {
41 | span: Span,
42 | name: String,
43 | parents: Option>,
44 | fields: HashMap, bool)>,
45 | },
46 | BooleanLiteral(Span, bool),
47 | Call(Span, Rc, CallArgs),
48 | Divide(Span, Rc, Rc),
49 | Modulo(Span, Rc, Rc),
50 | FloatLiteral(Span, f64),
51 | Function {
52 | span: Span,
53 | name: Option,
54 | args: FunctionArgs,
55 | required: usize,
56 | is_static: bool,
57 | in_class: bool,
58 | body: Rc,
59 | },
60 | Namespace {
61 | span: Span,
62 | name: String,
63 | body: Rc,
64 | },
65 | If(Span, Rc, Rc, Option>),
66 | In(Span, Rc, Rc),
67 | Index(Span, Rc, Rc),
68 | IntegerLiteral(Span, i64),
69 | Minus(Span, Rc, Rc),
70 | Multiply(Span, Rc, Rc),
71 | Power(Span, Rc, Rc),
72 | Not(Span, Rc),
73 | Negate(Span, Rc),
74 | Nothing(Span),
75 | Or(Span, Rc, Rc),
76 | Plus(Span, Rc, Rc),
77 | Return(Span, Rc),
78 | Slice {
79 | span: Span,
80 | lhs: Rc,
81 | start: Option>,
82 | end: Option>,
83 | step: Option>,
84 | },
85 | StringLiteral(Span, String),
86 | VarDeclaration(Span, String, Rc),
87 | Variable(Span, String),
88 | Equals(Span, Rc, Rc),
89 | NotEquals(Span, Rc, Rc),
90 | LessThan(Span, Rc, Rc),
91 | GreaterThan(Span, Rc, Rc),
92 | LessEquals(Span, Rc, Rc),
93 | GreaterEquals(Span, Rc, Rc),
94 | While(Span, Rc, Rc),
95 | Continue(Span),
96 | Break(Span),
97 | ForEach(Span, String, Rc, Rc),
98 | For {
99 | span: Span,
100 | init: Option>,
101 | cond: Option>,
102 | step: Option>,
103 | body: Rc,
104 | },
105 | Import {
106 | span: Span,
107 | path: String,
108 | alias: Option,
109 | },
110 | FromImport {
111 | span: Span,
112 | path: String,
113 | names: Vec<(String, Option)>,
114 | },
115 | FieldAccess(Span, Rc, String),
116 | Comprehension(Span, String, Rc, Rc, Option>),
117 | FormatStringLiteral(Span, Vec, Vec>),
118 | Range(Span, Rc, Rc),
119 | StarExpression(Span, Rc),
120 | StarStarExpression(Span, Rc),
121 |
122 | PostIncrement(Span, Rc, i64),
123 | PreIncrement(Span, Rc, i64),
124 | ArrayLiteral(Span, Vec>),
125 | TupleLiteral(Span, Vec>),
126 | DictionaryLiteral(Span, Vec<(Rc, Rc)>),
127 | }
128 |
129 | impl AST {
130 | pub fn span(&self) -> &Span {
131 | match self {
132 | AST::And(span, ..) => span,
133 | AST::Assert(span, ..) => span,
134 | AST::Assignment(span, ..) => span,
135 | AST::Block(span, ..) => span,
136 | AST::BooleanLiteral(span, ..) => span,
137 | AST::Call(span, ..) => span,
138 | AST::Class { span, .. } => span,
139 | AST::Divide(span, ..) => span,
140 | AST::FloatLiteral(span, ..) => span,
141 | AST::Function { span, .. } => span,
142 | AST::If(span, ..) => span,
143 | AST::Index(span, ..) => span,
144 | AST::IntegerLiteral(span, ..) => span,
145 | AST::Minus(span, ..) => span,
146 | AST::In(span, ..) => span,
147 | AST::Multiply(span, ..) => span,
148 | AST::Modulo(span, ..) => span,
149 | AST::Power(span, ..) => span,
150 | AST::Not(span, ..) => span,
151 | AST::Nothing(span, ..) => span,
152 | AST::Negate(span, ..) => span,
153 | AST::Or(span, ..) => span,
154 | AST::Plus(span, ..) => span,
155 | AST::Return(span, ..) => span,
156 | AST::Slice { span, .. } => span,
157 | AST::StringLiteral(span, ..) => span,
158 | AST::VarDeclaration(span, ..) => span,
159 | AST::Variable(span, ..) => span,
160 | AST::Equals(span, ..) => span,
161 | AST::NotEquals(span, ..) => span,
162 | AST::LessThan(span, ..) => span,
163 | AST::GreaterThan(span, ..) => span,
164 | AST::LessEquals(span, ..) => span,
165 | AST::GreaterEquals(span, ..) => span,
166 | AST::While(span, ..) => span,
167 | AST::Continue(span, ..) => span,
168 | AST::Break(span, ..) => span,
169 | AST::ForEach(span, ..) => span,
170 | AST::For { span, .. } => span,
171 | AST::FieldAccess(span, ..) => span,
172 | AST::Comprehension(span, ..) => span,
173 | AST::FormatStringLiteral(span, ..) => span,
174 | AST::Range(span, ..) => span,
175 | AST::PostIncrement(span, ..) => span,
176 | AST::PreIncrement(span, ..) => span,
177 | AST::ArrayLiteral(span, ..) => span,
178 | AST::TupleLiteral(span, ..) => span,
179 | AST::DictionaryLiteral(span, ..) => span,
180 | AST::Import { span, .. } => span,
181 | AST::FromImport { span, .. } => span,
182 | AST::Namespace { span, .. } => span,
183 | AST::StarExpression(span, ..) => span,
184 | AST::StarStarExpression(span, ..) => span,
185 | }
186 | }
187 | }
188 |
189 | impl std::fmt::Display for AST {
190 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
191 | match self {
192 | AST::And(_, lhs, rhs) => write!(f, "({} and {})", lhs, rhs),
193 | AST::Assert(_, expr, _) => write!(f, "assert {}", expr),
194 | AST::Assignment(_, lhs, rhs) => write!(f, "{} = {}", lhs, rhs),
195 | AST::Block(_, exprs) => write!(f, "", exprs.len()),
196 | AST::BooleanLiteral(_, val) => write!(f, "{}", val),
197 | AST::Call(_, func, args) => {
198 | write!(f, "{}(", func)?;
199 | for (i, (_, arg)) in args.iter().enumerate() {
200 | if i > 0 {
201 | write!(f, ", ")?;
202 | }
203 | write!(f, "{}", arg)?;
204 | }
205 | write!(f, ")")
206 | }
207 | AST::Class { name, .. } => write!(f, "", name,),
208 | AST::Divide(_, lhs, rhs) => write!(f, "({} / {})", lhs, rhs),
209 | AST::Modulo(_, lhs, rhs) => write!(f, "({} % {})", lhs, rhs),
210 | AST::FloatLiteral(_, val) => write!(f, "{}", val),
211 | AST::Function { name, .. } => write!(
212 | f,
213 | "def {} => ...",
214 | name.clone().unwrap_or_else(|| "".to_string())
215 | ),
216 | AST::If(_, cond, ..) => write!(f, "if {}", cond),
217 | AST::Index(_, lhs, rhs) => write!(f, "{}[{}]", lhs, rhs),
218 | AST::IntegerLiteral(_, val) => write!(f, "{}", val),
219 | AST::Minus(_, lhs, rhs) => write!(f, "({} - {})", lhs, rhs),
220 | AST::Multiply(_, lhs, rhs) => write!(f, "({} * {})", lhs, rhs),
221 | AST::Power(_, lhs, rhs) => write!(f, "({} ** {})", lhs, rhs),
222 | AST::In(_, lhs, rhs) => write!(f, "({} in {})", lhs, rhs),
223 | AST::Not(_, expr) => write!(f, "not {}", expr),
224 | AST::Nothing(_) => write!(f, "nothing"),
225 | AST::Negate(_, expr) => write!(f, "-{}", expr),
226 | AST::Or(_, lhs, rhs) => write!(f, "({} or {})", lhs, rhs),
227 | AST::Plus(_, lhs, rhs) => write!(f, "({} + {})", lhs, rhs),
228 | AST::Return(_, expr) => write!(f, "return {}", expr),
229 | AST::Slice {
230 | lhs,
231 | start,
232 | end,
233 | step,
234 | ..
235 | } => {
236 | write!(f, "{}[", lhs)?;
237 | if let Some(start) = start {
238 | write!(f, "{}", start)?;
239 | }
240 | write!(f, ":")?;
241 | if let Some(end) = end {
242 | write!(f, "{}", end)?;
243 | }
244 | if let Some(step) = step {
245 | write!(f, ":{}", step)?;
246 | }
247 | write!(f, "]")
248 | }
249 | AST::StringLiteral(_, val) => write!(f, "\"{}\"", val),
250 | AST::VarDeclaration(_, name, expr) => write!(f, "let {} = {}", name, expr),
251 | AST::Variable(_, name) => write!(f, "{}", name),
252 | AST::Equals(_, lhs, rhs) => write!(f, "({} == {})", lhs, rhs),
253 | AST::NotEquals(_, lhs, rhs) => write!(f, "({} != {})", lhs, rhs),
254 | AST::LessThan(_, lhs, rhs) => write!(f, "({} < {})", lhs, rhs),
255 | AST::GreaterThan(_, lhs, rhs) => write!(f, "({} > {})", lhs, rhs),
256 | AST::LessEquals(_, lhs, rhs) => write!(f, "({} <= {})", lhs, rhs),
257 | AST::GreaterEquals(_, lhs, rhs) => write!(f, "({} >= {})", lhs, rhs),
258 | AST::While(_, cond, ..) => write!(f, "while {}", cond),
259 | AST::Continue(_) => write!(f, "continue"),
260 | AST::Break(_) => write!(f, "break"),
261 | AST::ForEach(_, name, iter, ..) => write!(f, "for {} in {}", name, iter),
262 | AST::For {
263 | init, cond, step, ..
264 | } => {
265 | write!(f, "for (")?;
266 | if let Some(init) = init {
267 | write!(f, "{}", init)?;
268 | }
269 | write!(f, "; ")?;
270 | if let Some(cond) = cond {
271 | write!(f, "{}", cond)?;
272 | }
273 | write!(f, "; ")?;
274 | if let Some(step) = step {
275 | write!(f, "{}", step)?;
276 | }
277 | write!(f, ")")
278 | }
279 | AST::FieldAccess(_, lhs, rhs) => write!(f, "{}.{}", lhs, rhs),
280 | AST::Comprehension(_, var, iter, expr, cond) => match cond {
281 | Some(cond) => write!(f, "[{} for {} in {} if {}]", expr, var, iter, cond),
282 | None => write!(f, "[{} for {} in {}]", expr, var, iter),
283 | },
284 | AST::FormatStringLiteral(_, strings, exprs) => {
285 | write!(f, "\"")?;
286 | for (i, string) in strings.iter().enumerate() {
287 | write!(f, "{}", string)?;
288 | if i < exprs.len() {
289 | write!(f, "{{{}}}", exprs[i])?;
290 | }
291 | }
292 | write!(f, "\"")
293 | }
294 | AST::Range(_, start, end) => write!(f, "{}..{}", start, end),
295 | AST::PostIncrement(_, expr, offset) => {
296 | write!(f, "{}{}", expr, if *offset == 1 { "++" } else { "--" })
297 | }
298 | AST::PreIncrement(_, expr, offset) => {
299 | write!(f, "{}{}", if *offset == 1 { "++" } else { "--" }, expr)
300 | }
301 | AST::ArrayLiteral(_, exprs) | AST::TupleLiteral(_, exprs) => {
302 | write!(f, "[")?;
303 | for (i, expr) in exprs.iter().enumerate() {
304 | if i > 0 {
305 | write!(f, ", ")?;
306 | }
307 | write!(f, "{}", expr)?;
308 | }
309 | write!(f, "]")
310 | }
311 | AST::DictionaryLiteral(_, items) => {
312 | write!(f, "{{")?;
313 | for (i, (key, value)) in items.iter().enumerate() {
314 | if i > 0 {
315 | write!(f, ", ")?;
316 | }
317 | write!(f, "{}: {}", key, value)?;
318 | }
319 | write!(f, "}}")
320 | }
321 | AST::Namespace {
322 | span: _,
323 | name,
324 | body,
325 | } => write!(f, "namespace {} {{ {} }}", name, body),
326 | AST::Import {
327 | span: _,
328 | path,
329 | alias,
330 | } => {
331 | write!(f, "import {}", path)?;
332 | if let Some(alias) = alias {
333 | write!(f, " as {}", alias)?;
334 | }
335 | Ok(())
336 | }
337 | AST::FromImport {
338 | span: _,
339 | path,
340 | names,
341 | } => {
342 | write!(f, "from {} import ", path)?;
343 | for (i, (name, alias)) in names.iter().enumerate() {
344 | if i == 0 {
345 | write!(f, "{{")?;
346 | }
347 | if i > 0 {
348 | write!(f, ", ")?;
349 | }
350 | write!(f, "{}", name)?;
351 | if let Some(alias) = alias {
352 | write!(f, " as {}", alias)?;
353 | }
354 | }
355 | if !names.is_empty() {
356 | write!(f, "}}")?;
357 | }
358 | Ok(())
359 | }
360 | AST::StarExpression(_, expr) => write!(f, "*{}", expr),
361 | AST::StarStarExpression(_, expr) => write!(f, "**{}", expr),
362 | }
363 | }
364 | }
365 |
--------------------------------------------------------------------------------
/src/common.rs:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Copyright (C) 2023 Mustafa Quraish
4 | Check the LICENSE file for more information.
5 | */
6 |
7 | use std::cell::RefCell;
8 | use std::rc::Rc;
9 |
10 | pub type Ref = Rc>;
11 |
12 | // macro_rules! get {
13 | // ($val:expr) => {
14 | // &*$val.borrow()
15 | // };
16 | // }
17 | // pub(crate) use get;
18 |
19 | macro_rules! make {
20 | ($val:expr) => {
21 | std::rc::Rc::new(std::cell::RefCell::new($val))
22 | };
23 | }
24 | pub(crate) use make;
25 |
26 | #[derive(Clone, Copy)]
27 | pub struct Location {
28 | pub line: usize,
29 | pub column: usize,
30 | pub filename: &'static str,
31 | }
32 |
33 | impl std::fmt::Display for Location {
34 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
35 | write!(f, "{}:{}:{}", self.filename, self.line, self.column)
36 | }
37 | }
38 |
39 | impl std::fmt::Debug for Location {
40 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
41 | write!(f, "{}", self)
42 | }
43 | }
44 |
45 | #[derive(Clone, Copy)]
46 | pub struct Span(pub Location, pub Location);
47 |
48 | impl std::fmt::Display for Span {
49 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
50 | write!(f, "{} - {}", self.0, self.1)
51 | }
52 | }
53 |
54 | impl std::fmt::Debug for Span {
55 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
56 | write!(f, "{}", self)
57 | }
58 | }
59 |
60 | impl Span {
61 | pub fn extend(&self, other: &Span) -> Span {
62 | Span(self.0, other.1)
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/error.rs:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Copyright (C) 2023 Mustafa Quraish
4 | Check the LICENSE file for more information.
5 | */
6 |
7 | use crate::common::Span;
8 |
9 | #[derive(Debug)]
10 | pub enum ErrorKind {
11 | Lexer,
12 | Parser,
13 | UnexpectedEOF,
14 | Runtime,
15 | }
16 |
17 | #[derive(Debug)]
18 | pub struct Error {
19 | pub kind: ErrorKind,
20 | pub span: Span,
21 | pub message: String,
22 | }
23 |
24 | impl std::fmt::Display for Error {
25 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 | match self.kind {
27 | ErrorKind::Lexer | ErrorKind::Parser | ErrorKind::UnexpectedEOF => {
28 | write!(f, "SyntaxError: {}", self.message)
29 | }
30 | ErrorKind::Runtime => write!(f, "RuntimeError: {}", self.message),
31 | }
32 | }
33 | }
34 |
35 | pub type Result = std::result::Result;
36 |
37 | macro_rules! lexer_error {
38 | ($span:expr, $($arg:tt)*) => {
39 | return Err(crate::error::Error{
40 | kind: crate::error::ErrorKind::Lexer,
41 | span: $span.clone(),
42 | message: format!($($arg)*),
43 | })
44 | }
45 | }
46 | pub(crate) use lexer_error;
47 |
48 | macro_rules! parser_error {
49 | ($span:expr, $($arg:tt)*) => {
50 | return Err(crate::error::Error{
51 | kind: crate::error::ErrorKind::Parser,
52 | span: $span.clone(),
53 | message: format!($($arg)*),
54 | })
55 | }
56 | }
57 | pub(crate) use parser_error;
58 |
59 | macro_rules! eof_error {
60 | ($span:expr, $($arg:tt)*) => {
61 | return Err(crate::error::Error{
62 | kind: crate::error::ErrorKind::UnexpectedEOF,
63 | span: $span.clone(),
64 | message: format!("Unexpected EOF: {}", format!($($arg)*)),
65 | })
66 | }
67 | }
68 | pub(crate) use eof_error;
69 |
70 | macro_rules! runtime_error {
71 | ($span:expr, $($arg:tt)*) => {
72 | return Err(crate::error::Error{
73 | kind: crate::error::ErrorKind::Runtime,
74 | span: $span.clone(),
75 | message: format!($($arg)*),
76 | })
77 | }
78 | }
79 | pub(crate) use runtime_error;
80 |
81 | impl Error {
82 | pub fn print_with_source(&self) {
83 | let msg = &self.message;
84 | let filename = &self.span.0.filename;
85 | let file_content = match std::fs::read_to_string(filename) {
86 | Ok(content) => content,
87 | Err(_) => {
88 | println!("{}: Error: {}", self.span.0, msg);
89 | return;
90 | }
91 | };
92 | let lines = file_content.lines().collect::>();
93 | let context = 3;
94 |
95 | let start = self.span.0;
96 | let end = self.span.1;
97 |
98 | let min_line = if start.line <= context {
99 | 0
100 | } else {
101 | start.line - context - 1
102 | };
103 | let max_line = lines.len().min(end.line + context);
104 |
105 | println!(
106 | "╭────────────────────────────────────────────────────────────────────────────────"
107 | );
108 | println!("│ {}: Error: {}", start, msg);
109 | println!(
110 | "├─────┬──────────────────────────────────────────────────────────────────────────"
111 | );
112 | #[allow(clippy::needless_range_loop)]
113 | for line_no in min_line..max_line {
114 | let line = lines[line_no];
115 | if start.line - 1 <= line_no && line_no < end.line {
116 | let highlight_start = if line_no == start.line - 1 {
117 | start.column - 1
118 | } else {
119 | 0
120 | };
121 | let highlight_end = if line_no == end.line - 1 {
122 | end.column - 1
123 | } else {
124 | line.len()
125 | };
126 |
127 | let text_before = &line[..highlight_start];
128 | let text_highlight = &line[highlight_start..highlight_end];
129 | let text_after = &line[highlight_end..];
130 | println!(
131 | "│ {:>3} │ {}\x1b[0;31m{}\x1b[0m{}",
132 | line_no + 1,
133 | text_before,
134 | text_highlight,
135 | text_after
136 | );
137 |
138 | if start.line == end.line {
139 | if text_highlight.len() <= 1 {
140 | println!(
141 | "│ │ {}\x1b[0;31m▲\x1b[0m",
142 | " ".repeat(text_before.len())
143 | );
144 | } else {
145 | println!(
146 | "│ │ {}\x1b[0;31m└{}┘\x1b[0m",
147 | " ".repeat(text_before.len()),
148 | "─".repeat(text_highlight.len() - 2)
149 | );
150 | }
151 | }
152 | } else {
153 | println!("│ {:>3} │ {}", line_no + 1, line);
154 | }
155 | }
156 |
157 | println!(
158 | "╰─────┴──────────────────────────────────────────────────────────────────────────"
159 | );
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/src/interpreter/builtin.rs:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Copyright (C) 2023 Mustafa Quraish
4 | Check the LICENSE file for more information.
5 | */
6 |
7 | use crate::common::{make, Ref, Span};
8 | use crate::error::{runtime_error as error, Result};
9 | use crate::interpreter::value::{CallArgValues, Value};
10 | use crate::interpreter::{Interpreter, Scope};
11 | use crate::interpreter::random::RandomState;
12 | use std::io::{Read, Write};
13 | use std::rc::Rc;
14 |
15 | pub fn print(
16 | _interpreter: &mut Interpreter,
17 | _scope: Ref,
18 | _span: &Span,
19 | args: Vec,
20 | ) -> Result {
21 | for (i, arg) in args.iter().enumerate() {
22 | if i != 0 {
23 | print!(" ");
24 | }
25 | print!("{:?}", arg)
26 | }
27 | println!();
28 | Ok(Value::Nothing)
29 | }
30 |
31 | pub fn repr(
32 | _interpreter: &mut Interpreter,
33 | _scope: Ref,
34 | span: &Span,
35 | args: Vec,
36 | ) -> Result {
37 | if args.len() != 1 {
38 | error!(span, "repr() takes exactly one argument");
39 | }
40 | Ok(Value::String(Rc::new(args[0].repr())))
41 | }
42 |
43 | pub fn len(
44 | _interpreter: &mut Interpreter,
45 | _scope: Ref,
46 | span: &Span,
47 | args: Vec,
48 | ) -> Result {
49 | if args.len() != 1 {
50 | error!(span, "len() takes exactly one argument");
51 | }
52 |
53 | Ok(match &args[0] {
54 | Value::String(string) => Value::Integer(string.len() as i64),
55 | Value::Array(array) | Value::Tuple(array) => Value::Integer(array.borrow().len() as i64),
56 | Value::Dict(dict) => Value::Integer(dict.borrow().len() as i64),
57 | Value::Range(start, end) => Value::Integer(end - start),
58 | other => error!(span, "len() does not support {:?}", other),
59 | })
60 | }
61 |
62 | pub fn dump(
63 | _interpreter: &mut Interpreter,
64 | scope: Ref,
65 | _span: &Span,
66 | args: Vec,
67 | ) -> Result {
68 | // Dump the scope
69 | if !args.is_empty() {
70 | error!(_span, "dump() takes no arguments");
71 | }
72 | println!("{:#?}", scope.borrow().parent);
73 | Ok(Value::Nothing)
74 | }
75 |
76 | pub fn push(
77 | _interpreter: &mut Interpreter,
78 | _scope: Ref,
79 | span: &Span,
80 | args: Vec,
81 | ) -> Result {
82 | if args.len() != 2 {
83 | error!(span, "push() takes exactly two arguments");
84 | }
85 | match &args[0] {
86 | Value::Array(array) => {
87 | array.borrow_mut().push(args[1].clone());
88 | Ok(Value::Nothing)
89 | }
90 | other => error!(span, "push() does not support {:?}", other),
91 | }
92 | }
93 |
94 | pub fn pop(
95 | _interpreter: &mut Interpreter,
96 | _scope: Ref,
97 | span: &Span,
98 | args: Vec,
99 | ) -> Result {
100 | if args.len() != 1 {
101 | error!(span, "pop() takes exactly one argument");
102 | }
103 | match &args[0] {
104 | Value::Array(array) => {
105 | let mut array = array.borrow_mut();
106 | if array.is_empty() {
107 | error!(span, "pop() called on empty array");
108 | }
109 | Ok(array.pop().unwrap())
110 | }
111 | other => error!(span, "pop() does not support {:?}", other),
112 | }
113 | }
114 |
115 | pub fn exit(
116 | _interpreter: &mut Interpreter,
117 | _scope: Ref,
118 | span: &Span,
119 | args: Vec,
120 | ) -> Result {
121 | let code = match args.get(0) {
122 | Some(val) => match val {
123 | Value::Integer(i) => *i,
124 | _ => error!(span, "exit() may only take an integer as argument"),
125 | },
126 | None => 0,
127 | };
128 |
129 | match code.try_into() {
130 | Ok(code) => std::process::exit(code),
131 | Err(_) => std::process::exit(1),
132 | }
133 | }
134 |
135 | pub fn input(
136 | _interpreter: &mut Interpreter,
137 | _scope: Ref,
138 | span: &Span,
139 | args: Vec,
140 | ) -> Result {
141 | let prompt = if args.len() == 1 {
142 | match &args[0] {
143 | Value::String(string) => string.to_string(),
144 | _ => error!(span, "input() may only take a string as argument"),
145 | }
146 | } else if args.is_empty() {
147 | String::new()
148 | } else {
149 | error!(span, "input() takes either one or no arguments");
150 | };
151 | let mut input = String::new();
152 | print!("{}", prompt);
153 | std::io::Write::flush(&mut std::io::stdout()).unwrap();
154 | std::io::stdin().read_line(&mut input).unwrap();
155 | input = input.trim_end().to_string();
156 | Ok(Value::String(Rc::new(input)))
157 | }
158 |
159 | pub fn dict_get(
160 | _interpreter: &mut Interpreter,
161 | _scope: Ref,
162 | span: &Span,
163 | args: Vec,
164 | ) -> Result {
165 | if args.len() < 2 || args.len() > 3 {
166 | error!(span, "dict_get() takes two or three arguments");
167 | }
168 | let dict = match &args[0] {
169 | Value::Dict(dict) => dict,
170 | _ => error!(span, "dict_get() may only take a dict as first argument"),
171 | };
172 | let key = &args[1];
173 | let default = if args.len() == 3 {
174 | &args[2]
175 | } else {
176 | &Value::Nothing
177 | };
178 | let dict = dict.borrow();
179 | match dict.get(key) {
180 | Some(value) => Ok(value.clone()),
181 | None => Ok(default.clone()),
182 | }
183 | }
184 |
185 | pub fn dict_items(
186 | _interpreter: &mut Interpreter,
187 | _scope: Ref,
188 | span: &Span,
189 | args: Vec,
190 | ) -> Result {
191 | if args.len() != 1 {
192 | error!(span, "dict_items() takes exactly one argument");
193 | }
194 | let dict = match &args[0] {
195 | Value::Dict(dict) => dict,
196 | _ => error!(span, "dict_items() may only take a dict as argument"),
197 | };
198 | let dict = dict.borrow();
199 | let mut items = Vec::new();
200 | for (key, value) in dict.iter() {
201 | items.push(Value::Tuple(make!(vec![key.clone(), value.clone()])));
202 | }
203 | Ok(Value::Array(make!(items)))
204 | }
205 |
206 |
207 | pub fn dict_keys(
208 | _interpreter: &mut Interpreter,
209 | _scope: Ref,
210 | span: &Span,
211 | args: Vec,
212 | ) -> Result {
213 | if args.len() != 1 {
214 | error!(span, "dict_keys() takes exactly one argument");
215 | }
216 | let dict = match &args[0] {
217 | Value::Dict(dict) => dict,
218 | _ => error!(span, "dict_keys() may only take a dict as argument"),
219 | };
220 | let dict = dict.borrow();
221 | let mut keys = Vec::new();
222 | for key in dict.keys() {
223 | keys.push(key.clone());
224 | }
225 | Ok(Value::Array(make!(keys)))
226 | }
227 |
228 | pub fn dict_values(
229 | _interpreter: &mut Interpreter,
230 | _scope: Ref,
231 | span: &Span,
232 | args: Vec,
233 | ) -> Result {
234 | if args.len() != 1 {
235 | error!(span, "dict_values() takes exactly one argument");
236 | }
237 | let dict = match &args[0] {
238 | Value::Dict(dict) => dict,
239 | _ => error!(span, "dict_values() may only take a dict as argument"),
240 | };
241 | let dict = dict.borrow();
242 | let mut values = Vec::new();
243 | for value in dict.values() {
244 | values.push(value.clone());
245 | }
246 | Ok(Value::Array(make!(values)))
247 | }
248 |
249 | pub fn split(
250 | _interpreter: &mut Interpreter,
251 | _scope: Ref,
252 | span: &Span,
253 | args: Vec,
254 | ) -> Result {
255 | if args.len() != 2 {
256 | error!(span, "split() takes exactly two arguments");
257 | }
258 | let string = match &args[0] {
259 | Value::String(string) => string,
260 | _ => error!(span, "split() may only take a string as first argument"),
261 | };
262 | println!("{}", string);
263 | let separator = match &args[1] {
264 | Value::String(string) => string,
265 | _ => error!(span, "split() may only take a string as second argument"),
266 | };
267 | let mut items = Vec::new();
268 | for item in string.split(separator.as_str()) {
269 | items.push(Value::String(Rc::new(item.to_string())));
270 | }
271 | Ok(Value::Array(make!(items)))
272 | }
273 |
274 | pub fn strip(
275 | _interpreter: &mut Interpreter,
276 | _scope: Ref,
277 | span: &Span,
278 | args: Vec,
279 | ) -> Result {
280 | if args.len() > 2 {
281 | error!(span, "strip() takes at most two arguments");
282 | }
283 | let string = match &args[0] {
284 | Value::String(string) => string.to_string(),
285 | _ => error!(span, "strip() may only take a string as first argument"),
286 | };
287 | let chars = if args.len() == 2 {
288 | match &args[1] {
289 | Value::String(string) => string.to_string(),
290 | _ => error!(span, "strip() may only take a string as second argument"),
291 | }
292 | } else {
293 | " \t\n\r".to_string()
294 | };
295 |
296 | Ok(Value::String(Rc::new(
297 | string.trim_matches(|c| chars.contains(c)).to_string(),
298 | )))
299 | }
300 |
301 | pub fn lower(
302 | _interpreter: &mut Interpreter,
303 | _scope: Ref,
304 | span: &Span,
305 | args: Vec,
306 | ) -> Result {
307 | if args.len() != 1 {
308 | error!(span, "lower() takes exactly one argument");
309 | }
310 | let string = match &args[0] {
311 | Value::String(string) => string.to_string(),
312 | _ => error!(span, "lower() may only take a string as argument"),
313 | };
314 | Ok(Value::String(Rc::new(string.to_lowercase())))
315 | }
316 |
317 | pub fn upper(
318 | _interpreter: &mut Interpreter,
319 | _scope: Ref,
320 | span: &Span,
321 | args: Vec,
322 | ) -> Result {
323 | if args.len() != 1 {
324 | error!(span, "upper() takes exactly one argument");
325 | }
326 | let string = match &args[0] {
327 | Value::String(string) => string.to_string(),
328 | _ => error!(span, "upper() may only take a string as argument"),
329 | };
330 | Ok(Value::String(Rc::new(string.to_uppercase())))
331 | }
332 |
333 | pub fn join(
334 | _interpreter: &mut Interpreter,
335 | _scope: Ref,
336 | span: &Span,
337 | args: Vec,
338 | ) -> Result {
339 | if args.len() != 2 {
340 | error!(span, "join() takes exactly two arguments");
341 | }
342 | let iter = match &args[0] {
343 | Value::Iterator(iter) => iter,
344 | _ => error!(
345 | span,
346 | "join() may only take an iterable as the first argument"
347 | ),
348 | };
349 |
350 | let separator = match args.get(1) {
351 | Some(Value::String(string)) => string.to_string(),
352 | None => " ".to_string(),
353 | _ => error!(span, "join() may only take a string as the second argument"),
354 | };
355 | let mut result = String::new();
356 | let iter = &mut *(*iter.0).borrow_mut();
357 | for (i, item) in iter.enumerate() {
358 | if i > 0 {
359 | result.push_str(separator.as_str());
360 | }
361 | match item {
362 | Value::String(string) => result.push_str(string.as_str()),
363 | _ => error!(span, "join() may only take an iterator of strings"),
364 | }
365 | }
366 | Ok(Value::String(Rc::new(result)))
367 | }
368 |
369 | pub fn map(
370 | interpreter: &mut Interpreter,
371 | scope: Ref,
372 | span: &Span,
373 | args: Vec,
374 | ) -> Result {
375 | if args.len() != 2 {
376 | error!(span, "map() takes exactly two arguments");
377 | }
378 | let iter = match &args[0] {
379 | Value::Iterator(iter) => iter,
380 | _ => error!(
381 | span,
382 | "map() may only take an iterable as the first argument"
383 | ),
384 | };
385 | let function = &args[1];
386 | match function {
387 | Value::Function(_) => {}
388 | Value::BuiltInFunction(_) => {}
389 | _ => error!(
390 | span,
391 | "map() may only take a function as the second argument"
392 | ),
393 | };
394 | let mut result = Vec::new();
395 | let iter = &mut *(*iter.0).borrow_mut();
396 | for item in iter {
397 | let args: CallArgValues = vec![(None, item.clone())];
398 | result.push(interpreter.do_call(span, scope.clone(), None, function.clone(), &args)?);
399 | }
400 | Value::Array(make!(result)).iterator(span)
401 | }
402 |
403 | pub fn to_int(
404 | _interpreter: &mut Interpreter,
405 | _scope: Ref,
406 | span: &Span,
407 | args: Vec,
408 | ) -> Result {
409 | if args.len() != 1 {
410 | error!(span, "int() takes exactly one argument");
411 | }
412 | let value = match &args[0] {
413 | Value::Integer(i) => *i,
414 | Value::Float(f) => *f as i64,
415 | Value::Boolean(b) => *b as i64,
416 | Value::String(string) => match string.parse() {
417 | Ok(i) => i,
418 | Err(_) => error!(span, "Could not parse string as integer"),
419 | },
420 | _ => error!(span, "int() does not support {:?}", args[0]),
421 | };
422 | Ok(Value::Integer(value))
423 | }
424 |
425 | pub fn to_float(
426 | _interpreter: &mut Interpreter,
427 | _scope: Ref,
428 | span: &Span,
429 | args: Vec,
430 | ) -> Result {
431 | if args.len() != 1 {
432 | error!(span, "float() takes exactly one argument");
433 | }
434 | let value = match &args[0] {
435 | Value::Integer(i) => *i as f64,
436 | Value::Float(f) => *f,
437 | Value::String(string) => match string.parse() {
438 | Ok(f) => f,
439 | Err(_) => error!(span, "Could not parse string as float"),
440 | },
441 | _ => error!(span, "float() does not support {:?}", args[0]),
442 | };
443 | Ok(Value::Float(value))
444 | }
445 |
446 | pub fn to_str(
447 | _interpreter: &mut Interpreter,
448 | _scope: Ref,
449 | span: &Span,
450 | args: Vec,
451 | ) -> Result {
452 | if args.len() != 1 {
453 | error!(span, "str() takes exactly one argument");
454 | }
455 | let value = format!("{:?}", args[0]);
456 | Ok(Value::String(Rc::new(value)))
457 | }
458 |
459 | pub fn to_iter(
460 | _interpreter: &mut Interpreter,
461 | _scope: Ref,
462 | span: &Span,
463 | args: Vec,
464 | ) -> Result {
465 | if args.len() != 1 {
466 | error!(span, "iter() takes exactly one argument");
467 | }
468 | args[0].iterator(span)
469 | }
470 |
471 | pub fn to_array(
472 | _interpreter: &mut Interpreter,
473 | _scope: Ref,
474 | span: &Span,
475 | args: Vec,
476 | ) -> Result {
477 | if args.len() != 1 {
478 | error!(span, "collect() takes exactly one argument");
479 | }
480 | let iter = match &args[0] {
481 | Value::Iterator(iter) => iter,
482 | _ => error!(span, "collect() may only take an iterable as argument"),
483 | };
484 | let iter = &mut *(*iter.0).borrow_mut();
485 | let mut items = Vec::new();
486 | for item in iter {
487 | items.push(item.clone());
488 | }
489 | Ok(Value::Array(make!(items)))
490 | }
491 |
492 | pub fn iter_enumerate(
493 | _interpreter: &mut Interpreter,
494 | _scope: Ref,
495 | span: &Span,
496 | args: Vec,
497 | ) -> Result {
498 | if args.len() != 1 {
499 | error!(span, "enumerate() takes exactly one argument");
500 | }
501 | let iter = match &args[0] {
502 | Value::Iterator(iter) => iter,
503 | _ => error!(span, "enumerate() may only take an iterable as argument"),
504 | };
505 | let iter = &mut *(*iter.0).borrow_mut();
506 | let mut items = Vec::new();
507 | for (i, item) in iter.enumerate() {
508 | items.push(Value::Tuple(make!(vec![Value::Integer(i as i64), item])));
509 | }
510 | Ok(Value::Array(make!(items)))
511 | }
512 |
513 | pub fn file_open(
514 | _interpreter: &mut Interpreter,
515 | _scope: Ref,
516 | span: &Span,
517 | args: Vec,
518 | ) -> Result {
519 | if args.len() != 1 {
520 | error!(span, "open() takes exactly one argument");
521 | }
522 | let path = match &args[0] {
523 | Value::String(string) => string.clone(),
524 | _ => error!(span, "open() may only take a string as first argument"),
525 | };
526 | let file = match std::fs::File::open(path.to_string()) {
527 | Ok(file) => file,
528 | Err(err) => error!(span, "Could not open file: {}", err),
529 | };
530 | Ok(Value::File(make!((path.to_string(), file))))
531 | }
532 |
533 | pub fn file_read(
534 | _interpreter: &mut Interpreter,
535 | _scope: Ref,
536 | span: &Span,
537 | args: Vec,
538 | ) -> Result {
539 | if args.len() != 1 {
540 | error!(span, "read() takes exactly one argument");
541 | }
542 | let file = match &args[0] {
543 | Value::File(file) => file,
544 | _ => error!(span, "read() may only take a file as first argument"),
545 | };
546 | let mut file = file.borrow_mut();
547 | let mut buffer = String::new();
548 | match file.1.read_to_string(&mut buffer) {
549 | Ok(_) => Ok(Value::String(Rc::new(buffer))),
550 | Err(err) => error!(span, "Could not read file: {}", err),
551 | }
552 | }
553 |
554 | pub fn file_write(
555 | _interpreter: &mut Interpreter,
556 | _scope: Ref,
557 | span: &Span,
558 | args: Vec,
559 | ) -> Result {
560 | if args.len() != 2 {
561 | error!(span, "write() takes exactly two arguments");
562 | }
563 | let file = match &args[0] {
564 | Value::File(file) => file,
565 | _ => error!(span, "write() may only take a file as first argument"),
566 | };
567 | let string = match &args[1] {
568 | Value::String(string) => string,
569 | _ => error!(span, "write() may only take a string as second argument"),
570 | };
571 | let mut file = file.borrow_mut();
572 | match file.1.write_all(string.as_bytes()) {
573 | Ok(_) => Ok(Value::Nothing),
574 | Err(err) => error!(span, "Could not write to file: {}", err),
575 | }
576 | }
577 |
578 | pub fn debug(
579 | _interpreter: &mut Interpreter,
580 | _scope: Ref,
581 | span: &Span,
582 | args: Vec,
583 | ) -> Result {
584 | if args.len() != 1 {
585 | error!(span, "debug() takes exactly one argument");
586 | }
587 | println!("{:?}", args[0]);
588 | Ok(args[0].clone())
589 | }
590 |
591 | pub fn new_random_state(
592 | _interpreter: &mut Interpreter,
593 | _scope: Ref,
594 | span: &Span,
595 | args: Vec,
596 | ) -> Result {
597 | if args.len() != 0 {
598 | error!(span, "rand() takes no arguments");
599 | }
600 | Ok(Value::RandomState(make!(RandomState::new())))
601 | }
602 |
603 | pub fn randf(
604 | _interpreter: &mut Interpreter,
605 | _scope: Ref,
606 | span: &Span,
607 | args: Vec,
608 | ) -> Result {
609 | if args.len() != 1 {
610 | error!(span, "randf() takes at most one argument");
611 | }
612 | let state = match args[0] {
613 | Value::RandomState(ref state) => state,
614 | _ => error!(span, "randf() may only take a random state as argument"),
615 | };
616 | let random = state.borrow_mut().next();
617 | Ok(Value::Float(random as f64 / (2.0f64).powi(64)))
618 | }
619 |
620 | pub fn randi(
621 | _interpreter: &mut Interpreter,
622 | _scope: Ref,
623 | span: &Span,
624 | args: Vec,
625 | ) -> Result {
626 | let state = match args.get(0) {
627 | Some(Value::RandomState(ref state)) => state,
628 | _ => error!(span, "randi() requires a random state as first argument"),
629 | };
630 | let (min, max) = match args.len() {
631 | 1 => (0, 2),
632 | 2 => match args[1] {
633 | Value::Integer(min) => (0, min),
634 | _ => error!(span, "randi() may only take an integer as argument"),
635 | },
636 | 3 => match (&args[1], &args[2]) {
637 | (Value::Integer(min), Value::Integer(max)) => (*min, *max),
638 | _ => error!(span, "randi() may only take integers as arguments"),
639 | },
640 | _ => error!(span, "randi() takes at most two arguments"),
641 | };
642 | let random = state.borrow_mut().next() as i64;
643 | Ok(Value::Integer(min + if random > 0 { random } else { -random } % (max - min)))
644 | }
645 |
--------------------------------------------------------------------------------
/src/interpreter/mod.rs:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Copyright (C) 2023 Mustafa Quraish
4 | Check the LICENSE file for more information.
5 | */
6 |
7 | use crate::ast::ArgumentType::Keyword;
8 | use crate::ast::{ArgumentType, CallArgs, AST};
9 | use crate::common::{make, Ref, Span};
10 | use crate::error::{runtime_error as error, Result};
11 | use crate::interpreter::value::{
12 | builtin, CallArgValues, Class, ClassInstance, Function, IteratorValue, Value,
13 | };
14 | use std::collections::HashMap;
15 | use std::io::Read;
16 | use std::ops::Deref;
17 | use std::rc::Rc;
18 |
19 | mod builtin;
20 | mod random;
21 | pub mod value;
22 |
23 | #[derive(Debug)]
24 | pub struct Scope {
25 | pub vars: HashMap,
26 | pub parent: Option[>,
27 | pub in_function: bool,
28 | }
29 |
30 | impl Scope {
31 | pub fn new(parent: Option][>, in_function: bool) -> Ref {
32 | make!(Scope {
33 | vars: HashMap::new(),
34 | parent,
35 | in_function,
36 | })
37 | }
38 |
39 | fn insert(&mut self, name: &str, value: Value, update: bool, loc: &Span) -> Result<()> {
40 | if !update || self.vars.contains_key(name) {
41 | self.vars.insert(name.to_string(), value);
42 | } else {
43 | match &self.parent {
44 | Some(parent) => parent.borrow_mut().insert(name, value, update, loc)?,
45 | None => error!(loc, "Variable {} not found, couldn't update", name),
46 | }
47 | }
48 | Ok(())
49 | }
50 |
51 | fn get(&self, name: &str) -> Option {
52 | if self.vars.contains_key(name) {
53 | self.vars.get(name).cloned()
54 | } else {
55 | match &self.parent {
56 | Some(parent) => parent.borrow().get(name),
57 | None => None,
58 | }
59 | }
60 | }
61 | }
62 |
63 | #[derive(Debug)]
64 | enum ControlFlow {
65 | None,
66 | Continue,
67 | Break,
68 | Return(Value),
69 | }
70 |
71 | pub struct Interpreter {
72 | control_flow: ControlFlow,
73 | }
74 |
75 | impl Interpreter {
76 | pub fn new() -> Self {
77 | Self {
78 | control_flow: ControlFlow::None,
79 | }
80 | }
81 |
82 | pub fn run_and_return_scope(&mut self, ast: &Rc) -> Result][> {
83 | let scope = Scope::new(None, false);
84 | self.run_block_without_new_scope(ast, scope.clone())?;
85 | Ok(scope)
86 | }
87 |
88 | pub fn execute(&mut self, ast: &Rc) -> Result {
89 | let scope = Scope::new(None, false);
90 | self.run(ast, scope)
91 | }
92 |
93 | pub fn run_block_without_new_scope(
94 | &mut self,
95 | ast: &Rc,
96 | scope: Ref,
97 | ) -> Result {
98 | match ast.as_ref() {
99 | AST::Block(_, stmts) => {
100 | let mut last = None;
101 | for stmt in stmts {
102 | last = Some(self.run(stmt, scope.clone())?);
103 | match self.control_flow {
104 | ControlFlow::None => {}
105 | _ => break,
106 | }
107 | }
108 | Ok(last.unwrap_or_else(|| Value::Nothing))
109 | }
110 | _ => unreachable!("run_block_without_scope called on non-block"),
111 | }
112 | }
113 |
114 | pub fn run_file(&mut self, span: &Span, path: &str) -> Result][> {
115 | // Open file and read contents
116 | let mut file = std::fs::File::open(path).expect("File not found");
117 | let mut contents = String::new();
118 | match file.read_to_string(&mut contents) {
119 | Ok(_) => {}
120 | Err(_) => error!(span, "Failed to read file"),
121 | }
122 |
123 | let mut lexer =
124 | crate::lexer::Lexer::new(contents, Box::leak(path.to_string().into_boxed_str()));
125 | let tokens = lexer.lex()?;
126 |
127 | let mut parser = crate::parser::Parser::new(tokens);
128 | let ast = parser.parse()?;
129 |
130 | let mut interpreter = Interpreter::new();
131 | interpreter.run_and_return_scope(&ast)
132 | }
133 |
134 | fn run(&mut self, ast: &Rc, scope: Ref) -> Result {
135 | macro_rules! dispatch_op {
136 | ($span:expr, $op:path, $left:expr, $right:expr) => {{
137 | let left = self.run($left, scope.clone())?;
138 | let right = self.run($right, scope.clone())?;
139 | $op(&left, &right, $span)?
140 | }};
141 |
142 | ($span:expr, $op:path, $val:expr) => {{
143 | let val = self.run($val, scope.clone())?;
144 | $op(&val, $span)?
145 | }};
146 | }
147 | Ok(match ast.as_ref() {
148 | // Literals
149 | AST::BooleanLiteral(_, value) => Value::Boolean(*value),
150 | AST::IntegerLiteral(_, num) => Value::Integer(*num),
151 | AST::FloatLiteral(_, num) => Value::Float(*num),
152 | AST::StringLiteral(_, string) => Value::String(Rc::new(string.clone())),
153 | AST::Nothing(_) => Value::Nothing,
154 |
155 | AST::Plus(span, left, right) => dispatch_op!(span, Value::plus, left, right),
156 | AST::Minus(span, left, right) => dispatch_op!(span, Value::minus, left, right),
157 | AST::Multiply(span, left, right) => dispatch_op!(span, Value::multiply, left, right),
158 | AST::Power(span, left, right) => dispatch_op!(span, Value::power, left, right),
159 | AST::Divide(span, left, right) => dispatch_op!(span, Value::divide, left, right),
160 | AST::Modulo(span, left, right) => dispatch_op!(span, Value::modulo, left, right),
161 | AST::Negate(span, expr) => dispatch_op!(span, Value::negate, expr),
162 | AST::Not(span, expr) => dispatch_op!(span, Value::not, expr),
163 | AST::And(_, _left, _right) => {
164 | // Short circuiting
165 | let left = self.run(_left, scope.clone())?;
166 | match left {
167 | Value::Boolean(false) => return Ok(left),
168 | Value::Boolean(true) => {
169 | let right = self.run(_right, scope)?;
170 | match right {
171 | Value::Boolean(true) => return Ok(right),
172 | Value::Boolean(false) => return Ok(right),
173 | _ => error!(_right.span(), "Expected boolean, but got {}", right.type_of()),
174 | }
175 | }
176 | _ => error!(_left.span(), "Expected boolean, but got {}", left.type_of()),
177 | }
178 | }
179 | AST::Or(_, _left, _right) => {
180 | // Short circuiting
181 | let left = self.run(_left, scope.clone())?;
182 | match left {
183 | Value::Boolean(true) => return Ok(left),
184 | Value::Boolean(false) => {
185 | let right = self.run(_right, scope)?;
186 | match right {
187 | Value::Boolean(true) => return Ok(right),
188 | Value::Boolean(false) => return Ok(right),
189 | _ => error!(_right.span(), "Expected boolean, but got {}", right.type_of()),
190 | }
191 | }
192 | _ => error!(_left.span(), "Expected boolean, but got {}", left.type_of()),
193 | }
194 | }
195 | AST::In(span, left, right) => dispatch_op!(span, Value::contains, right, left),
196 |
197 | AST::Equals(span, left, right) => dispatch_op!(span, Value::equals, left, right),
198 | AST::NotEquals(span, left, right) => dispatch_op!(span, Value::not_equals, left, right),
199 | AST::LessThan(span, left, right) => dispatch_op!(span, Value::less_than, left, right),
200 |
201 | AST::GreaterThan(span, left, right) => {
202 | dispatch_op!(span, Value::greater_than, left, right)
203 | }
204 | AST::LessEquals(span, left, right) => {
205 | dispatch_op!(span, Value::less_equals, left, right)
206 | }
207 | AST::GreaterEquals(span, left, right) => {
208 | dispatch_op!(span, Value::greater_equals, left, right)
209 | }
210 |
211 | AST::Call(span, func, args) => self.handle_call(scope, span, func, args)?,
212 |
213 | AST::Function {
214 | span,
215 | name,
216 | args,
217 | required,
218 | is_static,
219 | in_class,
220 | body,
221 | } => {
222 | let func = Value::Function(make!(Function {
223 | span: *span,
224 | name: name.clone().unwrap_or_else(|| "".to_string()),
225 | args: args
226 | .iter()
227 | .map(|(name, default, argtype)| (
228 | name.clone(),
229 | default
230 | .as_ref()
231 | .map(|def| self.run(def, scope.clone()).unwrap()),
232 | *argtype,
233 | ))
234 | .collect(),
235 | required: *required,
236 | class_method: (*in_class && !*is_static),
237 | body: body.clone(),
238 | scope: scope.clone()
239 | }));
240 | match name {
241 | Some(name) => scope.borrow_mut().insert(name, func.clone(), false, span)?,
242 | None => {}
243 | }
244 | func
245 | }
246 | AST::FieldAccess(span, obj, field) => {
247 | let obj = self.run(obj, scope)?;
248 | obj.get_field(span, field)?
249 | }
250 | AST::Class {
251 | span,
252 | name,
253 | fields,
254 | parents,
255 | } => {
256 | let mut static_fields: HashMap = HashMap::new();
257 | let mut instance_fields: HashMap = HashMap::new();
258 | let parents: Option> = match parents {
259 | Some(parents) => {
260 | let mut parent_vals: Vec = Vec::new();
261 | for parent in parents {
262 | let parent_val = scope.borrow().get(parent.as_str());
263 | let class = match parent_val.clone() {
264 | Some(Value::Class(class)) => class,
265 | Some(val) => {
266 | error!(span, "Parent class `{}` is not a class", val.type_of());
267 | }
268 | None => {
269 | error!(span, "Parent class `{}` does not exist", parent);
270 | }
271 | };
272 | let class = class.borrow();
273 | let Class {
274 | span: _,
275 | name: _,
276 | parents: _,
277 | static_fields: parent_static_fields,
278 | fields: parent_fields,
279 | } = class.deref();
280 |
281 | static_fields.extend(parent_static_fields.borrow().clone()); // Handle static fields
282 | instance_fields.extend(parent_fields.clone()); // Handle instance fields
283 | parent_vals.push(parent_val.unwrap());
284 | }
285 | Some(parent_vals)
286 | }
287 | None => None,
288 | };
289 |
290 | for (name, (val, is_static)) in fields.iter() {
291 | let val = self.run(val, scope.clone())?;
292 | if *is_static {
293 | static_fields.insert(name.to_string(), val);
294 | } else {
295 | instance_fields.insert(name.to_string(), val);
296 | }
297 | }
298 |
299 | let class = Value::Class(make!(Class {
300 | span: *span,
301 | name: name.clone(),
302 | parents,
303 | static_fields: make!(static_fields),
304 | fields: instance_fields,
305 | }));
306 |
307 | scope
308 | .borrow_mut()
309 | .insert(name, class.clone(), false, span)?;
310 | class
311 | }
312 | AST::Slice {
313 | span,
314 | lhs,
315 | start,
316 | end,
317 | step,
318 | } => {
319 | let lhs = self.run(lhs, scope.clone())?;
320 | let start = start
321 | .clone()
322 | .map(|start| self.run(&start, scope.clone()))
323 | .transpose()?;
324 | let end = end
325 | .clone()
326 | .map(|end| self.run(&end, scope.clone()))
327 | .transpose()?;
328 | let step = step
329 | .clone()
330 | .map(|step| self.run(&step, scope.clone()))
331 | .transpose()?;
332 | lhs.slice(start, end, step, span)?
333 | }
334 |
335 | AST::Block(..) => {
336 | let block_scope = Scope::new(Some(scope.clone()), scope.borrow().in_function);
337 | self.run_block_without_new_scope(ast, block_scope)?
338 | }
339 | AST::Namespace { span, name, body } => {
340 | // Create a new scope for the namespace
341 | let namespace_scope = Scope::new(Some(scope.clone()), scope.borrow().in_function);
342 |
343 | // Run the namespace body
344 | self.run_block_without_new_scope(body, namespace_scope.clone())?;
345 |
346 | // Create the namespace value
347 | let namespace = Value::Namespace(*span, name.clone(), namespace_scope);
348 |
349 | // Insert the namespace into the parent scope
350 | scope.borrow_mut().insert(name, namespace, false, span)?;
351 |
352 | // Return nothing, namespaces are not an expression
353 | Value::Nothing
354 | }
355 | AST::Variable(span, name) => match name.as_str() {
356 | "len" => builtin!(len),
357 | "print" => builtin!(print),
358 | "input" => builtin!(input),
359 | "str" => builtin!(to_str),
360 | "repr" => builtin!(repr),
361 | "open" => builtin!(file_open),
362 | "exit" => builtin!(exit),
363 | "dump" => builtin!(dump),
364 | "new_random_state" => builtin!(new_random_state),
365 | _ => match scope.borrow().get(name) {
366 | Some(val) => val,
367 | None => {
368 | error!(span, "Variable '{}' not found", name);
369 | }
370 | },
371 | },
372 | AST::Return(span, val) => {
373 | if !scope.borrow().in_function {
374 | error!(span, "Return statement outside of function")
375 | }
376 | self.control_flow = ControlFlow::Return(self.run(val, scope)?);
377 | Value::Nothing
378 | }
379 | AST::Assignment(span, lhs, value) => {
380 | let value = self.run(value, scope.clone())?;
381 | self.handle_assign(scope, span, lhs, value.clone())?;
382 | value
383 | }
384 | AST::VarDeclaration(span, name, value) => {
385 | self.check_arg_name(name, span)?;
386 | let value = self.run(value, scope.clone())?;
387 | scope.borrow_mut().insert(name, value, false, span)?;
388 | Value::Nothing
389 | }
390 | AST::Assert(loc, cond, msg) => {
391 | let cond = self.run(cond, scope)?;
392 | match cond {
393 | Value::Boolean(true) => {}
394 | Value::Boolean(false) => match msg {
395 | Some(msg) => error!(loc, "Assertion failed: {}", msg),
396 | _ => error!(loc, "Assertion failed"),
397 | },
398 | _ => error!(loc, "Assertion condition must be a boolean"),
399 | }
400 | Value::Nothing
401 | }
402 | AST::If(span, cond, body, else_body) => {
403 | let cond = self.run(cond, scope.clone())?;
404 | match cond {
405 | Value::Boolean(true) => self.run(body, scope)?,
406 | Value::Boolean(false) => match else_body {
407 | Some(else_body) => self.run(else_body, scope)?,
408 | None => Value::Nothing,
409 | },
410 | _ => error!(span, "If condition must be a boolean"),
411 | }
412 | }
413 | AST::While(span, cond, body) => {
414 | loop {
415 | let cond = self.run(cond, scope.clone())?;
416 | match cond {
417 | Value::Boolean(true) => {
418 | self.run(body, scope.clone())?;
419 | match self.control_flow {
420 | ControlFlow::None => {}
421 | ControlFlow::Continue => self.control_flow = ControlFlow::None,
422 | ControlFlow::Break => {
423 | self.control_flow = ControlFlow::None;
424 | break;
425 | }
426 | ControlFlow::Return(_) => break,
427 | }
428 | }
429 | Value::Boolean(false) => break,
430 | _ => error!(span, "While condition must be a boolean"),
431 | };
432 | }
433 | Value::Nothing
434 | }
435 | AST::ForEach(span, loop_var, iter, body) => {
436 | self.check_arg_name(loop_var, span)?;
437 | let val = self.run(iter, scope.clone())?;
438 | let iter = val.iterator(span)?;
439 | match iter {
440 | Value::Iterator(IteratorValue(iter)) => {
441 | let iter = &mut *(*iter).borrow_mut();
442 | for val in iter {
443 | let loop_scope =
444 | Scope::new(Some(scope.clone()), scope.borrow().in_function);
445 | loop_scope
446 | .borrow_mut()
447 | .insert(loop_var, val.clone(), false, span)?;
448 | self.run(body, loop_scope)?;
449 | match self.control_flow {
450 | ControlFlow::None => {}
451 | ControlFlow::Continue => self.control_flow = ControlFlow::None,
452 | ControlFlow::Break => {
453 | self.control_flow = ControlFlow::None;
454 | break;
455 | }
456 | ControlFlow::Return(_) => break,
457 | }
458 | }
459 | }
460 | _ => error!(span, "For loop must iterate over an iterable"),
461 | };
462 | Value::Nothing
463 | }
464 | AST::Comprehension(span, var, iter, expr, cond) => {
465 | let val = self.run(iter, scope.clone())?;
466 | let iter_value = val.iterator(span)?;
467 | match iter_value {
468 | Value::Iterator(IteratorValue(iter)) => {
469 | let iter = &mut *(*iter).borrow_mut();
470 | let mut vec = Vec::new();
471 | for val in iter {
472 | let loop_scope =
473 | Scope::new(Some(scope.clone()), scope.borrow().in_function);
474 | loop_scope
475 | .borrow_mut()
476 | .insert(var, val.clone(), false, span)?;
477 | if let Some(cond) = cond {
478 | let condition = self.run(cond, loop_scope.clone())?;
479 | match condition {
480 | Value::Boolean(true) => {}
481 | Value::Boolean(false) => continue,
482 | _ => error!(
483 | cond.span(),
484 | "Comprehension condition must be a boolean"
485 | ),
486 | };
487 | }
488 | vec.push(self.run(expr, loop_scope)?);
489 | }
490 | Value::Array(make!(vec))
491 | }
492 | _ => error!(iter.span(), "Comprehension target must be iterable"),
493 | }
494 | }
495 | AST::For {
496 | span,
497 | init,
498 | cond,
499 | step,
500 | body,
501 | } => {
502 | let loop_scope = Scope::new(Some(scope.clone()), scope.borrow().in_function);
503 | if let Some(init) = init {
504 | self.run(init, loop_scope.clone())?;
505 | }
506 | loop {
507 | if let Some(cond) = cond {
508 | let cond = self.run(cond, loop_scope.clone())?;
509 | match cond {
510 | Value::Boolean(true) => {}
511 | Value::Boolean(false) => break,
512 | _ => error!(span, "For condition must be a boolean"),
513 | };
514 | }
515 | self.run(body, loop_scope.clone())?;
516 | match self.control_flow {
517 | ControlFlow::None => {}
518 | ControlFlow::Continue => self.control_flow = ControlFlow::None,
519 | ControlFlow::Break => {
520 | self.control_flow = ControlFlow::None;
521 | break;
522 | }
523 | ControlFlow::Return(_) => break,
524 | }
525 | if let Some(step) = step {
526 | self.run(step, loop_scope.clone())?;
527 | }
528 | }
529 | Value::Nothing
530 | }
531 | AST::FormatStringLiteral(_, strings, exprs) => {
532 | let mut result = String::new();
533 | for (i, string) in strings.iter().enumerate() {
534 | result.push_str(string);
535 | if i < exprs.len() {
536 | let expr = self.run(&exprs[i], scope.clone())?;
537 | result.push_str(format!("{:?}", expr).as_str());
538 | }
539 | }
540 | Value::String(Rc::new(result))
541 | }
542 | AST::Range(span, start, end) => {
543 | let start = self.run(start, scope.clone())?;
544 | let end = self.run(end, scope)?;
545 | Value::create_range(&start, &end, span)?
546 | }
547 |
548 | AST::Break(_) => {
549 | self.control_flow = ControlFlow::Break;
550 | Value::Nothing
551 | }
552 | AST::Continue(_) => {
553 | self.control_flow = ControlFlow::Continue;
554 | Value::Nothing
555 | }
556 | AST::Index(span, left, right) => {
557 | let left = self.run(left, scope.clone())?;
558 | let right = self.run(right, scope)?;
559 | // match left {
560 | // // Value::Dict
561 | // _ => left.index(&right, span)?,
562 | // }
563 | left.index(&right, span)?
564 | }
565 | AST::PostIncrement(span, expr, offset) => {
566 | let value = self.run(expr, scope.clone())?;
567 | match &value {
568 | Value::Integer(val) => {
569 | let new_val = Value::Integer(*val + offset);
570 | self.handle_assign(scope, span, expr, new_val)?;
571 | }
572 | _ => error!(span, "Operation only supported for integers"),
573 | }
574 | value
575 | }
576 | AST::PreIncrement(span, expr, offset) => {
577 | let value = self.run(expr, scope.clone())?;
578 | match &value {
579 | Value::Integer(val) => {
580 | let new_val = Value::Integer(*val + offset);
581 | self.handle_assign(scope, span, expr, new_val.clone())?;
582 | new_val
583 | }
584 | _ => error!(span, "Operation only supported for integers"),
585 | }
586 | }
587 | AST::ArrayLiteral(_, arr) => Value::Array(make!(arr
588 | .iter()
589 | .map(|x| self.run(x, scope.clone()))
590 | .collect::>>()?)),
591 | AST::TupleLiteral(_, arr) => Value::Tuple(make!(arr
592 | .iter()
593 | .map(|x| self.run(x, scope.clone()))
594 | .collect::>>()?)),
595 | AST::DictionaryLiteral(_, arr) => {
596 | let mut map = HashMap::new();
597 | for (key, value) in arr {
598 | let span = key.span();
599 | let key = self.run(key, scope.clone())?;
600 | if !key.is_hashable() {
601 | error!(span, "Dictionary key must be hashable")
602 | }
603 | let value = self.run(value, scope.clone())?;
604 | map.insert(key, value);
605 | }
606 | Value::Dict(make!(map))
607 | }
608 | AST::Import { span, path, alias } => {
609 | let program = self.run_file(span, path)?;
610 | let name = match alias {
611 | Some(name) => name.clone(),
612 | None => {
613 | // Get last part of path
614 | let path = std::path::Path::new(path);
615 | path.with_extension("")
616 | .file_name()
617 | .unwrap()
618 | .to_str()
619 | .unwrap()
620 | .to_string()
621 | }
622 | };
623 | let program = Value::Namespace(*span, name.clone(), program);
624 | scope
625 | .borrow_mut()
626 | .insert(name.as_str(), program, false, span)?;
627 | Value::Nothing
628 | }
629 | AST::FromImport { span, path, names } => {
630 | let program = self.run_file(span, path)?;
631 | if names.first().expect("Import object is empty").0 == "*" { // Merge scopes
632 | scope.borrow_mut().vars.extend(program.borrow().vars.clone());
633 | } else { // Insert all names into scope
634 | for (name, alias) in names {
635 | let alias = match alias {
636 | Some(alias) => alias,
637 | None => name,
638 | };
639 | let value = match program.borrow().get(name.as_str()) {
640 | Some(value) => value.clone(),
641 | None => error!(span, "Variable `{}` doesn't exist", name),
642 | };
643 | scope
644 | .borrow_mut()
645 | .insert(alias.as_str(), value, false, span)?;
646 | }
647 | }
648 | Value::Nothing
649 | }
650 | AST::StarExpression(span, _) => error!(span, "Star expressions cannot be used here."),
651 | AST::StarStarExpression(span, _) => {
652 | error!(span, "Star star expressions cannot be used here.")
653 | }
654 | })
655 | }
656 |
657 | fn handle_assign(
658 | &mut self,
659 | scope: Ref,
660 | span: &Span,
661 | left: &Rc,
662 | value: Value,
663 | ) -> Result<()> {
664 | match &**left {
665 | AST::Variable(span, name) => {
666 | if scope.borrow().get(name.as_str()).is_none() {
667 | error!(span, "Variable {} doesn't exist", name)
668 | }
669 | // if self.builtins.contains_key(name.as_str()) {
670 | // error!(span, "`{}` is a built-in function, can't override it", name)
671 | // }
672 | scope
673 | .borrow_mut()
674 | .insert(name.as_str(), value, true, span)?;
675 | }
676 | AST::Index(span, left, right) => {
677 | let left = self.run(left, scope.clone())?;
678 | let right = self.run(right, scope)?;
679 | left.set_index(&right, &value, span)?;
680 | }
681 | AST::FieldAccess(span, left, name) => {
682 | let left = self.run(left, scope)?;
683 | left.set_field(span, name.as_str(), &value)?;
684 | }
685 | _ => error!(span, "Invalid assignment target"),
686 | }
687 | Ok(())
688 | }
689 |
690 | fn check_arg_name(&self, name: &str, span: &Span) -> Result<()> {
691 | if name == "self" {
692 | error!(span, "Argument name can't be `self`")
693 | // } else if self.builtins.contains_key(name) {
694 | // error!(span, "Argument name can't be a built-in function name")
695 | } else {
696 | Ok(())
697 | }
698 | }
699 |
700 | fn handle_call(
701 | &mut self,
702 | scope: Ref,
703 | span: &Span,
704 | obj: &Rc,
705 | args: &CallArgs,
706 | ) -> Result {
707 | let mut parent = None;
708 |
709 | let callee = match obj.deref() {
710 | AST::FieldAccess(_, left, field) => {
711 | let temp = self.run(left, scope.clone())?;
712 | parent = Some(temp.clone());
713 | temp.get_field(span, field)?
714 | }
715 | _ => self.run(obj, scope.clone())?,
716 | };
717 | let args = self.run_call_args(scope.clone(), args)?;
718 | self.do_call(span, scope, parent, callee, &args)
719 | }
720 |
721 | pub fn handle_star_expression(
722 | &mut self,
723 | scope: Ref,
724 | expr: Rc,
725 | ) -> Result> {
726 | let mut values: Vec = Vec::new();
727 | match self.run(&expr, scope)? {
728 | Value::Array(arr) => {
729 | for value in arr.borrow().iter() {
730 | values.push(value.clone());
731 | }
732 | }
733 | Value::Tuple(arr) => {
734 | for value in arr.borrow().iter() {
735 | values.push(value.clone());
736 | }
737 | }
738 | _ => error!(
739 | expr.span(),
740 | "Star expression can only be used with arrays and tuples"
741 | ),
742 | };
743 | Ok(values)
744 | }
745 |
746 | pub fn handle_star_star_expression(
747 | &mut self,
748 | scope: Ref,
749 | expr: Rc,
750 | ) -> Result {
751 | let mut values: CallArgValues = CallArgValues::new();
752 | match self.run(&expr, scope)? {
753 | Value::Dict(map) => {
754 | for (key, value) in map.borrow().iter() {
755 | match key {
756 | Value::String(key) => values.push((Some(key.deref().to_string()), value.clone())),
757 | _ => error!(expr.span(), "Star star expression can only be used with dictionaries using string keys"),
758 | }
759 | }
760 | }
761 | _ => error!(
762 | expr.span(),
763 | "Star star expression can only be used with dictionaries"
764 | ),
765 | };
766 | Ok(values)
767 | }
768 |
769 | pub fn run_call_args(&mut self, scope: Ref, args: &CallArgs) -> Result {
770 | /*
771 | Takes CallArgs and runs each argument, returning CallArgValues
772 | */
773 | let mut values = CallArgValues::new();
774 | for (name, value) in args {
775 | // We must handle star expressions
776 | match value.deref() {
777 | AST::StarExpression(span, expr) => {
778 | if name.is_some() {
779 | error!(span, "Star expressions can't be passed as named arguments")
780 | }
781 | self.handle_star_expression(scope.clone(), expr.clone())?
782 | .into_iter()
783 | .for_each(|value| {
784 | values.push((None, value));
785 | });
786 | }
787 | AST::StarStarExpression(span, expr) => {
788 | if name.is_some() {
789 | error!(
790 | span,
791 | "Star star expressions can't be passed as named arguments"
792 | )
793 | }
794 | self.handle_star_star_expression(scope.clone(), expr.clone())?
795 | .into_iter()
796 | .for_each(|(name, value)| {
797 | values.push((name, value));
798 | });
799 | }
800 | _ => {
801 | values.push((name.clone(), self.run(value, scope.clone())?));
802 | }
803 | }
804 | }
805 | Ok(values)
806 | }
807 |
808 | pub fn do_call(
809 | &mut self,
810 | span: &Span,
811 | scope: Ref,
812 | parent: Option,
813 | callee: Value,
814 | args: &CallArgValues,
815 | ) -> Result {
816 | // Handle the call
817 | Ok(match callee.clone() {
818 | Value::Function(func) => {
819 | // Setup scope
820 |
821 | let run_scope = Scope::new(Some(func.borrow().scope.clone()), true);
822 |
823 | // This will always inject parent if it exists, meaning even if function is not a class method.
824 | // if let Some(parent) = parent {
825 | // run_scope.borrow_mut().insert("self", parent, false, span)?;
826 | // }
827 |
828 | // Let's handle the function arguments
829 | let func = func.borrow();
830 |
831 | // Let's check if self should be injected
832 | if func.class_method && parent.is_some() {
833 | run_scope.borrow_mut().insert("self", parent.unwrap(), false, span)?;
834 | }
835 |
836 | let mut variadic_name = None;
837 | let mut variadic_keyword_name = None;
838 |
839 | let mut need: Vec = Vec::new();
840 | let mut seen: Vec = Vec::new();
841 | let mut arguments: HashMap = HashMap::new();
842 | let mut variadic: Vec = Vec::new();
843 | let mut variadic_keyword: HashMap = HashMap::new();
844 |
845 | for (name, arg, argtype) in func.args.iter() {
846 | match argtype {
847 | ArgumentType::Positional => need.push(name.to_string()),
848 | Keyword => {
849 | run_scope.borrow_mut().insert(
850 | name,
851 | arg.clone().expect("Keywords always have default values."),
852 | false,
853 | span,
854 | )?;
855 | }
856 | ArgumentType::Variadic => {
857 | variadic_name = Some(name);
858 | }
859 | ArgumentType::VariadicKeyword => {
860 | variadic_keyword_name = Some(name);
861 | }
862 | };
863 | }
864 |
865 | let mut state = ArgumentType::Positional;
866 | for (i, (name, arg)) in args.iter().enumerate() {
867 | match name {
868 | Some(name) => {
869 | if seen.contains(name) {
870 | error!(span, "Duplicate keyword argument: `{}`", name);
871 | } else if run_scope.borrow().vars.contains_key(name)
872 | || need.contains(name)
873 | {
874 | arguments.insert(name.to_string(), arg.clone());
875 | seen.push(name.clone());
876 | state = Keyword;
877 | } else if variadic_keyword_name.is_some() {
878 | variadic_keyword
879 | .insert(Value::String(Rc::new(name.clone())), arg.clone());
880 | seen.push(name.clone());
881 | state = Keyword;
882 | } else {
883 | error!(span, "Unexpected keyword in {}: `{}`", func.name, name);
884 | }
885 | }
886 | None => {
887 | if i < func.required {
888 | if state != ArgumentType::Positional {
889 | error!(
890 | span,
891 | "Positional arguments must be the first provided."
892 | );
893 | }
894 | let (name, ..) = func.args.get(i).unwrap();
895 | arguments.insert(name.to_string(), arg.clone());
896 | seen.push(name.clone());
897 | } else if variadic_name.is_some() {
898 | if state != ArgumentType::Variadic
899 | && state != ArgumentType::Positional
900 | {
901 | error!(span, "Variadic arguments must be the last provided.");
902 | }
903 | variadic.push(arg.clone());
904 | state = ArgumentType::Variadic;
905 | } else {
906 | error!(span, "Unexpected positional argument in {}", func.name);
907 | }
908 | }
909 | }
910 | }
911 |
912 | // Check if all required arguments are provided
913 | for name in need {
914 | if !seen.contains(&name) {
915 | error!(span, "Missing required argument: `{}`", name);
916 | }
917 | }
918 |
919 | if let Some(variadic_name) = variadic_name {
920 | arguments.insert(variadic_name.to_string(), Value::Array(make!(variadic)));
921 | }
922 |
923 | if let Some(variadic_keyword_name) = variadic_keyword_name {
924 | arguments.insert(
925 | variadic_keyword_name.to_string(),
926 | Value::Dict(make!(variadic_keyword)),
927 | );
928 | }
929 | for key in arguments.keys() {
930 | run_scope.borrow_mut().insert(
931 | key,
932 | arguments.get(key).unwrap().clone(),
933 | false,
934 | span,
935 | )?;
936 | }
937 |
938 | // Run the function
939 | let body = func.body.clone();
940 | self.run(&body, run_scope)?;
941 | let value = if let ControlFlow::Return(value) = &self.control_flow {
942 | value.clone()
943 | } else {
944 | Value::Nothing
945 | };
946 | self.control_flow = ControlFlow::None;
947 | value
948 | }
949 | Value::BuiltInFunction(func) => {
950 | let run_scope = Scope::new(Some(scope), true);
951 | let mut args: Vec = args.iter().map(|(_, arg)| arg.clone()).collect();
952 | if let Some(parent) = parent {
953 | args.insert(0, parent);
954 | }
955 | func.1.borrow()(self, run_scope, span, args)?
956 | }
957 | Value::Class(_class) => {
958 | let class = _class.borrow();
959 | let name = class.name.clone();
960 | let fields = class.fields.to_owned();
961 |
962 | let mut instance = Value::ClassInstance(make!(ClassInstance {
963 | span: *span,
964 | name: name.clone(),
965 | class: _class.clone(),
966 | parents: class.parents.clone(),
967 | in_initializer: true,
968 | static_fields: class.static_fields.clone(),
969 | fields: fields.clone()
970 | }));
971 |
972 | // Call new if it exists
973 | let Some(function) = fields.get("new") else {
974 | error!(span, "Class '{}' has no initializer.", name)
975 | };
976 | match function {
977 | Value::Function { .. } => {
978 | self.do_call(span, scope, Some(instance.clone()), function.clone(), args)?;
979 | }
980 | _ => error!(
981 | span,
982 | "Expected function for initializer, but got '{}'",
983 | function.type_of()
984 | ),
985 | }
986 | instance.class_instance_set_in_initializer(false);
987 | instance
988 | }
989 | _ => error!(span, "Can't call object {:?}", callee),
990 | })
991 | }
992 | }
993 |
--------------------------------------------------------------------------------
/src/interpreter/random.rs:
--------------------------------------------------------------------------------
1 | /*
2 | Written in 2019 by David Blackman and Sebastiano Vigna (vigna@acm.org)
3 |
4 | To the extent possible under law, the author has dedicated all copyright
5 | and related and neighboring rights to this software to the public domain
6 | worldwide. This software is distributed without any warranty.
7 |
8 | See .
9 |
10 | This is xoshiro256++ 1.0, one of our all-purpose, rock-solid generators.
11 | It has excellent (sub-ns) speed, a state (256 bits) that is large
12 | enough for any parallel application, and it passes all tests we are
13 | aware of.
14 |
15 | For generating just floating-point numbers, xoshiro256+ is even faster.
16 |
17 | The state must be seeded so that it is not everywhere zero. If you have
18 | a 64-bit seed, we suggest to seed a splitmix64 generator and use its
19 | output to fill s.
20 | */
21 |
22 | use std::time::{SystemTime, UNIX_EPOCH};
23 |
24 | pub struct RandomState {
25 | s0: u64,
26 | s1: u64,
27 | s2: u64,
28 | s3: u64,
29 | }
30 |
31 | impl RandomState {
32 | pub fn new() -> Self {
33 | let time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
34 | // Turn time's last 4 digits into a f64
35 | let time_: u64 = (time % 10000).rotate_right(4);
36 | let mut s = RandomState {
37 | s0: time << (time_ % 16),
38 | s1: 0,
39 | s2: time_,
40 | s3: 0,
41 | };
42 | for _ in 0..(time % 10) {
43 | s.next();
44 | };
45 | s.s0 = s.next();
46 | s.s3 = s.next();
47 | s
48 | }
49 |
50 | pub fn next(&mut self) -> u64 {
51 | let result = (self.s0.overflowing_add(self.s3).0).rotate_left(23).overflowing_add(self.s0).0;
52 | let t = self.s1 << 17;
53 |
54 | self.s2 ^= self.s0;
55 | self.s3 ^= self.s1;
56 | self.s1 ^= self.s2;
57 | self.s0 ^= self.s3;
58 |
59 | self.s2 ^= t;
60 | self.s3 = self.s3.rotate_left(45);
61 | result
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/lexer.rs:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Copyright (C) 2023 Mustafa Quraish
4 | Check the LICENSE file for more information.
5 | */
6 |
7 | use crate::common::{Location, Span};
8 | use crate::error::{lexer_error as error, Result};
9 | use crate::token::{Token, TokenKind};
10 |
11 | #[derive(Debug)]
12 | pub struct Lexer {
13 | pub location: Location,
14 | input: String,
15 | current_index: usize,
16 | seen_newline: bool,
17 | }
18 |
19 | impl Lexer {
20 | pub fn new(input: String, filename: &'static str) -> Lexer {
21 | Lexer {
22 | location: Location {
23 | line: 1,
24 | column: 1,
25 | filename,
26 | },
27 | input,
28 | current_index: 0,
29 | seen_newline: false,
30 | }
31 | }
32 |
33 | fn cur(&self) -> Option {
34 | self.input.chars().nth(self.current_index)
35 | }
36 |
37 | fn peek(&self, offset: usize) -> Option {
38 | self.input.chars().nth(self.current_index + offset)
39 | }
40 |
41 | // fn peek_is(&self, s: &str) -> bool {
42 | // if self.current_index + s.len() > self.input.len() {
43 | // return false;
44 | // }
45 | // &self.input[self.current_index..self.current_index + s.len()] == s
46 | // }
47 |
48 | fn increment(&mut self) {
49 | match self.cur() {
50 | Some('\n') => {
51 | self.location.line += 1;
52 | self.location.column = 1;
53 | self.current_index += 1;
54 | self.seen_newline = true;
55 | }
56 | Some(_) => {
57 | self.current_index += 1;
58 | self.location.column += 1;
59 | }
60 | None => {}
61 | }
62 | }
63 |
64 | fn loc(&self) -> Location {
65 | self.location
66 | }
67 |
68 | fn push_simple(&mut self, tokens: &mut Vec, kind: TokenKind, len: usize) {
69 | let start = self.loc();
70 | let text = self.input[self.current_index..self.current_index + len].to_string();
71 | for _ in 0..len {
72 | self.increment();
73 | }
74 | self.push(tokens, Token::new(kind, Span(start, self.loc()), text));
75 | }
76 |
77 | fn push(&mut self, tokens: &mut Vec, mut token: Token) {
78 | token.newline_before = self.seen_newline;
79 | tokens.push(token);
80 | self.seen_newline = false;
81 | }
82 |
83 | pub fn lex(&mut self) -> Result> {
84 | let mut tokens: Vec = vec![];
85 | while let Some(c) = self.cur() {
86 | let start = self.loc();
87 | match c {
88 | c if c.is_whitespace() => self.increment(),
89 |
90 | // base N literals, i.e. 0b_1101, 0o_567, 0x_ff
91 | '0' if self.peek(1).map_or(false, |c| "box".contains(c)) => {
92 | let mut num = String::new();
93 |
94 | let base = match self.peek(1) {
95 | Some('b') => Base::Bin,
96 | Some('o') => Base::Oct,
97 | Some('x') => Base::Hex,
98 | _ => Base::Dec,
99 | };
100 |
101 | self.increment();
102 | self.increment();
103 |
104 | self.lex_num(&mut num, base, &start)?;
105 | self.push(
106 | &mut tokens,
107 | Token::new(base.into(), Span(start, self.loc()), num),
108 | );
109 | }
110 |
111 | // decimal int/float literals
112 | '0'..='9' => {
113 | let mut num = String::new();
114 |
115 | self.lex_num(&mut num, Base::Dec, &start)?;
116 | if let Some('.') = self.cur() {
117 | if let Some('.') = self.peek(1) {
118 | self.push(
119 | &mut tokens,
120 | Token::new(
121 | TokenKind::IntegerLiteralDec,
122 | Span(start, self.loc()),
123 | num,
124 | ),
125 | );
126 | } else {
127 | num.push('.');
128 | self.increment();
129 | self.lex_num(&mut num, Base::Dec, &start)?;
130 | self.push(
131 | &mut tokens,
132 | Token::new(TokenKind::FloatLiteral, Span(start, self.loc()), num),
133 | );
134 | }
135 | } else {
136 | self.push(
137 | &mut tokens,
138 | Token::new(TokenKind::IntegerLiteralDec, Span(start, self.loc()), num),
139 | );
140 | }
141 | }
142 | '+' => match self.peek(1) {
143 | Some('+') => self.push_simple(&mut tokens, TokenKind::PlusPlus, 2),
144 | Some('=') => self.push_simple(&mut tokens, TokenKind::PlusEquals, 2),
145 | _ => self.push_simple(&mut tokens, TokenKind::Plus, 1),
146 | },
147 | '-' => match self.peek(1) {
148 | Some('-') => self.push_simple(&mut tokens, TokenKind::MinusMinus, 2),
149 | Some('=') => self.push_simple(&mut tokens, TokenKind::MinusEquals, 2),
150 | _ => self.push_simple(&mut tokens, TokenKind::Minus, 1),
151 | },
152 | '*' => match self.peek(1) {
153 | Some('*') => self.push_simple(&mut tokens, TokenKind::StarStar, 2),
154 | Some('=') => self.push_simple(&mut tokens, TokenKind::StarEquals, 2),
155 | _ => self.push_simple(&mut tokens, TokenKind::Star, 1),
156 | },
157 | '/' => match self.peek(1) {
158 | Some('/') => {
159 | while let Some(c) = self.cur() {
160 | self.increment();
161 | if c == '\n' {
162 | break;
163 | }
164 | }
165 | }
166 | Some('*') => {
167 | let mut closed = false;
168 | while let Some(c) = self.cur() {
169 | self.increment();
170 | if c == '*' && self.cur() == Some('/') {
171 | self.increment();
172 | closed = true;
173 | break;
174 | }
175 | }
176 | if !closed {
177 | error!(Span(start, self.loc()), "Unterminated block comment");
178 | }
179 | }
180 | Some('=') => self.push_simple(&mut tokens, TokenKind::SlashEquals, 2),
181 | _ => self.push_simple(&mut tokens, TokenKind::Slash, 1),
182 | },
183 | '%' => self.push_simple(&mut tokens, TokenKind::Percent, 1),
184 | '(' => self.push_simple(&mut tokens, TokenKind::LeftParen, 1),
185 | ')' => self.push_simple(&mut tokens, TokenKind::RightParen, 1),
186 | '[' => self.push_simple(&mut tokens, TokenKind::LeftBracket, 1),
187 | ']' => self.push_simple(&mut tokens, TokenKind::RightBracket, 1),
188 | '|' => self.push_simple(&mut tokens, TokenKind::Pipe, 1),
189 | ':' => self.push_simple(&mut tokens, TokenKind::Colon, 1),
190 | '=' => match self.peek(1) {
191 | Some('>') => self.push_simple(&mut tokens, TokenKind::FatArrow, 2),
192 | Some('=') => self.push_simple(&mut tokens, TokenKind::EqualsEquals, 2),
193 | _ => self.push_simple(&mut tokens, TokenKind::Equals, 1),
194 | },
195 | '<' => match self.peek(1) {
196 | Some('=') => self.push_simple(&mut tokens, TokenKind::LessEquals, 2),
197 | _ => self.push_simple(&mut tokens, TokenKind::LessThan, 1),
198 | },
199 | '>' => match self.peek(1) {
200 | Some('=') => self.push_simple(&mut tokens, TokenKind::GreaterEquals, 2),
201 | _ => self.push_simple(&mut tokens, TokenKind::GreaterThan, 1),
202 | },
203 | '!' => match self.peek(1) {
204 | Some('=') => self.push_simple(&mut tokens, TokenKind::BangEquals, 2),
205 | _ => self.push_simple(&mut tokens, TokenKind::Bang, 1),
206 | },
207 | ';' => self.push_simple(&mut tokens, TokenKind::SemiColon, 1),
208 | ',' => self.push_simple(&mut tokens, TokenKind::Comma, 1),
209 | '{' => self.push_simple(&mut tokens, TokenKind::LeftBrace, 1),
210 | '}' => self.push_simple(&mut tokens, TokenKind::RightBrace, 1),
211 | '@' => self.push_simple(&mut tokens, TokenKind::At, 1),
212 | '"' | '`' => {
213 | let token = self.lex_string_literal()?;
214 | self.push(&mut tokens, token);
215 | }
216 | '.' => match self.peek(1) {
217 | Some('.') => self.push_simple(&mut tokens, TokenKind::DotDot, 2),
218 | _ => self.push_simple(&mut tokens, TokenKind::Dot, 1),
219 | },
220 |
221 | // identifiers
222 | 'a'..='z' | 'A'..='Z' | '_' => {
223 | let mut ident = String::new();
224 | while let Some(c) = self.cur() {
225 | match c {
226 | 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => {
227 | ident.push(c);
228 | self.increment();
229 | }
230 | _ => break,
231 | }
232 | }
233 | match ident.as_str() {
234 | "elif" => {
235 | self.push(
236 | &mut tokens,
237 | Token::new(TokenKind::Else, Span(start, self.loc()), ident.clone()),
238 | );
239 | self.push(
240 | &mut tokens,
241 | Token::new(TokenKind::If, Span(start, self.loc()), ident),
242 | );
243 | }
244 | _ => {
245 | self.push(&mut tokens, Token::from_str(ident, Span(start, self.loc())))
246 | }
247 | }
248 | }
249 | _ => error!(Span(start, self.loc()), "Unexpected character {}", c),
250 | }
251 | }
252 | self.push_simple(&mut tokens, TokenKind::EOF, 0);
253 | Ok(tokens)
254 | }
255 |
256 | fn lex_string_literal(&mut self) -> Result {
257 | let start = self.loc();
258 | let mut string = String::new();
259 | let quote = self.cur().unwrap();
260 | self.increment();
261 | while let Some(c) = self.cur() {
262 | match c {
263 | c if c == quote => {
264 | self.increment();
265 | return Ok(Token::new(
266 | if quote == '"' {
267 | TokenKind::StringLiteral
268 | } else {
269 | TokenKind::FormatStringLiteral
270 | },
271 | Span(start, self.loc()),
272 | string,
273 | ));
274 | }
275 | '\\' => {
276 | self.increment();
277 | match self.cur() {
278 | Some('\\') => string.push('\\'),
279 | Some(c) if (c == quote) => string.push(quote),
280 | Some('n') => string.push('\n'),
281 | Some('r') => string.push('\r'),
282 | Some('t') => string.push('\t'),
283 | Some('0') => string.push('\0'),
284 | Some('{') => string.push_str("\\{"),
285 | Some('}') => string.push_str("\\}"),
286 | _ => error!(Span(start, self.loc()), "Invalid escape sequence"),
287 | }
288 | self.increment();
289 | }
290 | '\n' => break,
291 | _ => {
292 | string.push(c);
293 | self.increment();
294 | }
295 | }
296 | }
297 | error!(Span(start, self.loc()), "Unterminated string literal");
298 | }
299 |
300 | fn lex_num(&mut self, num: &mut String, base: Base, start: &Location) -> Result<()> {
301 | while let Some(mut c) = self.cur() {
302 | c = c.to_ascii_lowercase();
303 | match (base, c) {
304 | (Base::Bin, '0'..='1')
305 | | (Base::Oct, '0'..='7')
306 | | (Base::Dec, '0'..='9')
307 | | (Base::Hex, '0'..='9' | 'a'..='f') => {
308 | num.push(c);
309 | self.increment();
310 | }
311 | (_, '0'..='9' | 'a'..='f') => {
312 | error!(Span(*start, self.loc()), "Invalid numerical literal");
313 | }
314 | (_, '_') => self.increment(),
315 | _ => break,
316 | }
317 | }
318 | Ok(())
319 | }
320 | }
321 |
322 | #[derive(Debug, Clone, Copy)]
323 | enum Base {
324 | Bin,
325 | Oct,
326 | Dec,
327 | Hex,
328 | }
329 |
330 | impl From for TokenKind {
331 | fn from(value: Base) -> Self {
332 | match value {
333 | Base::Bin => Self::IntegerLiteralBin,
334 | Base::Oct => Self::IntegerLiteralOct,
335 | Base::Dec => Self::IntegerLiteralDec,
336 | Base::Hex => Self::IntegerLiteralHex,
337 | }
338 | }
339 | }
340 |
--------------------------------------------------------------------------------
/src/main.rs:
--------------------------------------------------------------------------------
1 | /*
2 | Rattlescript is a dynamically typed, interpreted programming language written in Rust.
3 | Copyright (C) 2023 Haven Selph
4 | Copyright (C) 2023 Mustafa Quraish
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 | */
19 |
20 | #![allow(clippy::upper_case_acronyms)]
21 |
22 | use crate::error::Result;
23 |
24 | mod ast;
25 | mod common;
26 | mod error;
27 | mod interpreter;
28 | mod lexer;
29 | mod parser;
30 | mod repl;
31 | mod token;
32 |
33 | const LICENSE: &str = include_str!("../LICENSE.md");
34 |
35 | fn run_file(filename: &str, verbose: bool) -> Result<()> {
36 | let content = std::fs::read_to_string(filename).expect("Couldn't open input file");
37 |
38 | let mut lex = lexer::Lexer::new(content, Box::leak(filename.to_string().into_boxed_str()));
39 | let tokens = lex.lex()?;
40 |
41 | if verbose {
42 | for token in &tokens {
43 | println!("{:?}", token);
44 | }
45 | }
46 |
47 | let mut parser = parser::Parser::new(tokens);
48 | let ast = parser.parse()?;
49 |
50 | if verbose {
51 | println!("{:#?}", ast);
52 | }
53 |
54 | let mut interpreter = interpreter::Interpreter::new();
55 | interpreter.execute(&ast)?;
56 | Ok(())
57 | }
58 |
59 | fn print_help(filename: &str) {
60 | println!("Usage: {} [options] [filename]", filename);
61 | println!("Options:");
62 | println!(" -d, --disable-error-context Disable error context (default: false)");
63 | println!(" -v, --verbose Enable verbose output (default: false)");
64 | println!(" -i, --info Print info about the REPL");
65 | println!(" -l, --license Print the license");
66 | println!(" -h, --help Print this help message");
67 | }
68 |
69 | fn main() {
70 | let args = std::env::args().collect::>();
71 |
72 | let mut filename = None;
73 | let mut disable_error_context = false;
74 | let mut verbose = false;
75 |
76 | for arg in args.iter().skip(1) {
77 | match arg.as_str() {
78 | "-d" | "--disable-error-context" => disable_error_context = true,
79 | "-v" | "--verbose" => verbose = true,
80 | "-l" | "--license" => {
81 | println!("{}", LICENSE);
82 | std::process::exit(0);
83 | }
84 | "-i" | "--info" => {
85 | println!(
86 | "RattleScript REPL Version: {} | Language Version: {}",
87 | repl::REPL_VERSION,
88 | env!("CARGO_PKG_VERSION")
89 | );
90 | println!("Author: Haven Selph ");
91 | println!("Repository: ");
92 | println!("GNU General Public License v3.0: ");
93 | std::process::exit(0);
94 | }
95 | "-h" | "--help" => {
96 | print_help(&args[0]);
97 | std::process::exit(0);
98 | }
99 | arg => {
100 | // Check if first character is a dash
101 | if arg.starts_with('-') {
102 | eprintln!("Unknown option: {}", arg);
103 | print_help(&args[0]);
104 | std::process::exit(1);
105 | }
106 | if filename.is_some() {
107 | print_help(&args[0]);
108 | std::process::exit(1);
109 | }
110 | filename = Some(arg);
111 | }
112 | }
113 | }
114 |
115 | let rattle_script_path = match std::env::var("RATTLESCRIPT_PATH") {
116 | Ok(path) => {
117 | // Check if path is a directory
118 | if !std::path::Path::new(&path).is_dir() {
119 | eprintln!("{} is not a directory, consider set RATTLESCRIPT_PATH environment variable to the path of the RattleScript repository.", path);
120 | std::process::exit(1);
121 | }
122 | std::path::Path::new(&path).to_path_buf()
123 | }
124 | Err(_) => match std::env::current_dir() {
125 | Ok(path) => path,
126 | Err(_) => {
127 | eprintln!("Couldn't get current directory, set RATTLESCRIPT_PATH environment variable to the path of the RattleScript repository.");
128 | std::process::exit(1);
129 | }
130 | },
131 | };
132 |
133 | if rattle_script_path.join("std").exists() {
134 | std::env::set_var("RATTLESCRIPT_PATH", rattle_script_path.join("std"));
135 | } else {
136 | eprintln!("Couldn't find std directory in RATTLESCRIPT_PATH, set RATTLESCRIPT_PATH environment variable to the path of the RattleScript repository.");
137 | std::process::exit(1);
138 | }
139 |
140 | if filename.is_none() {
141 | let mut repl = repl::Repl::new(verbose);
142 | repl.run();
143 | std::process::exit(0);
144 | }
145 |
146 | let filename = match filename {
147 | Some(filename) => filename,
148 | None => {
149 | eprintln!("No filename provided");
150 | std::process::exit(1);
151 | }
152 | };
153 |
154 | let result = run_file(filename, verbose);
155 |
156 | match result {
157 | Ok(_) => std::process::exit(0),
158 | Err(err) => {
159 | if disable_error_context {
160 | eprintln!("{} {}", err.span.0, err.message);
161 | std::process::exit(1);
162 | } else {
163 | err.print_with_source();
164 | std::process::exit(1);
165 | }
166 | }
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/src/repl.rs:
--------------------------------------------------------------------------------
1 | /*
2 | Rattlescript is a dynamically typed, interpreted programming language written in Rust.
3 | Copyright (C) 2023 Haven Selph
4 | Copyright (C) 2023 Mustafa Quraish
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 | */
19 |
20 | use crate::ast::AST;
21 | use crate::common::Ref;
22 | use crate::error::{Error, ErrorKind, Result};
23 | use crate::interpreter::value::Value;
24 | use crate::interpreter::{Interpreter, Scope};
25 | use std::io::Write;
26 | use std::rc::Rc;
27 |
28 | pub const REPL_VERSION: &str = "1.0.0";
29 |
30 | pub struct Repl {
31 | interpreter: Interpreter,
32 | global_scope: Ref,
33 | verbose: bool,
34 | }
35 |
36 | impl Repl {
37 | pub fn new(verbose: bool) -> Repl {
38 | let interpreter = Interpreter::new();
39 | let global_scope = Scope::new(None, false);
40 | Repl {
41 | interpreter,
42 | global_scope,
43 | verbose,
44 | }
45 | }
46 |
47 | fn run_once(&mut self) -> Result<()> {
48 | let mut input = String::new();
49 | let ast = loop {
50 | let mut temp = String::new();
51 | print!("{}", if input.is_empty() { ">>> " } else { "... " });
52 | std::io::stdout().flush().expect("Failed to flush stdout");
53 | std::io::stdin()
54 | .read_line(&mut temp)
55 | .expect("Failed to read line");
56 | if temp.trim().is_empty() {
57 | if input.trim().is_empty() {
58 | return Ok(());
59 | }
60 | continue;
61 | }
62 |
63 | input.push_str(&temp);
64 | match self.try_parse(input.clone()) {
65 | Ok(ast) => break ast,
66 | Err(Error {
67 | kind: ErrorKind::UnexpectedEOF,
68 | ..
69 | }) => {}
70 | Err(err) => return Err(err),
71 | }
72 | };
73 |
74 | if self.verbose {
75 | println!("{:#?}", ast);
76 | }
77 |
78 | let val = self
79 | .interpreter
80 | .run_block_without_new_scope(&ast, self.global_scope.clone())?;
81 | match &val {
82 | Value::Nothing => {}
83 | _ => println!("{}", val.repr()),
84 | }
85 | Ok(())
86 | }
87 |
88 | fn try_parse(&self, input: String) -> Result> {
89 | let mut lex = crate::lexer::Lexer::new(input, "");
90 | let tokens = lex.lex()?;
91 |
92 | if self.verbose {
93 | for token in &tokens {
94 | println!("{:?}", token);
95 | }
96 | }
97 |
98 | let mut parser = crate::parser::Parser::new(tokens);
99 | parser.parse()
100 | }
101 |
102 | pub fn run(&mut self) {
103 | println!("Rattlescript Copyright (C) 2023 Haven Selph\nThis program comes with ABSOLUTELY NO WARRANTY.\nThis is free software, and you are welcome to redistribute it\nunder certain conditions.\n");
104 | println!(
105 | "RattleScript REPL, press Ctrl-C to exit | REPL Version: {} | Language Version: {}",
106 | REPL_VERSION,
107 | env!("CARGO_PKG_VERSION")
108 | );
109 | println!("GNU General Public License v3.0: ");
110 | loop {
111 | match self.run_once() {
112 | Ok(_) => {}
113 | Err(err) => {
114 | if err.span.0.line == err.span.1.line {
115 | let len = err.span.1.column - err.span.0.column;
116 | if len <= 1 {
117 | println!(" {}\x1b[0;31m▲\x1b[0m", " ".repeat(err.span.0.column));
118 | } else {
119 | println!(
120 | " {}\x1b[0;31m└{}┘\x1b[0m",
121 | " ".repeat(err.span.0.column),
122 | "─".repeat(len - 2)
123 | );
124 | }
125 | }
126 | println!("\x1b[0;31m{}\x1b[0m", err);
127 | }
128 | }
129 | }
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/src/token.rs:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2023 Haven Selph
3 | Copyright (C) 2023 Mustafa Quraish
4 | Check the LICENSE file for more information.
5 | */
6 |
7 | use crate::common::Span;
8 |
9 | #[allow(clippy::upper_case_acronyms)]
10 | #[derive(Debug, Clone, Eq, PartialEq)]
11 | pub enum TokenKind {
12 | And,
13 | As,
14 | Assert,
15 | At,
16 | Bang,
17 | BangEquals,
18 | Break,
19 | Class,
20 | Colon,
21 | Comma,
22 | Continue,
23 | Def,
24 | Dot,
25 | DotDot,
26 | EOF,
27 | Elif,
28 | Else,
29 | Equals,
30 | EqualsEquals,
31 | False,
32 | FatArrow,
33 | FloatLiteral,
34 | For,
35 | FormatStringLiteral,
36 | From,
37 | GreaterEquals,
38 | GreaterThan,
39 | Identifier,
40 | If,
41 | Import,
42 | In,
43 | IntegerLiteralBin,
44 | IntegerLiteralDec,
45 | IntegerLiteralHex,
46 | IntegerLiteralOct,
47 | LeftBrace,
48 | LeftBracket,
49 | LeftParen,
50 | LessEquals,
51 | LessThan,
52 | Let,
53 | Minus,
54 | MinusEquals,
55 | MinusMinus,
56 | Not,
57 | Namespace,
58 | Nothing,
59 | Or,
60 | Percent,
61 | Pipe,
62 | Plus,
63 | PlusEquals,
64 | PlusPlus,
65 | Return,
66 | RightBrace,
67 | RightBracket,
68 | RightParen,
69 | SemiColon,
70 | Slash,
71 | SlashEquals,
72 | Star,
73 | StarEquals,
74 | StarStar,
75 | Static,
76 | StringLiteral,
77 | True,
78 | While,
79 | }
80 |
81 | #[derive(Debug, Clone)]
82 | pub struct Token {
83 | pub kind: TokenKind,
84 | pub span: Span,
85 | pub text: String,
86 | pub newline_before: bool,
87 | }
88 |
89 | impl Token {
90 | pub fn new(kind: TokenKind, span: Span, text: String) -> Token {
91 | Token {
92 | kind,
93 | span,
94 | text,
95 | newline_before: false,
96 | }
97 | }
98 |
99 | pub fn from_str(text: String, span: Span) -> Token {
100 | Token {
101 | kind: match text.as_ref() {
102 | "and" => TokenKind::And,
103 | "as" => TokenKind::As,
104 | "assert" => TokenKind::Assert,
105 | "break" => TokenKind::Break,
106 | "class" => TokenKind::Class,
107 | "continue" => TokenKind::Continue,
108 | "def" => TokenKind::Def,
109 | "elif" => TokenKind::Elif,
110 | "else" => TokenKind::Else,
111 | "false" => TokenKind::False,
112 | "for" => TokenKind::For,
113 | "from" => TokenKind::From,
114 | "if" => TokenKind::If,
115 | "import" => TokenKind::Import,
116 | "in" => TokenKind::In,
117 | "let" => TokenKind::Let,
118 | "not" => TokenKind::Not,
119 | "namespace" => TokenKind::Namespace,
120 | "nothing" => TokenKind::Nothing,
121 | "or" => TokenKind::Or,
122 | "return" => TokenKind::Return,
123 | "static" => TokenKind::Static,
124 | "true" => TokenKind::True,
125 | "while" => TokenKind::While,
126 | _ => TokenKind::Identifier,
127 | },
128 | span,
129 | text,
130 | newline_before: false,
131 | }
132 | }
133 | }
134 |
135 | impl std::fmt::Display for Token {
136 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
137 | write!(f, "{:?}", self.kind)?;
138 | if !self.text.is_empty() {
139 | write!(f, "({})", self.text)?;
140 | }
141 | Ok(())
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/std/array.rat:
--------------------------------------------------------------------------------
1 | // Various functions to work on arrays
2 |
3 | def any(arr) {
4 | for item in arr {
5 | if item {
6 | return true
7 | }
8 | }
9 | return false
10 | }
11 |
12 | def all(arr) {
13 | for item in arr {
14 | if not item {
15 | return false
16 | }
17 | }
18 | return true
19 | }
20 |
21 | def sum(arr) {
22 | var total = 0
23 | for num in arr {
24 | total += num
25 | }
26 | total
27 | }
28 |
29 | def max(arr) {
30 | var max = arr[0]
31 | for num in arr {
32 | if num > max {
33 | max = num
34 | }
35 | }
36 | max
37 | }
38 |
39 | def min(arr) {
40 | var min = arr[0]
41 | for num in arr {
42 | if num < min {
43 | min = num
44 | }
45 | }
46 | min
47 | }
48 |
--------------------------------------------------------------------------------
/std/collection.rat:
--------------------------------------------------------------------------------
1 | class Counter {
2 | def new(self, arr) {
3 | self.arr = arr
4 | self.count = {}
5 | for item in arr {
6 | if item in self.count.keys() {
7 | self.count[item] += 1
8 | } else {
9 | self.count[item] = 1
10 | }
11 | }
12 | }
13 |
14 | def most_common(self) {
15 | // Return the most common item in the array.
16 | // If there is a tie, the first item is returned.
17 | let items = self.all_most_common()
18 | if items[0].len() > 0 {
19 | return (items[0][0], items[1])
20 | }
21 | return nothing
22 | }
23 |
24 | def all_most_common(self) {
25 | // Return a list of all the most common items
26 | // in the array. If there is a tie, all items
27 | // are returned.
28 | let max = 0
29 | let max_items = []
30 | for item in self.count.keys() {
31 | if self.count[item] > max {
32 | max = self.count[item]
33 | max_items = [item]
34 | } else if self.count[item] == max {
35 | max_items.push(item)
36 | }
37 | }
38 | return (max_items, max)
39 | }
40 |
41 | def least_common(self) {
42 | // Return the least common item in the array.
43 | // If there is a tie, the first item is returned.
44 | let items = self.all_least_common()
45 | if items[0].len() > 0 {
46 | return (items[0][0], items[1])
47 | }
48 | return nothing
49 | }
50 |
51 | def all_least_common(self) {
52 | // Return a list of all the least common items
53 | // in the array. If there is a tie, all items
54 | // are returned.
55 | let min = nothing
56 | let min_items = []
57 | for item in self.count.keys() {
58 | if min == nothing {
59 | min = self.count[item]
60 | min_items = [item]
61 | } else if self.count[item] < min {
62 | min = self.count[item]
63 | min_items = [item]
64 | } else if self.count[item] == min {
65 | min_items.push(item)
66 | }
67 | }
68 | return (min_items, min)
69 | }
70 |
71 | def count_item(self, item) {
72 | // Return the count of the given item in the array.
73 | return self.count.get(item, 0)
74 | }
75 |
76 | def items(self) {
77 | // Return a list of tuples of the form (item, count)
78 | // for each item in the array.
79 | let items = []
80 | for item in self.count.keys() {
81 | items.push((item, self.count[item]))
82 | }
83 | return items
84 | }
85 | }
86 |
87 | class OrderedDict {
88 | def new(self) {
89 | // Create a new ordered dictionary.
90 | self.keys = []
91 | self.dict = {}
92 | }
93 |
94 | def push(self, key, value) {
95 | self.dict[key] = value
96 | self.keys.push(key)
97 | }
98 |
99 | def get(self, key, default=nothing) {
100 | return self.dict.get(key, default)
101 | }
102 |
103 | def items(self) {
104 | let items = []
105 | for key in self.keys {
106 | items.push((key, self.dict[key]))
107 | }
108 | return items
109 | }
110 | }
111 |
112 | class LinkedList {
113 | static class Node {
114 | def new(self, val, next=nothing) {
115 | self.next = next
116 | self.val = val
117 | }
118 | }
119 |
120 | def new(self) {
121 | self.head = nothing
122 | self.len = 0
123 | }
124 |
125 | def get(self, idx) {
126 | if idx > self.len or 0 > idx {
127 | print(`Index '{idx}' out of bounds`)
128 | exit(1)
129 | }
130 | let cur = self.head
131 | let i = 0
132 | while i != idx {
133 | cur = cur.next
134 | i++
135 | }
136 | return cur
137 | }
138 |
139 | def push(self, val) {
140 | if self.head == nothing {
141 | self.head = Node(val)
142 | } else {
143 | let cur = self.head
144 | self.head = self.Node(val, next:cur)
145 | }
146 | self.len++
147 | }
148 |
149 | def push_many(self, *vals) {
150 | for val in vals {
151 | self.push(val)
152 | }
153 | }
154 |
155 | def push_at(self, idx, val) {
156 | if idx == 0 {
157 | self.push(val)
158 | return nothing
159 | }
160 | if idx > self.len or 0 > idx {
161 | print(`Index '{idx}' out of bounds`)
162 | exit(1)
163 | }
164 | let node = self.get(idx-1)
165 | let cur = node.next
166 | node.next = self.Node(val, next:cur)
167 | self.len++
168 | }
169 |
170 | def pop(self) {
171 | if self.len == 0 {
172 | print("Cannot pop on an empty linked list.")
173 | exit(1)
174 | }
175 | self.head = self.head.next
176 | self.len--
177 | return self.head
178 | }
179 |
180 | def pop_at(self, idx) {
181 | if idx == 0 {
182 | return self.pop()
183 | }
184 | if idx > self.len or 0 > idx {
185 | print(`Index '{idx}' out of bounds`)
186 | exit(1)
187 | }
188 | let node = self.get(idx-1)
189 | let popped = node.next
190 | node.next = popped.next
191 | self.len--
192 | return popped
193 | }
194 |
195 | def print(self) {
196 | let out = "Linked list: "
197 | let cur = self.head
198 | while cur != nothing {
199 | out += repr(cur.val)
200 | if cur.next != nothing {
201 | out += " -> "
202 | }
203 | cur = cur.next
204 | }
205 | print(out)
206 | }
207 | }
208 |
--------------------------------------------------------------------------------
/std/math.rat:
--------------------------------------------------------------------------------
1 | from std.array import (max as max_a, min as min_a)
2 |
3 | // Constants
4 | let pi = 3.141592653589793
5 | let e = 2.718281828459045
6 |
7 | // Helper functions
8 | def max(*args) => max_a(args)
9 | def min(*args) => min_a(args)
10 |
11 | def factorial(n) {
12 | if n == 0 {
13 | return 1
14 | }
15 | return n * factorial(n - 1)
16 | }
17 |
18 | def floor(x) => x - x % 1
19 |
20 | def ceil(x) => floor(x) + 1
21 |
22 | def round(x) => floor(x + 0.5)
23 |
24 | def abs(x) {
25 | if x < 0 {
26 | return -x
27 | }
28 | return x
29 | }
30 |
31 | def sqrt(x) => x ** 0.5
32 |
33 | def sin(x) {
34 | let sum = 0
35 | for i in 0..10 {
36 | sum += (-1) ** i * x ** (2 * i + 1) / factorial(2 * i + 1)
37 | }
38 | return sum
39 | }
40 |
41 | def cos(x) {
42 | let sum = 0
43 | for i in 0..10 {
44 | sum += (-1) ** i * x ** (2 * i) / factorial(2 * i)
45 | }
46 | return sum
47 | }
48 |
49 | def tan(x) => sin(x) / cos(x)
50 |
51 | def asin(x) {
52 | let sum = 0
53 | for i in 0..10 {
54 | sum += factorial(2 * i) * x ** (2 * i + 1) / (4 ** i * factorial(i) ** 2 * (2 * i + 1))
55 | }
56 | return sum
57 | }
58 |
59 | def acos(x) => pi / 2 - asin(x)
60 |
61 | def atan(x) {
62 | let sum = 0
63 | for i in 0..10 {
64 | sum += (-1) ** i * x ** (2 * i + 1) / (2 * i + 1)
65 | }
66 | return sum
67 | }
68 |
69 | def sinh(x) => (e ** x - e ** (-x)) / 2
70 |
71 | def cosh(x) => (e ** x + e ** (-x)) / 2
72 |
73 | def tanh(x) => sinh(x) / cosh(x)
74 |
75 | def asinh(x) => log(x + sqrt(x ** 2 + 1))
76 |
77 | def acosh(x) => log(x + sqrt(x ** 2 - 1))
78 |
79 | def atanh(x) => log((1 + x) / (1 - x)) / 2
80 |
81 | def log(x) {
82 | let sum = 0
83 | for i in 1..10 {
84 | sum += (-1) ** (i + 1) * (x - 1) ** i / i
85 | }
86 | return sum
87 | }
88 |
89 | def log(x, base) => log(x) / log(base)
90 |
91 | def lg(x) => log(x, 10)
92 |
--------------------------------------------------------------------------------
/std/random.rat:
--------------------------------------------------------------------------------
1 |
2 | class Random {
3 | def new(self) { self.state = new_random_state() }
4 | def randint(self, a=0, b=2) { return self.state.rand_i(a, b) }
5 | def rand(self) { return self.state.rand_f() }
6 | def choice(self, arr) { return arr[self.state.rand_i(0,arr.len())] }
7 | def shuffle(self, arr) {
8 | for i in 0..arr.len() {
9 | let j = self.state.rand_i(0, i+1)
10 | let temp = arr[i]
11 | arr[i] = arr[j]
12 | arr[j] = temp
13 | }
14 | return arr
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/std/string.rat:
--------------------------------------------------------------------------------
1 | def is_space(c) => c in [" ", "\t", "\n", "\r"]
2 | def is_alpha(c) => c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVQXYZ"
3 | def is_digit(c) => c in "0123456789"
4 | def is_alnum(c) => is_alpha(c) or is_digit(c)
5 |
--------------------------------------------------------------------------------
/tests/bad/addition.rat:
--------------------------------------------------------------------------------
1 | /// fail: Invalid types for addition
2 |
3 | 10 + "string"
4 |
--------------------------------------------------------------------------------
/tests/bad/assert.rat:
--------------------------------------------------------------------------------
1 | /// fail: Assertion failed
2 |
3 | assert 1 == 2
4 |
--------------------------------------------------------------------------------
/tests/bad/class_function_without_self.rat:
--------------------------------------------------------------------------------
1 | /// fail: First argument of class method must be self
2 |
3 | class Test {
4 | def new() {}
5 | }
6 |
--------------------------------------------------------------------------------
/tests/bad/comment.rat:
--------------------------------------------------------------------------------
1 | /// fail: Unterminated block comment
2 |
3 | /*
4 | /*
5 | */
6 | //
7 | /*
8 |
--------------------------------------------------------------------------------
/tests/bad/function_same_name_arguments.rat:
--------------------------------------------------------------------------------
1 | /// fail: Duplicate argument name
2 |
3 | def func(args, *args, **args) {}
4 |
--------------------------------------------------------------------------------
/tests/bad/no_argument_class_function.rat:
--------------------------------------------------------------------------------
1 | /// fail: First argument of class method must be self
2 |
3 | class Test {
4 | def new() {
5 | }
6 | }
7 |
8 | t = Test()
9 |
--------------------------------------------------------------------------------
/tests/bad/uninitialized_variable_assignment.rat:
--------------------------------------------------------------------------------
1 | /// fail: Variable x doesn't exist
2 |
3 | x = 2
4 |
--------------------------------------------------------------------------------
/tests/good/arrow_return.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | def add(a,b) => a+b
4 | assert add(1,2) == 3
5 |
--------------------------------------------------------------------------------
/tests/good/binary_logic.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | assert true or false
4 | assert false or true
5 | assert not (false and true)
6 | assert not (true and false)
7 | assert true and true
8 |
--------------------------------------------------------------------------------
/tests/good/binaryops.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | assert 1 + 1 * 2 == 3
4 | assert 2 * 2 ** 3 == 16
5 | assert 2 ** 3 * 2 == 16
6 | assert 2 ** 3 ** 2 == 512
7 | assert 11 * (10 + 1) == 121
8 | assert 11 * 10 + 1 == 111
9 | assert 5 - 2 - 3 == 0
10 | assert 8 / 2 / 2 == 2
11 |
--------------------------------------------------------------------------------
/tests/good/builtins.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | print("Hello world!", 1, [1,2,3,4], nothing, {1:2})
4 |
5 | assert repr("Hello world!") == "\"Hello world!\""
6 | assert repr(1) == "1"
7 | assert repr([1,2,3,4]) == "[1, 2, 3, 4]"
8 |
9 | assert len([1,2,3]) == 3
10 | assert len("Hello world!") == 12
11 |
12 | let a = [1,2,3,4]
13 | a.push(a.pop())
14 | assert a==[1,2,3,4]
15 |
16 | assert {1:2}.get(1) == 2
17 |
18 | assert "Hello world!".split(" ") == ["Hello", "world!"]
19 | assert ["Hello", "world!"].iter().join(" ") == "Hello world!"
20 |
21 | assert [1,2,3,4].iter().map(str).join(", ") == "1, 2, 3, 4"
22 |
23 | assert (1.2).int() == 1
24 |
25 | assert str(1) == "1"
26 |
27 | let file = open("./tests/good/builtins.rat")
28 | let lines = file.read().split("\n")
29 | print(lines)
30 | assert lines[0].strip() == "/// exit: 0"
31 |
--------------------------------------------------------------------------------
/tests/good/class.rat:
--------------------------------------------------------------------------------
1 | /// out: "1\n3"
2 |
3 | class TestClass {
4 | class InnerClass {
5 | def new(self, x, *ys) {
6 | self.x = x
7 | self.ys = ys
8 | }
9 | }
10 |
11 | def new(self, a, b, c) {
12 | self.a = a
13 | self.b = b
14 | self.c = c
15 | }
16 | }
17 |
18 |
19 | print(TestClass(1, 2, 3).a)
20 | print(TestClass(1, 3, 4).b)
21 |
--------------------------------------------------------------------------------
/tests/good/class_inheritance.rat:
--------------------------------------------------------------------------------
1 | /// out: "6"
2 |
3 | class Test {
4 | def new(self) {}
5 | def test_func(self, *a) {
6 | return a
7 | }
8 | }
9 |
10 |
11 | class Test2 {
12 | def test_func(self, *a) {
13 | let sum = 0
14 | for a in a {
15 | sum += a
16 | }
17 | return sum
18 | }
19 | }
20 |
21 | class InheritedTest(Test, Test2) {}
22 |
23 | let t = InheritedTest()
24 | print(t.test_func(1, 2, 3))
25 |
--------------------------------------------------------------------------------
/tests/good/class_instance_is_instance_of.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 | class T { def new(self) {} }
3 | assert T() == T
4 |
--------------------------------------------------------------------------------
/tests/good/closures.rat:
--------------------------------------------------------------------------------
1 | /// out: "Adding\nSubtracting"
2 |
3 | def operator(msg) {
4 | def wrapper(fn) {
5 | def inner(a, b) {
6 | print(msg)
7 | return fn(a, b)
8 | }
9 | return inner
10 | }
11 | return wrapper
12 | }
13 |
14 | @operator("Adding")
15 | def add(a, b) {
16 | return a + b
17 | }
18 |
19 | @operator("Subtracting")
20 | def sub(a, b) {
21 | return a - b
22 | }
23 |
24 | def main() {
25 | print(add(1, 2))
26 | print(sub(1, 2))
27 | }
28 |
29 | add(1,2)
30 | sub(1,2)
31 |
--------------------------------------------------------------------------------
/tests/good/dictionaries.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | let x = { "a": 1, "b": 2, "c": 3 }
4 | let keys = x.keys()
5 | let values = x.values()
6 | let items = x.items()
7 |
--------------------------------------------------------------------------------
/tests/good/fib.rat:
--------------------------------------------------------------------------------
1 | /// out: "5\n[0, 1, 1, 2]"
2 |
3 | def fib(n) {
4 | let a = 0
5 | let b = 1
6 | for i in 0..n {
7 | let t = a
8 | a = b
9 | b = t + b
10 | }
11 | return a
12 | }
13 |
14 | print(fib(5))
15 | print([fib(x) for x in 0..4])
16 |
--------------------------------------------------------------------------------
/tests/good/field_access_duplicate_run.rat:
--------------------------------------------------------------------------------
1 | /// out: "1\n2\n3"
2 |
3 | [print(x) for x in 1..4].iter()
4 |
--------------------------------------------------------------------------------
/tests/good/first_argument_variadic.rat:
--------------------------------------------------------------------------------
1 | /// out: "3"
2 |
3 |
4 | class Test {
5 | def new(self) {}
6 | def func(self, *a) => a
7 | }
8 |
9 | print(len(Test().func(1,2,3)))
10 |
--------------------------------------------------------------------------------
/tests/good/function_consuming_endline.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | class test { static def add(a,b) => a+b }
4 |
--------------------------------------------------------------------------------
/tests/good/if.rat:
--------------------------------------------------------------------------------
1 | /// out: "x is something\ny is nothing"
2 |
3 | let x = "hello"
4 | let y = nothing
5 |
6 | if x != nothing {
7 | print("x is something")
8 | }
9 |
10 | if y == nothing {
11 | print("y is nothing")
12 | }
13 |
14 | if false {
15 | print("this will never be printed")
16 | }
17 |
--------------------------------------------------------------------------------
/tests/good/if_statement_expression_body.rat:
--------------------------------------------------------------------------------
1 | /// out: "true"
2 | if (true) print("true")
3 |
--------------------------------------------------------------------------------
/tests/good/import.rat:
--------------------------------------------------------------------------------
1 | /// out: "3\n-1"
2 | import import_test as test
3 | print(test.add(1,2))
4 | print(test.sub(1,2))
5 |
--------------------------------------------------------------------------------
/tests/good/import_test.rat:
--------------------------------------------------------------------------------
1 | /// skip
2 | def add(a,b) => a+b
3 | def sub(a,b) => a-b
4 |
--------------------------------------------------------------------------------
/tests/good/index_assignment.rat:
--------------------------------------------------------------------------------
1 | /// out: "[1, 4, 3]"
2 | let x = [1,2,3]
3 | x[1] = 4
4 | print(x)
5 |
--------------------------------------------------------------------------------
/tests/good/lambda.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | let x = |a,b| => a+b
4 | assert x(1,2) == 3
5 |
--------------------------------------------------------------------------------
/tests/good/list_comprehension.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | assert [print(x) for x in [1,2,3,4]] == [nothing, nothing, nothing, nothing]
4 | assert [x for x in [1,2,3,4] if x > 2] == [3,4]
5 |
--------------------------------------------------------------------------------
/tests/good/lists_tuples.rat:
--------------------------------------------------------------------------------
1 | /// out: "1,2,3\n1,2,3"
2 |
3 | let x = [1,2,3]
4 | print(x.iter().map(str).join(","))
5 |
6 | let y = (1,2,3)
7 | print(y.iter().map(str).join(","))
8 |
--------------------------------------------------------------------------------
/tests/good/multiple_assignment.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | let x = 1
4 | let y = 2
5 | let a = x = y = 3
6 |
--------------------------------------------------------------------------------
/tests/good/mutation_assignment.rat:
--------------------------------------------------------------------------------
1 | /// out: "0"
2 | let x = 1
3 | x -= 1
4 | print(x)
5 |
--------------------------------------------------------------------------------
/tests/good/namespaces.rat:
--------------------------------------------------------------------------------
1 | /// out: "test\ntest2\ntest3\ntest"
2 |
3 | namespace test {
4 | def test() {
5 | print("test")
6 | }
7 |
8 | def test2() {
9 | print("test2")
10 | }
11 |
12 | def test3() {
13 | print("test3")
14 | }
15 | }
16 |
17 | test.test()
18 | test.test2()
19 | test.test3()
20 |
21 | let j = test
22 | j.test()
23 |
--------------------------------------------------------------------------------
/tests/good/number_bases.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | assert 0b101 == 5
4 | assert 0x123f == 4671
5 | assert 0o666 == 438
6 | assert 1 == 1
7 |
--------------------------------------------------------------------------------
/tests/good/postfix.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 | // This was a bug that caused the parser to assume that the list comp was a postfix.
3 | // It was fixed by adding a check for whether the current token had a newline before it.
4 |
5 | let x = 10
6 | [y for y in 0..12]
7 | let s = new_random_state()
8 | [y for y in 0..12]
9 |
--------------------------------------------------------------------------------
/tests/good/prefix_postfix_mutation.rat:
--------------------------------------------------------------------------------
1 | /// out: "9\n9\n9\n9\n10\n"
2 |
3 | let x = 10
4 | print(--x)
5 | print(x--)
6 | print(++x)
7 | print(x++)
8 | print(x)
9 |
--------------------------------------------------------------------------------
/tests/good/range_with_field_access.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | class Test {
4 | def new(self) => self.x = 1
5 | }
6 |
7 | let t=Test()
8 | let r = 0..t.x
9 |
--------------------------------------------------------------------------------
/tests/good/short_circut.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 | assert true or true+1 // fine, left side is true so right side is not evaluated
3 | assert not (false and true+1) // fine, left side is false so right side is not evaluated
4 |
--------------------------------------------------------------------------------
/tests/good/star_expressions.rat:
--------------------------------------------------------------------------------
1 | /// out: "3 3"
2 |
3 | let x = [1,2]
4 | let y = {"a":1,"b":2}
5 |
6 | def add(a,b) => a+b
7 |
8 | print(add(*x), add(**y))
9 |
--------------------------------------------------------------------------------
/tests/good/static_fields.rat:
--------------------------------------------------------------------------------
1 | /// out: "Test"
2 |
3 | class Test {
4 | static def print_name() {
5 | print("Test")
6 | }
7 | }
8 |
9 | Test.print_name()
10 |
11 |
--------------------------------------------------------------------------------
/tests/good/std_lib.rat:
--------------------------------------------------------------------------------
1 | /// out: "true\ntrue\ntrue\n"
2 | from std.string import *
3 | print(is_space(" "))
4 | print(is_alpha("a"))
5 | print(is_digit("1"))
6 |
--------------------------------------------------------------------------------
/tests/good/string_multiplication.rat:
--------------------------------------------------------------------------------
1 | /// exit: 0
2 |
3 | assert "-"*5 == "-----"
4 |
--------------------------------------------------------------------------------
/tests/good/while.rat:
--------------------------------------------------------------------------------
1 | /// out: "1\n2\n3\n4\n5\n6"
2 |
3 | let x = 0
4 | while x < 6 {
5 | x++
6 | print(x)
7 | }
8 |
--------------------------------------------------------------------------------
/tests/good/wildcard_import.rat:
--------------------------------------------------------------------------------
1 | /// out: "3\n2"
2 |
3 | from import_test import *
4 | print(add(1,2))
5 | print(sub(3,1))
6 |
--------------------------------------------------------------------------------
/tests/test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # NOT UNDER MY LICENSE
3 | # Original Author:
4 | # https://github.com/mustafaquraish/aecor/blob/master/meta/test.py
5 | from subprocess import run, PIPE
6 | import argparse
7 | from ast import literal_eval
8 | from dataclasses import dataclass
9 | from enum import Enum
10 | from pathlib import Path
11 | from typing import Union, Optional, Tuple
12 | import multiprocessing
13 | import colorama
14 | colorama.init()
15 |
16 |
17 | class Result(Enum):
18 | EXIT_WITH_CODE = 1
19 | EXIT_WITH_OUTPUT = 2
20 | FAIL = 3
21 | SKIP_SILENTLY = 4
22 | SKIP_REPORT = 5
23 |
24 |
25 | @dataclass(frozen=True)
26 | class Expected:
27 | type: Result
28 | value: Union[int, str, None]
29 |
30 |
31 | def get_expected(filename) -> Optional[Expected]:
32 | with open(filename) as file:
33 | for line in file:
34 | if not line.startswith("///"):
35 | break
36 |
37 | line = line[3:].strip()
38 |
39 | # Commands with no arguments
40 | if line == "skip":
41 | return Expected(Result.SKIP_SILENTLY, None)
42 | if line == "":
43 | continue
44 |
45 | if ":" not in line:
46 | print(f'[-] Invalid parameters in {filename}: "{line}"')
47 | break
48 |
49 | # Commands with arguments
50 | name, value = map(str.strip, line.split(":", 1))
51 |
52 | if name == "exit":
53 | return Expected(Result.EXIT_WITH_CODE, int(value))
54 | if name == "out":
55 | return Expected(Result.EXIT_WITH_OUTPUT, value)
56 | if name == "fail":
57 | return Expected(Result.FAIL, value)
58 |
59 | print(f'[-] Invalid parameter in {filename}: {line}')
60 | break
61 |
62 | return Expected(Result.SKIP_REPORT, None)
63 |
64 |
65 | def handle_test(interpreter: str, path: Path, expected: Expected) -> Tuple[bool, str, Path]:
66 | process = run(
67 | [interpreter, "--disable-error-context", str(path)],
68 | stdout=PIPE,
69 | stderr=PIPE
70 | )
71 |
72 | error = process.stderr.decode("utf-8").strip()
73 |
74 | if expected.type == Result.FAIL:
75 | if process.returncode == 0:
76 | return False, "Expected failure, but succeeded", path
77 |
78 | expected_error = expected.value
79 |
80 | if expected_error == error:
81 | return True, "(Success)", path
82 | elif expected_error in error:
83 | return True, "(Success)", path
84 | else:
85 | try:
86 | error_line = error.splitlines()[0]
87 | remaining = error_line.split("Error: ")[1]
88 | except IndexError:
89 | remaining = error
90 | return False, f"Did not find expected error message\nexpected: {repr(expected_error)}\ngot: '{repr(remaining)}'", path
91 |
92 | if process.returncode != 0 and expected.type != Result.EXIT_WITH_CODE:
93 | return False, f"Expected exit code 0, but got {process.returncode}\n{error}", path
94 |
95 | if expected.type == Result.EXIT_WITH_CODE:
96 | if process.returncode != expected.value:
97 | return False, f"Expected exit code {expected.value}, but got {process.returncode}\n{error}", path
98 |
99 | if expected.type == Result.EXIT_WITH_OUTPUT:
100 | output = process.stdout.decode('utf-8').strip()
101 | try:
102 | expected_out = literal_eval(expected.value).strip()
103 | except: # noqa
104 | raise SyntaxError(f'Invalid options in file {path}')
105 | if output != expected_out:
106 | return False, f'Incorrect output produced\nexpected: {repr(expected_out)}\ngot: {repr(output)}', path
107 |
108 | return True, "(Success)", path
109 |
110 |
111 | def pool_helper(args):
112 | return handle_test(*args)
113 |
114 |
115 | def main():
116 | parser = argparse.ArgumentParser(description="Runs RattleScript test suite")
117 | parser.add_argument(
118 | "-i",
119 | "--interpreter",
120 | default="debug",
121 | help="Which interpreter to use for testing. (default: debug)"
122 | )
123 | parser.add_argument(
124 | "files",
125 | nargs="?",
126 | default=["tests"],
127 | help="Files / folders to run"
128 | )
129 | parser.add_argument(
130 | "-c",
131 | "--cpus",
132 | type=int,
133 | default=multiprocessing.cpu_count(),
134 | )
135 | args = parser.parse_args()
136 | if args.interpreter != 'debug':
137 | run(["cargo", "build", f"--{args.interpreter}"])
138 | else:
139 | run(["cargo", "build"])
140 | interpreter_path = Path().cwd() / 'target' / args.interpreter / 'rattlescript'
141 | if interpreter_path.with_suffix('.exe').exists():
142 | print("[+] Assuming on Windows, .exe found")
143 | interpreter_path = interpreter_path.with_suffix('.exe')
144 | else:
145 | print("[+] Assuming on Linux, no .exe found")
146 | if not interpreter_path.exists():
147 | print(f"[-] Interpreter {interpreter_path} not found")
148 | exit(1)
149 | arg_files = args.files if isinstance(args.files, list) else [args.files]
150 | test_paths = [Path(pth) for pth in arg_files]
151 |
152 | tests_to_run = []
153 | for path in test_paths:
154 | files = []
155 |
156 | if path.is_dir():
157 | for path_ in path.glob('**/*.rat'):
158 | if path_.is_file():
159 | files.append(path_)
160 | else:
161 | files.append(path)
162 |
163 | for file in files:
164 | expected = get_expected(file)
165 | if expected.type == Result.SKIP_SILENTLY:
166 | continue
167 | if expected.type == Result.SKIP_REPORT:
168 | print(f'[-] Skipping {file}')
169 | continue
170 | tests_to_run.append((file, expected))
171 |
172 | num_passed = 0
173 | num_failed = 0
174 | num_total = len(tests_to_run)
175 |
176 | arguments = [
177 | (interpreter_path, test_path, expected)
178 | for num, (test_path, expected) in enumerate(tests_to_run)
179 | ]
180 |
181 | with multiprocessing.Pool(args.cpus) as pool:
182 | for passed, message, path in pool.imap_unordered(pool_helper, arguments):
183 | print(f" \33[2K[\033[92m{num_passed:3d}\033[0m", end="")
184 | print(f"/\033[91m{num_failed:3d}\033[0m]", end="")
185 | print(f" Running tests, finished {num_passed+num_failed} / {num_total}\r", end="", flush=True)
186 | if passed:
187 | num_passed += 1
188 | else:
189 | num_failed += 1
190 | print(f"\r\33[2K\033[91m[-] Failed {path.absolute()}\033[0m")
191 | message = message.replace('\n', '\n ')
192 | print(f" {message}", flush=True)
193 |
194 | print("\33[2K")
195 | print(f"Tests passed: \033[92m{num_passed}\033[0m")
196 | print(f"Tests failed: \033[91m{num_failed}\033[0m")
197 |
198 | if num_failed > 0:
199 | exit(1)
200 |
201 |
202 | if __name__ == "__main__":
203 | main()
204 |
--------------------------------------------------------------------------------
]