Compare commits
16 Commits
09400afa13
...
cd350c538e
| Author | SHA1 | Date |
|---|---|---|
|
|
cd350c538e | |
|
|
8d359f9969 | |
|
|
aed758101c | |
|
|
a9a8aff13b | |
|
|
804f314df7 | |
|
|
c1a8bc8577 | |
|
|
a3e0bd95bc | |
|
|
6abe437c70 | |
|
|
0133661ad4 | |
|
|
61b8f1ffb9 | |
|
|
0cccee936e | |
|
|
2bc8281f19 | |
|
|
6f3c152e73 | |
|
|
6e019fb3ac | |
|
|
3332511290 | |
|
|
6422737cf3 |
|
|
@ -0,0 +1,20 @@
|
|||
name: Publish
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [created]
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish to crates.io
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
CRATES_TOKEN: ${{ secrets.CRATES_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: publish
|
||||
- run: cargo publish --token ${CRATES_TOKEN}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
name: Cargo build & test
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- development
|
||||
- 'releases/**'
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build_and_test:
|
||||
name: Cargo test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: cargo test --verbose
|
||||
14
CHANGELOG.md
14
CHANGELOG.md
|
|
@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
### Added
|
||||
|
||||
### Changed
|
||||
|
||||
### Removed
|
||||
|
||||
## [0.1.0] - 2024-10-01
|
||||
|
||||
### Added
|
||||
|
||||
- Functions
|
||||
- without arguments
|
||||
- Raw commands
|
||||
|
|
@ -20,7 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
- lua blocks
|
||||
- imports
|
||||
- group
|
||||
- Tags
|
||||
|
||||
### Changed
|
||||
|
||||
### Removed
|
||||
[unreleased]: https://github.com/moritz-hoelting/shulkerscript-lang/compare/v0.1.0...HEAD
|
||||
[0.1.0]: https://github.com/moritz-hoelting/shulkerscript-lang/releases/tag/v0.1.0
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
# Code of Conduct - Shulkerscript Lang
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to make participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||
level of experience, education, socio-economic status, nationality, personal
|
||||
appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, or to ban
|
||||
temporarily or permanently any contributor for other behaviors that they deem
|
||||
inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at [shulkerscript@hoelting.dev](mailto:shulkerscript@hoelting.dev).
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant](https://contributor-covenant.org/), version
|
||||
[1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct/code_of_conduct.md) and
|
||||
[2.0](https://www.contributor-covenant.org/version/2/0/code_of_conduct/code_of_conduct.md),
|
||||
and was generated by [contributing-gen](https://github.com/bttger/contributing-gen).
|
||||
|
|
@ -0,0 +1,146 @@
|
|||
<!-- omit in toc -->
|
||||
# Contributing to Shulkerscript Lang
|
||||
|
||||
First off, thanks for taking the time to contribute! ❤️
|
||||
|
||||
All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉
|
||||
|
||||
> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
|
||||
> - Star the project
|
||||
> - Tweet about it
|
||||
> - Refer this project in your project's readme
|
||||
> - Mention the project at local meetups and tell your friends/colleagues
|
||||
|
||||
<!-- omit in toc -->
|
||||
## Table of Contents
|
||||
|
||||
- [Code of Conduct](#code-of-conduct)
|
||||
- [I Have a Question](#i-have-a-question)
|
||||
- [I Want To Contribute](#i-want-to-contribute)
|
||||
- [Reporting Bugs](#reporting-bugs)
|
||||
- [Suggesting Enhancements](#suggesting-enhancements)
|
||||
- [Your First Code Contribution](#your-first-code-contribution)
|
||||
- [Improving The Documentation](#improving-the-documentation)
|
||||
- [Styleguides](#styleguides)
|
||||
- [Commit Messages](#commit-messages)
|
||||
- [Join The Project Team](#join-the-project-team)
|
||||
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
This project and everyone participating in it is governed by the
|
||||
[Shulkerscript Lang Code of Conduct](https://github.com/moritz-hoelting/shulkerscript-lang/blob/main/CODE_OF_CONDUCT.md).
|
||||
By participating, you are expected to uphold this code. Please report unacceptable behavior
|
||||
to .
|
||||
|
||||
|
||||
## I Have a Question
|
||||
|
||||
> If you want to ask a question, we assume that you have read the available [Documentation](https://shulkerscript.hoelting.dev/).
|
||||
> When asking about a missing feature, please make sure that it is not already on the [Roadmap](https://shulkerscript.hoelting.dev/roadmap).
|
||||
|
||||
Before you ask a question, it is best to search for existing [Issues](https://github.com/moritz-hoelting/shulkerscript-lang/issues) and [Discussions](https://github.com/moritz-hoelting/shulkerscript-lang/discussions) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first.
|
||||
|
||||
If you then still feel the need to ask a question and need clarification, we recommend either [writing an email](mailto:shulkerscript@hoelting.dev) or opening a discussion on GitHub:
|
||||
|
||||
- Open a [Q&A Discussion](https://github.com/moritz-hoelting/shulkerscript-lang/discussions/new?category=q-a).
|
||||
- Provide as much context as you can about what you're running into.
|
||||
- Provide project and platform versions (Windows/Linux/macOS), depending on what seems relevant.
|
||||
|
||||
We will then take care of the issue as soon as possible.
|
||||
|
||||
## I Want To Contribute
|
||||
|
||||
> ### Legal Notice <!-- omit in toc -->
|
||||
> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license.
|
||||
|
||||
### Reporting Bugs
|
||||
|
||||
<!-- omit in toc -->
|
||||
#### Before Submitting a Bug Report
|
||||
|
||||
A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.
|
||||
|
||||
- Make sure that you are using the latest version.
|
||||
- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://shulkerscript.hoelting.dev/). If you are looking for support, you might want to check [this section](#i-have-a-question)).
|
||||
- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/moritz-hoelting/shulkerscript-lang/issues?q=label%3Abug).
|
||||
- Collect information about the bug:
|
||||
- Stack trace (Traceback)
|
||||
- OS, Platform and Version (Windows, Linux, macOS, x86, ARM)
|
||||
- Version of the Library.
|
||||
- Possibly your input and the output
|
||||
- Can you reliably reproduce the issue? And can you also reproduce it with older versions?
|
||||
|
||||
<!-- omit in toc -->
|
||||
#### How Do I Submit a Good Bug Report?
|
||||
|
||||
> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to [shulkerscript@hoelting.dev](mailto:shulkerscript@hoelting.dev).
|
||||
<!-- You may add a PGP key to allow the messages to be sent encrypted as well. -->
|
||||
|
||||
We use GitHub issues to track bugs and errors. If you run into an issue with the project:
|
||||
|
||||
- Open an [Issue](https://github.com/moritz-hoelting/shulkerscript-lang/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)
|
||||
- Explain the behavior you would expect and the actual behavior.
|
||||
- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case.
|
||||
- Provide the information you collected in the previous section.
|
||||
|
||||
Once it's filed:
|
||||
|
||||
- The project team will label the issue accordingly.
|
||||
- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced.
|
||||
- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution).
|
||||
|
||||
<!-- You might want to create an issue template for bugs and errors that can be used as a guide and that defines the structure of the information to be included. If you do so, reference it here in the description. -->
|
||||
|
||||
|
||||
### Suggesting Enhancements
|
||||
|
||||
This section guides you through submitting an enhancement suggestion for Shulkerscript Lang, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions.
|
||||
|
||||
<!-- omit in toc -->
|
||||
#### Before Submitting an Enhancement
|
||||
|
||||
- Make sure that you are using the latest version.
|
||||
- Read the [documentation](https://shulkerscript.hoelting.dev/) carefully and find out if the functionality is already covered, maybe by an individual configuration.
|
||||
- Perform a [search](https://github.com/moritz-hoelting/shulkerscript-lang/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
|
||||
- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library.
|
||||
|
||||
<!-- omit in toc -->
|
||||
#### How Do I Submit a Good Enhancement Suggestion?
|
||||
|
||||
Enhancement suggestions are tracked as [GitHub issues](https://github.com/moritz-hoelting/shulkerscript-lang/issues).
|
||||
|
||||
- Use a **clear and descriptive title** for the issue to identify the suggestion.
|
||||
- Provide a **step-by-step description of the suggested enhancement** in as many details as possible.
|
||||
- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you.
|
||||
- **Explain why this enhancement would be useful** to most Shulkerscript lang users. You may also want to point out the other projects that solved it better and which could serve as inspiration.
|
||||
|
||||
<!-- You might want to create an issue template for enhancement suggestions that can be used as a guide and that defines the structure of the information to be included. If you do so, reference it here in the description. -->
|
||||
|
||||
### Your First Code Contribution
|
||||
Think about which part of the project your idea fits into. Do you want to work on [the cli](https://github.com/moritz-hoelting/shulkerscript-cli), [the language](https://github.com/moritz-hoelting/shulkerscript-lang) or [the datapack generation](https://github.com/moritz-hoelting/shulkerbox)?
|
||||
|
||||
- Make sure you have [Rust](https://www.rust-lang.org/tools/install) installed.
|
||||
- Fork the repository and clone it to your local machine.
|
||||
- Create a new branch for your feature or bug fix.
|
||||
- Make your changes and commit them to your branch.
|
||||
- Push your changes to your fork.
|
||||
- Open a pull request in the original repository and describe the changes you made.
|
||||
|
||||
### Improving The Documentation
|
||||
If you want to improve the documentation, you can do so by editing the [documentation repository](https://github.com/moritz-hoelting/shulkerscript-webpage).
|
||||
|
||||
- Make sure you have [Node.js](https://nodejs.org/en/download) and [PNPM](https://pnpm.io/installation) installed.
|
||||
- Fork the repository and clone it to your local machine.
|
||||
- Create a new branch for your changes.
|
||||
- Start the development server with `pnpm dev --open`.
|
||||
- Make your changes and commit them to your branch.
|
||||
- Push your changes to your fork.
|
||||
- Open a pull request in the original repository and describe the changes you made.
|
||||
|
||||
## Join The Project Team
|
||||
We are always looking for new contributors to the project. If you are interested in joining the project team, please contact us at [shulkerscript@hoelting.dev](mailto:shulkerscript@hoelting.dev).
|
||||
|
||||
<!-- omit in toc -->
|
||||
## Attribution
|
||||
This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)!
|
||||
29
Cargo.toml
29
Cargo.toml
|
|
@ -4,19 +4,23 @@ version = "0.1.0"
|
|||
edition = "2021"
|
||||
|
||||
authors = ["Moritz Hölting <moritz@hoelting.dev>"]
|
||||
categories = ["compilers"]
|
||||
description = "ShulkerScript language implementation with compiler"
|
||||
description = "Shulkerscript language implementation with compiler"
|
||||
categories = ["compilers", "game-development"]
|
||||
keywords = ["minecraft", "datapack", "mcfunction"]
|
||||
repository = "https://github.com/moritz-hoelting/shulkerscript-lang"
|
||||
homepage = "https://shulkerscript.hoelting.dev/"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[features]
|
||||
default = ["lua", "shulkerbox"]
|
||||
default = ["fs_access", "lua", "shulkerbox", "zip"]
|
||||
fs_access = ["shulkerbox?/fs_access"]
|
||||
lua = ["dep:mlua"]
|
||||
serde = ["dep:serde", "shulkerbox?/serde"]
|
||||
shulkerbox = ["dep:shulkerbox"]
|
||||
lua = ["dep:mlua"]
|
||||
zip = ["shulkerbox?/zip"]
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
path-absolutize = { version = "3.1.1", features = ["use_unix_paths_on_wasm"] }
|
||||
|
|
@ -24,14 +28,17 @@ path-absolutize = { version = "3.1.1", features = ["use_unix_paths_on_wasm"] }
|
|||
[dependencies]
|
||||
chksum-md5 = "0.0.0"
|
||||
colored = "2.1.0"
|
||||
derive_more = { version = "0.99.17", default-features = false, features = ["deref", "from", "deref_mut"] }
|
||||
derive_more = { version = "1.0.0", default-features = false, features = ["deref", "deref_mut", "from"] }
|
||||
enum-as-inner = "0.6.0"
|
||||
getset = "0.1.2"
|
||||
mlua = { version = "0.9.7", features = ["lua54", "vendored"], optional = true }
|
||||
itertools = "0.13.0"
|
||||
mlua = { version = "0.10.0", features = ["lua54", "vendored"], optional = true }
|
||||
path-absolutize = "3.1.1"
|
||||
serde = { version = "1.0.197", features = ["derive", "rc"], optional = true }
|
||||
shulkerbox = { git = "https://github.com/moritz-hoelting/shulkerbox", default-features = false, optional = true, rev = "a2d20dab8ea97bbd873edafb23afaad34292457f" }
|
||||
pathdiff = "0.2.2"
|
||||
serde = { version = "1.0.214", features = ["derive", "rc"], optional = true }
|
||||
shulkerbox = { version = "0.1.0", default-features = false, optional = true }
|
||||
strsim = "0.11.1"
|
||||
strum = { version = "0.26.2", features = ["derive"] }
|
||||
strum_macros = "0.26.2"
|
||||
thiserror = "1.0.58"
|
||||
strum_macros = "0.26.4"
|
||||
thiserror = "1.0.65"
|
||||
tracing = "0.1.40"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2024 Moritz Hölting <moritz@hoelting.dev>
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
14
README.md
14
README.md
|
|
@ -1,15 +1,23 @@
|
|||
# ShulkerScript Language
|
||||
# Shulkerscript Language
|
||||
|
||||
ShulkerScript is a simple, easy-to-use scripting language for Minecraft datapacks. It is designed to be easy to learn and use, while still being powerful enough to create complex scripts, while not being hindered by Minecraft command limitations.
|
||||
Shulkerscript is a simple, easy-to-use scripting language for Minecraft datapacks. It is designed to be easy to learn and use, while still being powerful enough to create complex scripts, while not being hindered by Minecraft command limitations.
|
||||
|
||||
## Usage
|
||||
|
||||
Add the following to your dependencies in `Cargo.toml`:
|
||||
```toml
|
||||
[dependencies]
|
||||
shulkerscript-lang = { git = "https://github.com/moritz-hoelting/shulkerscript-lang" }
|
||||
shulkerscript = "0.1.0"
|
||||
```
|
||||
|
||||
## VS Code Extension
|
||||
|
||||
A VS Code extension is available [here](https://marketplace.visualstudio.com/items?itemName=moritz-hoelting.shulkerscript-lang) to provide syntax highlighting and snippets for Shulkerscript files.
|
||||
|
||||
## Usage
|
||||
|
||||
Read the [documentation](https://shulkerscript.hoelting.dev) for more information on the language and cli.
|
||||
|
||||
## Features
|
||||
|
||||
### Functions
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
# Grammar of the ShulkerScript language
|
||||
# Grammar of the Shulkerscript language
|
||||
|
||||
## Table of contents
|
||||
|
||||
|
|
@ -14,7 +14,7 @@ Namespace: 'namespace' StringLiteral;
|
|||
|
||||
### Declaration
|
||||
```ebnf
|
||||
Declaration: FunctionDeclaration | Import;
|
||||
Declaration: FunctionDeclaration | Import | TagDeclaration;
|
||||
```
|
||||
|
||||
### Import
|
||||
|
|
@ -22,6 +22,11 @@ Declaration: FunctionDeclaration | Import;
|
|||
Import: 'from' StringLiteral 'import' Identifier;
|
||||
```
|
||||
|
||||
### TagDeclaration
|
||||
```ebnf
|
||||
TagDeclaration: 'tag' StringLiteral ('of' StringLiteral)? 'replace'? '[' (StringLiteral (',' StringLiteral)*)? ']';
|
||||
```
|
||||
|
||||
### FunctionDeclaration
|
||||
```ebnf
|
||||
Function:
|
||||
|
|
|
|||
|
|
@ -1,19 +1,24 @@
|
|||
/// An error that occurred during compilation.
|
||||
#[allow(missing_docs)]
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
|
||||
pub enum Error {
|
||||
#[error("An error occurred while working with Input/Output.")]
|
||||
IoError(String),
|
||||
#[error("An error occurred while lexing the source code.")]
|
||||
#[error("FileProviderError: {0}")]
|
||||
FileProviderError(#[from] super::FileProviderError),
|
||||
#[error(transparent)]
|
||||
LexicalError(#[from] crate::lexical::Error),
|
||||
#[error("An error occured while tokenizing the source code.")]
|
||||
TokenizeError(#[from] crate::lexical::token::TokenizeError),
|
||||
#[error(transparent)]
|
||||
ParseError(#[from] crate::syntax::error::Error),
|
||||
#[error(transparent)]
|
||||
TranspileError(#[from] crate::transpile::TranspileError),
|
||||
#[error("An error occurred")]
|
||||
Other(&'static str),
|
||||
#[error("An error occurred: {0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Creates a new error from a string.
|
||||
pub fn other<S: Into<String>>(error: S) -> Self {
|
||||
Self::Other(error.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// A specialized [`Result`] type for this crate.
|
||||
|
|
|
|||
|
|
@ -1,15 +1,35 @@
|
|||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::Error;
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
fmt::Display,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
/// A trait for providing file contents.
|
||||
pub trait FileProvider {
|
||||
/// Reads the contents of the file at the given path as bytes.
|
||||
///
|
||||
/// # Errors
|
||||
/// - If an error occurs while reading the file.
|
||||
/// - If the file does not exist.
|
||||
fn read_bytes<P: AsRef<Path>>(&self, path: P) -> Result<Cow<[u8]>, Error>;
|
||||
|
||||
/// Reads the contents of the file at the given path.
|
||||
///
|
||||
/// # Errors
|
||||
/// - If an error occurs while reading the file.
|
||||
/// - If the file does not exist.
|
||||
fn read_to_string<P: AsRef<Path>>(&self, path: P) -> Result<String, Error>;
|
||||
/// - If the file is not valid UTF-8.
|
||||
fn read_str<P: AsRef<Path>>(&self, path: P) -> Result<Cow<str>, Error> {
|
||||
let bytes = self.read_bytes(path)?;
|
||||
let string = std::str::from_utf8(&bytes)
|
||||
.map_err(|err| {
|
||||
let arc: Arc<dyn std::error::Error + Send + Sync> = Arc::new(err);
|
||||
Error::other(arc)
|
||||
})?
|
||||
.to_string();
|
||||
Ok(Cow::Owned(string))
|
||||
}
|
||||
}
|
||||
|
||||
/// Provides file contents from the file system.
|
||||
|
|
@ -37,28 +57,155 @@ where
|
|||
}
|
||||
|
||||
impl FileProvider for FsProvider {
|
||||
fn read_to_string<P: AsRef<Path>>(&self, path: P) -> Result<String, Error> {
|
||||
fn read_bytes<P: AsRef<Path>>(&self, path: P) -> Result<Cow<[u8]>, Error> {
|
||||
let full_path = self.root.join(path);
|
||||
std::fs::read_to_string(full_path).map_err(|err| Error::IoError(err.to_string()))
|
||||
std::fs::read(full_path)
|
||||
.map(Cow::Owned)
|
||||
.map_err(Error::from)
|
||||
}
|
||||
|
||||
fn read_str<P: AsRef<Path>>(&self, path: P) -> Result<Cow<str>, Error> {
|
||||
let full_path = self.root.join(path);
|
||||
std::fs::read_to_string(full_path)
|
||||
.map(Cow::Owned)
|
||||
.map_err(Error::from)
|
||||
}
|
||||
}
|
||||
|
||||
/// The error type for [`FileProvider`] operations.
|
||||
#[allow(clippy::module_name_repetitions)]
|
||||
#[derive(Debug, Clone, thiserror::Error)]
|
||||
pub struct Error {
|
||||
kind: std::io::ErrorKind,
|
||||
#[source]
|
||||
error: Option<Arc<dyn std::error::Error + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Creates a new [`Error`] from a known kind of error as well as an
|
||||
/// arbitrary error payload.
|
||||
///
|
||||
/// The `error` argument is an arbitrary
|
||||
/// payload which will be contained in this [`Error`].
|
||||
///
|
||||
/// Note that this function allocates memory on the heap.
|
||||
/// If no extra payload is required, use the `From` conversion from
|
||||
/// `ErrorKind`.
|
||||
pub fn new<E>(kind: std::io::ErrorKind, error: E) -> Self
|
||||
where
|
||||
E: Into<Arc<dyn std::error::Error + Send + Sync>>,
|
||||
{
|
||||
Self {
|
||||
kind,
|
||||
error: Some(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new [`Error`] from an arbitrary error payload.
|
||||
///
|
||||
/// It is a shortcut for [`Error::new`]
|
||||
/// with [`std::io::ErrorKind::Other`].
|
||||
pub fn other<E>(error: E) -> Self
|
||||
where
|
||||
E: Into<Arc<dyn std::error::Error + Send + Sync>>,
|
||||
{
|
||||
Self::new(std::io::ErrorKind::Other, error)
|
||||
}
|
||||
|
||||
/// Returns a reference to the inner error wrapped by this error (if any).
|
||||
///
|
||||
/// If this [`Error`] was constructed via [`Self::new`] then this function will
|
||||
/// return [`Some`], otherwise it will return [`None`].
|
||||
#[must_use]
|
||||
pub fn get_ref(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
|
||||
return self.error.as_deref();
|
||||
}
|
||||
|
||||
/// Consumes the [`Error`], returning its inner error (if any).
|
||||
///
|
||||
/// If this [`Error`] was constructed via [`Self::new`] then this function will
|
||||
/// return [`Some`], otherwise it will return [`None`].
|
||||
#[must_use]
|
||||
pub fn into_inner(self) -> Option<Arc<dyn std::error::Error + Send + Sync>> {
|
||||
self.error
|
||||
}
|
||||
|
||||
/// Returns the corresponding [`std::io::ErrorKind`] for this error.
|
||||
#[must_use]
|
||||
pub fn kind(&self) -> std::io::ErrorKind {
|
||||
self.kind
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match &self.error {
|
||||
Some(err) => write!(f, "{}: {}", self.kind, err),
|
||||
None => write!(f, "{}", self.kind),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Error {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::ErrorKind> for Error {
|
||||
fn from(value: std::io::ErrorKind) -> Self {
|
||||
Self {
|
||||
kind: value,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(value: std::io::Error) -> Self {
|
||||
let kind = value.kind();
|
||||
let error = value.into_inner().map(Arc::from);
|
||||
|
||||
Self { kind, error }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "shulkerbox")]
|
||||
mod vfs {
|
||||
use std::{borrow::Cow, sync::Arc};
|
||||
|
||||
use super::{Error, FileProvider, Path};
|
||||
use shulkerbox::virtual_fs::{VFile, VFolder};
|
||||
|
||||
impl FileProvider for VFolder {
|
||||
fn read_to_string<P: AsRef<Path>>(&self, path: P) -> Result<String, Error> {
|
||||
fn read_bytes<P: AsRef<Path>>(&self, path: P) -> Result<Cow<[u8]>, Error> {
|
||||
normalize_path_str(path).map_or_else(
|
||||
|| Err(Error::IoError("Invalid path".to_string())),
|
||||
|| Err(Error::from(std::io::ErrorKind::InvalidData)),
|
||||
|path| {
|
||||
self.get_file(&path)
|
||||
.ok_or_else(|| Error::IoError("File not found".to_string()))
|
||||
.ok_or_else(|| Error::from(std::io::ErrorKind::NotFound))
|
||||
.map(|file| Cow::Borrowed(file.as_bytes()))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn read_str<P: AsRef<Path>>(&self, path: P) -> Result<Cow<str>, Error> {
|
||||
normalize_path_str(path).map_or_else(
|
||||
|| Err(Error::from(std::io::ErrorKind::InvalidData)),
|
||||
|path| {
|
||||
self.get_file(&path)
|
||||
.ok_or_else(|| Error::from(std::io::ErrorKind::NotFound))
|
||||
.and_then(|file| match file {
|
||||
VFile::Text(text) => Ok(text.to_owned()),
|
||||
VFile::Binary(bin) => String::from_utf8(bin.clone())
|
||||
.map_err(|err| Error::IoError(err.to_string())),
|
||||
VFile::Text(text) => Ok(Cow::Borrowed(text.as_str())),
|
||||
VFile::Binary(bin) => {
|
||||
let string = std::str::from_utf8(bin).map_err(|err| {
|
||||
let arc: Arc<dyn std::error::Error + Send + Sync> =
|
||||
Arc::new(err);
|
||||
Error::new(std::io::ErrorKind::InvalidData, arc)
|
||||
})?;
|
||||
|
||||
Ok(Cow::Borrowed(string))
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
|
|
@ -112,15 +259,15 @@ mod vfs {
|
|||
dir.add_file("foo.txt", VFile::Text("foo".to_string()));
|
||||
dir.add_file("bar/baz.txt", VFile::Text("bar, baz".to_string()));
|
||||
|
||||
assert_eq!(dir.read_to_string("foo.txt").unwrap(), "foo".to_string());
|
||||
assert_eq!(
|
||||
dir.read_to_string("bar/baz.txt").unwrap(),
|
||||
dir.read_str("foo.txt").unwrap().into_owned(),
|
||||
"foo".to_string()
|
||||
);
|
||||
assert_eq!(
|
||||
dir.read_str("bar/baz.txt").unwrap().into_owned(),
|
||||
"bar, baz".to_string()
|
||||
);
|
||||
assert!(matches!(
|
||||
dir.read_to_string("nonexistent.txt"),
|
||||
Err(Error::IoError(_))
|
||||
));
|
||||
assert!(dir.read_str("nonexistent.txt").is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -291,7 +291,7 @@ fn write_error_line(
|
|||
(line_number == start_line && index >= start_location.column)
|
||||
|| (line_number == end_line
|
||||
&& (index + 1)
|
||||
< end_location
|
||||
<= end_location
|
||||
.map_or(usize::MAX, |end_location| end_location.column))
|
||||
|| (line_number > start_line && line_number < end_line)
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! The base module contains the core functionality of the `ShulkerScript` language.
|
||||
//! The base module contains the core functionality of the `Shulkerscript` language.
|
||||
|
||||
pub mod source_file;
|
||||
|
||||
|
|
@ -10,6 +10,6 @@ mod diagnostic;
|
|||
pub use diagnostic::{Handler, PrintHandler, SilentHandler, VoidHandler};
|
||||
|
||||
mod file_provider;
|
||||
pub use file_provider::{FileProvider, FsProvider};
|
||||
pub use file_provider::{Error as FileProviderError, FileProvider, FsProvider};
|
||||
|
||||
pub mod log;
|
||||
|
|
|
|||
|
|
@ -86,14 +86,18 @@ impl SourceFile {
|
|||
/// Load the source file from the given file path.
|
||||
///
|
||||
/// # Errors
|
||||
/// - [`Error::IoError`]: Error occurred when reading the file contents.
|
||||
/// - [`Error::FileProviderError`]: Error occurred when reading the file contents.
|
||||
pub fn load(
|
||||
path: &Path,
|
||||
identifier: String,
|
||||
provider: &impl FileProvider,
|
||||
) -> Result<Arc<Self>, Error> {
|
||||
let source = provider.read_to_string(path)?;
|
||||
Ok(Self::new(path.to_path_buf(), identifier, source))
|
||||
let source = provider.read_str(path)?;
|
||||
Ok(Self::new(
|
||||
path.to_path_buf(),
|
||||
identifier,
|
||||
source.into_owned(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Get the [`Location`] of a given byte index
|
||||
|
|
@ -132,6 +136,12 @@ impl SourceFile {
|
|||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the relative path of the source file from the current working directory.
|
||||
#[must_use]
|
||||
pub fn path_relative(&self) -> Option<PathBuf> {
|
||||
pathdiff::diff_paths(&self.path, std::env::current_dir().ok()?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a range of characters in a source file.
|
||||
|
|
|
|||
|
|
@ -7,16 +7,18 @@ use crate::base::{
|
|||
source_file::Span,
|
||||
};
|
||||
|
||||
use super::token_stream::Delimiter;
|
||||
use super::{token, token_stream::Delimiter};
|
||||
|
||||
/// Represents an error that occurred during the lexical analysis of the source code.
|
||||
#[allow(missing_docs)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("Comment is not terminated.")]
|
||||
#[error(transparent)]
|
||||
UnterminatedDelimitedComment(#[from] UnterminatedDelimitedComment),
|
||||
#[error("Delimiter is not terminated.")]
|
||||
#[error(transparent)]
|
||||
UndelimitedDelimiter(#[from] UndelimitedDelimiter),
|
||||
#[error("Tokenize error: {0}")]
|
||||
TokenizeError(#[from] token::TokenizeError),
|
||||
}
|
||||
|
||||
/// Source code contains an unclosed `/*` comment.
|
||||
|
|
|
|||
|
|
@ -41,6 +41,9 @@ pub enum KeywordKind {
|
|||
Namespace,
|
||||
From,
|
||||
Import,
|
||||
Tag,
|
||||
Of,
|
||||
Replace,
|
||||
}
|
||||
|
||||
impl Display for KeywordKind {
|
||||
|
|
@ -101,6 +104,9 @@ impl KeywordKind {
|
|||
Self::Namespace => "namespace",
|
||||
Self::From => "from",
|
||||
Self::Import => "import",
|
||||
Self::Tag => "tag",
|
||||
Self::Of => "of",
|
||||
Self::Replace => "replace",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -455,17 +461,8 @@ impl Token {
|
|||
|
||||
Self::walk_iter(iter, |character| !(character == '\n' || character == '\r'));
|
||||
|
||||
let is_cr = iter
|
||||
.peek()
|
||||
.map_or(false, |(_, character)| character == '\r');
|
||||
|
||||
let span = Self::create_span(start, iter);
|
||||
|
||||
if let (true, Some((_, '\n'))) = (is_cr, iter.next()) {
|
||||
// skips the crlf
|
||||
iter.next();
|
||||
}
|
||||
|
||||
let comment = if is_doccomment {
|
||||
DocComment { span }.into()
|
||||
} else {
|
||||
|
|
|
|||
19
src/lib.rs
19
src/lib.rs
|
|
@ -1,6 +1,6 @@
|
|||
//! The `ShulkerScript` language.
|
||||
//! The `Shulkerscript` language.
|
||||
//!
|
||||
//! `ShulkerScript` is a simple, imperative scripting language for creating Minecraft data packs.
|
||||
//! `Shulkerscript` is a simple, imperative scripting language for creating Minecraft data packs.
|
||||
|
||||
#![deny(
|
||||
missing_debug_implementations,
|
||||
|
|
@ -29,6 +29,11 @@ use shulkerbox::{datapack::Datapack, virtual_fs::VFolder};
|
|||
|
||||
use crate::lexical::token_stream::TokenStream;
|
||||
|
||||
/// The version of the `Shulkerscript` language.
|
||||
///
|
||||
/// Matches the version of this [`crate`].
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// Converts the given source code to tokens and returns a token stream.
|
||||
///
|
||||
/// # Errors
|
||||
|
|
@ -78,7 +83,7 @@ pub fn parse(
|
|||
let tokens = tokenize(handler, file_provider, path, identifier)?;
|
||||
|
||||
if handler.has_received() {
|
||||
return Err(Error::Other(
|
||||
return Err(Error::other(
|
||||
"An error occurred while tokenizing the source code.",
|
||||
));
|
||||
}
|
||||
|
|
@ -86,12 +91,10 @@ pub fn parse(
|
|||
tracing::info!("Parsing the source code at path: {}", path.display());
|
||||
|
||||
let mut parser = Parser::new(&tokens);
|
||||
let program = parser.parse_program(handler).ok_or(Error::Other(
|
||||
"An error occurred while parsing the source code.",
|
||||
))?;
|
||||
let program = parser.parse_program(handler)?;
|
||||
|
||||
if handler.has_received() {
|
||||
return Err(Error::Other(
|
||||
return Err(Error::other(
|
||||
"An error occurred while parsing the source code.",
|
||||
));
|
||||
}
|
||||
|
|
@ -165,7 +168,7 @@ where
|
|||
let datapack = transpiler.into_datapack();
|
||||
|
||||
if handler.has_received() {
|
||||
return Err(Error::Other(
|
||||
return Err(Error::other(
|
||||
"An error occurred while transpiling the source code.",
|
||||
));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,14 +3,31 @@
|
|||
use std::fmt::Display;
|
||||
|
||||
use crate::{
|
||||
base::log::{Message, Severity, SourceCodeDisplay},
|
||||
base::{
|
||||
log::{Message, Severity, SourceCodeDisplay},
|
||||
source_file::Span,
|
||||
},
|
||||
lexical::token::{KeywordKind, Token},
|
||||
};
|
||||
|
||||
/// Result type for parsing operations.
|
||||
pub type ParseResult<T> = Result<T, Error>;
|
||||
|
||||
/// An enumeration containing all kinds of syntactic errors that can occur while parsing the
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, thiserror::Error)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
UnexpectedSyntax(#[from] UnexpectedSyntax),
|
||||
#[error(transparent)]
|
||||
InvalidArgument(#[from] InvalidArgument),
|
||||
}
|
||||
|
||||
/// Enumeration containing all kinds of syntax that can be failed to parse.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum SyntaxKind {
|
||||
Either(&'static [SyntaxKind]),
|
||||
Punctuation(char),
|
||||
Keyword(KeywordKind),
|
||||
Identifier,
|
||||
|
|
@ -24,6 +41,43 @@ pub enum SyntaxKind {
|
|||
ExecuteBlockTail,
|
||||
}
|
||||
|
||||
impl SyntaxKind {
|
||||
fn expected_binding_str(&self) -> String {
|
||||
match self {
|
||||
Self::Either(variants) => {
|
||||
if variants.is_empty() {
|
||||
"end of file".to_string()
|
||||
} else if variants.len() == 1 {
|
||||
variants[0].expected_binding_str()
|
||||
} else {
|
||||
let comma_range = ..variants.len() - 2;
|
||||
let comma_elements = variants[comma_range]
|
||||
.iter()
|
||||
.map(Self::expected_binding_str)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!(
|
||||
"{}, or {}",
|
||||
comma_elements,
|
||||
variants.last().unwrap().expected_binding_str()
|
||||
)
|
||||
}
|
||||
}
|
||||
Self::Identifier => "an identifier token".to_string(),
|
||||
Self::Punctuation(char) => format!("a punctuation token `{char}`"),
|
||||
Self::Keyword(keyword) => format!("a keyword token `{}`", keyword.as_str()),
|
||||
Self::Declaration => "a declaration token".to_string(),
|
||||
Self::Numeric => "a numeric token".to_string(),
|
||||
Self::StringLiteral => "a string literal".to_string(),
|
||||
Self::Statement => "a statement syntax".to_string(),
|
||||
Self::Expression => "an expression syntax".to_string(),
|
||||
Self::Type => "a type syntax".to_string(),
|
||||
Self::ExecuteBlock => "an execute block syntax".to_string(),
|
||||
Self::ExecuteBlockTail => "an execute block tail syntax".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A syntax/token is expected but found an other invalid token.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct UnexpectedSyntax {
|
||||
|
|
@ -36,19 +90,7 @@ pub struct UnexpectedSyntax {
|
|||
|
||||
impl Display for UnexpectedSyntax {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let expected_binding = match self.expected {
|
||||
SyntaxKind::Identifier => "an identifier token".to_string(),
|
||||
SyntaxKind::Punctuation(char) => format!("a punctuation token `{char}`"),
|
||||
SyntaxKind::Keyword(keyword) => format!("a keyword token `{}`", keyword.as_str()),
|
||||
SyntaxKind::Declaration => "a declaration token".to_string(),
|
||||
SyntaxKind::Numeric => "a numeric token".to_string(),
|
||||
SyntaxKind::StringLiteral => "a string literal".to_string(),
|
||||
SyntaxKind::Statement => "a statement syntax".to_string(),
|
||||
SyntaxKind::Expression => "an expression syntax".to_string(),
|
||||
SyntaxKind::Type => "a type syntax".to_string(),
|
||||
SyntaxKind::ExecuteBlock => "an execute block syntax".to_string(),
|
||||
SyntaxKind::ExecuteBlockTail => "an execute block tail syntax".to_string(),
|
||||
};
|
||||
let expected_binding = self.expected.expected_binding_str();
|
||||
let found_binding = match self.found.clone() {
|
||||
Some(Token::Comment(..)) => "a comment token".to_string(),
|
||||
Some(Token::DocComment(..)) => "a doc comment token".to_string(),
|
||||
|
|
@ -83,10 +125,24 @@ impl Display for UnexpectedSyntax {
|
|||
|
||||
impl std::error::Error for UnexpectedSyntax {}
|
||||
|
||||
/// An enumeration containing all kinds of syntactic errors that can occur while parsing the
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, thiserror::Error)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
UnexpectedSyntax(#[from] UnexpectedSyntax),
|
||||
/// An error that occurred due to an invalid argument.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct InvalidArgument {
|
||||
/// The error message.
|
||||
pub message: String,
|
||||
/// The span of the invalid argument.
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl Display for InvalidArgument {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", Message::new(Severity::Error, &self.message))?;
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.span, Option::<u8>::None)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidArgument {}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! This module contains the syntax tree and parser for the `ShulkerScript` language.
|
||||
//! This module contains the syntax tree and parser for the `Shulkerscript` language.
|
||||
|
||||
pub mod error;
|
||||
pub mod parser;
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ use crate::{
|
|||
},
|
||||
};
|
||||
|
||||
use super::error::{Error, SyntaxKind, UnexpectedSyntax};
|
||||
use super::error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax};
|
||||
|
||||
/// Represents a parser that reads a token stream and constructs an abstract syntax tree.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deref, DerefMut)]
|
||||
|
|
@ -38,12 +38,15 @@ impl<'a> Parser<'a> {
|
|||
/// Steps into the [`Delimited`] token stream and parses the content within the delimiters.
|
||||
///
|
||||
/// The parser's position must be at the delimited token stream.
|
||||
///
|
||||
/// # Errors
|
||||
/// - If the parser's position is not at the delimited token stream.
|
||||
pub fn step_into<T>(
|
||||
&mut self,
|
||||
delimiter: Delimiter,
|
||||
f: impl FnOnce(&mut Self) -> Option<T>,
|
||||
f: impl FnOnce(&mut Self) -> ParseResult<T>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Option<DelimitedTree<T>> {
|
||||
) -> ParseResult<DelimitedTree<T>> {
|
||||
self.current_frame.stop_at_significant();
|
||||
let raw_token_tree = self
|
||||
.current_frame
|
||||
|
|
@ -62,7 +65,7 @@ impl<'a> Parser<'a> {
|
|||
delimited_tree
|
||||
}
|
||||
found => {
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Punctuation(expected),
|
||||
found: Some(match found {
|
||||
TokenTree::Token(token) => token.clone(),
|
||||
|
|
@ -70,18 +73,20 @@ impl<'a> Parser<'a> {
|
|||
Token::Punctuation(delimited_tree.open.clone())
|
||||
}
|
||||
}),
|
||||
}));
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
|
||||
return None;
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Punctuation(expected),
|
||||
found: self.get_reading(None).into_token(),
|
||||
}));
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
|
||||
return None;
|
||||
return Err(err);
|
||||
};
|
||||
|
||||
// creates a new frame
|
||||
|
|
@ -99,7 +104,10 @@ impl<'a> Parser<'a> {
|
|||
let tree = f(self);
|
||||
|
||||
// pops the current frame off the stack
|
||||
let new_frame = self.stack.pop()?;
|
||||
let new_frame = self
|
||||
.stack
|
||||
.pop()
|
||||
.expect("frame has been pushed on the stack before");
|
||||
|
||||
// the current frame must be at the end
|
||||
if !self.current_frame.is_exhausted() {
|
||||
|
|
@ -111,10 +119,12 @@ impl<'a> Parser<'a> {
|
|||
.delimiter
|
||||
.closing_char();
|
||||
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Punctuation(expected),
|
||||
found: self.peek().into_token(),
|
||||
}));
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let close_punctuation = self
|
||||
|
|
@ -128,7 +138,7 @@ impl<'a> Parser<'a> {
|
|||
// replaces the current frame with the popped one
|
||||
self.current_frame = new_frame;
|
||||
|
||||
Some(DelimitedTree {
|
||||
Ok(DelimitedTree {
|
||||
open,
|
||||
tree,
|
||||
close: close_punctuation,
|
||||
|
|
@ -137,12 +147,15 @@ impl<'a> Parser<'a> {
|
|||
|
||||
/// Tries to parse the given function, and if it fails, resets the current index to the
|
||||
/// `current_index` before the function call.
|
||||
pub fn try_parse<T>(&mut self, f: impl FnOnce(&mut Self) -> Option<T>) -> Option<T> {
|
||||
///
|
||||
/// # Errors
|
||||
/// - If the given function returns an error.
|
||||
pub fn try_parse<T>(&mut self, f: impl FnOnce(&mut Self) -> ParseResult<T>) -> ParseResult<T> {
|
||||
let current_index = self.current_frame.current_index;
|
||||
|
||||
let result = f(self);
|
||||
|
||||
if result.is_none() {
|
||||
if result.is_err() {
|
||||
self.current_frame.current_index = current_index;
|
||||
}
|
||||
|
||||
|
|
@ -157,7 +170,7 @@ pub struct DelimitedTree<T> {
|
|||
pub open: Punctuation,
|
||||
|
||||
/// The tree inside the delimiter.
|
||||
pub tree: Option<T>,
|
||||
pub tree: ParseResult<T>,
|
||||
|
||||
/// The closing delimiter.
|
||||
pub close: Punctuation,
|
||||
|
|
@ -363,15 +376,19 @@ impl<'a> Frame<'a> {
|
|||
///
|
||||
/// # Errors
|
||||
/// If the next [`Token`] is not an [`Identifier`].
|
||||
pub fn parse_identifier(&mut self, handler: &impl Handler<base::Error>) -> Option<Identifier> {
|
||||
pub fn parse_identifier(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> ParseResult<Identifier> {
|
||||
match self.next_significant_token() {
|
||||
Reading::Atomic(Token::Identifier(ident)) => Some(ident),
|
||||
Reading::Atomic(Token::Identifier(ident)) => Ok(ident),
|
||||
found => {
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Identifier,
|
||||
found: found.into_token(),
|
||||
}));
|
||||
None
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -380,15 +397,16 @@ impl<'a> Frame<'a> {
|
|||
///
|
||||
/// # Errors
|
||||
/// If the next [`Token`] is not an [`Identifier`].
|
||||
pub fn parse_numeric(&mut self, handler: &impl Handler<Error>) -> Option<Numeric> {
|
||||
pub fn parse_numeric(&mut self, handler: &impl Handler<Error>) -> ParseResult<Numeric> {
|
||||
match self.next_significant_token() {
|
||||
Reading::Atomic(Token::Numeric(ident)) => Some(ident),
|
||||
Reading::Atomic(Token::Numeric(ident)) => Ok(ident),
|
||||
found => {
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Numeric,
|
||||
found: found.into_token(),
|
||||
}));
|
||||
None
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -400,15 +418,16 @@ impl<'a> Frame<'a> {
|
|||
pub fn parse_string_literal(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Option<StringLiteral> {
|
||||
) -> ParseResult<StringLiteral> {
|
||||
match self.next_significant_token() {
|
||||
Reading::Atomic(Token::StringLiteral(literal)) => Some(literal),
|
||||
Reading::Atomic(Token::StringLiteral(literal)) => Ok(literal),
|
||||
found => {
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::StringLiteral,
|
||||
found: found.into_token(),
|
||||
}));
|
||||
None
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -421,17 +440,18 @@ impl<'a> Frame<'a> {
|
|||
&mut self,
|
||||
expected: KeywordKind,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Option<Keyword> {
|
||||
) -> ParseResult<Keyword> {
|
||||
match self.next_significant_token() {
|
||||
Reading::Atomic(Token::Keyword(keyword_token)) if keyword_token.keyword == expected => {
|
||||
Some(keyword_token)
|
||||
Ok(keyword_token)
|
||||
}
|
||||
found => {
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Keyword(expected),
|
||||
found: found.into_token(),
|
||||
}));
|
||||
None
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -445,7 +465,7 @@ impl<'a> Frame<'a> {
|
|||
expected: char,
|
||||
skip_insignificant: bool,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Option<Punctuation> {
|
||||
) -> ParseResult<Punctuation> {
|
||||
match if skip_insignificant {
|
||||
self.next_significant_token()
|
||||
} else {
|
||||
|
|
@ -454,14 +474,15 @@ impl<'a> Frame<'a> {
|
|||
Reading::Atomic(Token::Punctuation(punctuation_token))
|
||||
if punctuation_token.punctuation == expected =>
|
||||
{
|
||||
Some(punctuation_token)
|
||||
Ok(punctuation_token)
|
||||
}
|
||||
found => {
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Punctuation(expected),
|
||||
found: found.into_token(),
|
||||
}));
|
||||
None
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
//! Syntax tree nodes for conditions.
|
||||
|
||||
#![allow(clippy::missing_errors_doc)]
|
||||
|
||||
use std::{cmp::Ordering, collections::VecDeque};
|
||||
|
||||
use enum_as_inner::EnumAsInner;
|
||||
|
|
@ -9,23 +11,25 @@ use crate::{
|
|||
base::{
|
||||
self,
|
||||
source_file::{SourceElement, Span},
|
||||
VoidHandler, Handler,
|
||||
Handler, VoidHandler,
|
||||
},
|
||||
lexical::{
|
||||
token::{Punctuation, StringLiteral, Token},
|
||||
token_stream::Delimiter,
|
||||
},
|
||||
syntax::{
|
||||
error::{Error, SyntaxKind, UnexpectedSyntax},
|
||||
error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax},
|
||||
parser::{Parser, Reading},
|
||||
},
|
||||
};
|
||||
|
||||
/// Condition that is viewed as a single entity during precedence parsing.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
/// PrimaryCondition:
|
||||
/// ConditionalPrefix
|
||||
/// UnaryCondition
|
||||
/// | ParenthesizedCondition
|
||||
/// | StringLiteral
|
||||
/// ```
|
||||
|
|
@ -33,7 +37,7 @@ use crate::{
|
|||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, EnumAsInner)]
|
||||
pub enum PrimaryCondition {
|
||||
Prefix(ConditionalPrefix),
|
||||
Unary(UnaryCondition),
|
||||
Parenthesized(ParenthesizedCondition),
|
||||
StringLiteral(StringLiteral),
|
||||
}
|
||||
|
|
@ -41,13 +45,15 @@ pub enum PrimaryCondition {
|
|||
impl SourceElement for PrimaryCondition {
|
||||
fn span(&self) -> Span {
|
||||
match self {
|
||||
Self::Prefix(prefix) => prefix.span(),
|
||||
Self::Unary(unary) => unary.span(),
|
||||
Self::Parenthesized(parenthesized) => parenthesized.span(),
|
||||
Self::StringLiteral(literal) => literal.span(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Condition that is composed of two conditions and a binary operator.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -86,6 +92,8 @@ impl BinaryCondition {
|
|||
}
|
||||
}
|
||||
|
||||
/// Operator that is used to combine two conditions.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -126,6 +134,8 @@ impl SourceElement for ConditionalBinaryOperator {
|
|||
}
|
||||
}
|
||||
|
||||
/// Condition that is enclosed in parentheses.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -163,6 +173,8 @@ impl SourceElement for ParenthesizedCondition {
|
|||
}
|
||||
}
|
||||
|
||||
/// Operator that is used to prefix a condition.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -183,16 +195,18 @@ impl SourceElement for ConditionalPrefixOperator {
|
|||
}
|
||||
}
|
||||
|
||||
/// Condition that is prefixed by an operator.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ```ebnf
|
||||
/// ConditionalPrefix:
|
||||
/// UnaryCondition:
|
||||
/// ConditionalPrefixOperator PrimaryCondition
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
|
||||
pub struct ConditionalPrefix {
|
||||
pub struct UnaryCondition {
|
||||
/// The operator of the prefix.
|
||||
#[get = "pub"]
|
||||
operator: ConditionalPrefixOperator,
|
||||
|
|
@ -201,12 +215,12 @@ pub struct ConditionalPrefix {
|
|||
operand: Box<PrimaryCondition>,
|
||||
}
|
||||
|
||||
impl SourceElement for ConditionalPrefix {
|
||||
impl SourceElement for UnaryCondition {
|
||||
fn span(&self) -> Span {
|
||||
self.operator.span().join(&self.operand.span()).unwrap()
|
||||
}
|
||||
}
|
||||
impl ConditionalPrefix {
|
||||
impl UnaryCondition {
|
||||
/// Dissolves the conditional prefix into its components
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (ConditionalPrefixOperator, PrimaryCondition) {
|
||||
|
|
@ -214,6 +228,8 @@ impl ConditionalPrefix {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a condition in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -241,12 +257,20 @@ impl SourceElement for Condition {
|
|||
|
||||
impl<'a> Parser<'a> {
|
||||
/// Parses a [`Condition`].
|
||||
pub fn parse_condition(&mut self, handler: &impl Handler<base::Error>) -> Option<Condition> {
|
||||
///
|
||||
/// # Precedence of the operators
|
||||
/// 1. `!`
|
||||
/// 2. `&&`
|
||||
/// 3. `||`
|
||||
pub fn parse_condition(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> ParseResult<Condition> {
|
||||
let mut lhs = Condition::Primary(self.parse_primary_condition(handler)?);
|
||||
let mut expressions = VecDeque::new();
|
||||
|
||||
// Parses a list of binary operators and expressions
|
||||
while let Some(binary_operator) = self.try_parse_conditional_binary_operator() {
|
||||
while let Ok(binary_operator) = self.try_parse_conditional_binary_operator() {
|
||||
expressions.push_back((
|
||||
binary_operator,
|
||||
Some(Condition::Primary(self.parse_primary_condition(handler)?)),
|
||||
|
|
@ -300,14 +324,14 @@ impl<'a> Parser<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
Some(lhs)
|
||||
Ok(lhs)
|
||||
}
|
||||
|
||||
/// Parses a [`PrimaryCondition`].
|
||||
pub fn parse_primary_condition(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Option<PrimaryCondition> {
|
||||
) -> ParseResult<PrimaryCondition> {
|
||||
match self.stop_at_significant() {
|
||||
// prefixed expression
|
||||
Reading::Atomic(Token::Punctuation(punc)) if punc.punctuation == '!' => {
|
||||
|
|
@ -321,7 +345,7 @@ impl<'a> Parser<'a> {
|
|||
|
||||
let operand = Box::new(self.parse_primary_condition(handler)?);
|
||||
|
||||
Some(PrimaryCondition::Prefix(ConditionalPrefix {
|
||||
Ok(PrimaryCondition::Unary(UnaryCondition {
|
||||
operator,
|
||||
operand,
|
||||
}))
|
||||
|
|
@ -330,7 +354,7 @@ impl<'a> Parser<'a> {
|
|||
// string literal
|
||||
Reading::Atomic(Token::StringLiteral(literal)) => {
|
||||
self.forward();
|
||||
Some(PrimaryCondition::StringLiteral(literal))
|
||||
Ok(PrimaryCondition::StringLiteral(literal))
|
||||
}
|
||||
|
||||
// parenthesized condition
|
||||
|
|
@ -342,12 +366,17 @@ impl<'a> Parser<'a> {
|
|||
// make progress
|
||||
self.forward();
|
||||
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Expression,
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Either(&[
|
||||
SyntaxKind::Punctuation('!'),
|
||||
SyntaxKind::StringLiteral,
|
||||
SyntaxKind::Punctuation('('),
|
||||
]),
|
||||
found: unexpected.into_token(),
|
||||
}));
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
|
||||
None
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -356,38 +385,59 @@ impl<'a> Parser<'a> {
|
|||
pub fn parse_parenthesized_condition(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Option<ParenthesizedCondition> {
|
||||
) -> ParseResult<ParenthesizedCondition> {
|
||||
let token_tree = self.step_into(
|
||||
Delimiter::Parenthesis,
|
||||
|parser| {
|
||||
let cond = parser.parse_condition(handler)?;
|
||||
parser.stop_at_significant();
|
||||
Some(cond)
|
||||
Ok(cond)
|
||||
},
|
||||
handler,
|
||||
)?;
|
||||
|
||||
Some(ParenthesizedCondition {
|
||||
Ok(ParenthesizedCondition {
|
||||
open_paren: token_tree.open,
|
||||
condition: Box::new(token_tree.tree?),
|
||||
close_paren: token_tree.close,
|
||||
})
|
||||
}
|
||||
|
||||
fn try_parse_conditional_binary_operator(&mut self) -> Option<ConditionalBinaryOperator> {
|
||||
fn try_parse_conditional_binary_operator(&mut self) -> ParseResult<ConditionalBinaryOperator> {
|
||||
self.try_parse(|parser| match parser.next_significant_token() {
|
||||
Reading::Atomic(Token::Punctuation(punc)) => match punc.punctuation {
|
||||
Reading::Atomic(token) => match token.clone() {
|
||||
Token::Punctuation(punc) => match punc.punctuation {
|
||||
'&' => {
|
||||
let b = parser.parse_punctuation('&', false, &VoidHandler)?;
|
||||
Some(ConditionalBinaryOperator::LogicalAnd(punc, b))
|
||||
Ok(ConditionalBinaryOperator::LogicalAnd(punc, b))
|
||||
}
|
||||
'|' => {
|
||||
let b = parser.parse_punctuation('|', false, &VoidHandler)?;
|
||||
Some(ConditionalBinaryOperator::LogicalOr(punc, b))
|
||||
Ok(ConditionalBinaryOperator::LogicalOr(punc, b))
|
||||
}
|
||||
_ => None,
|
||||
_ => Err(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Either(&[
|
||||
SyntaxKind::Punctuation('&'),
|
||||
SyntaxKind::Punctuation('|'),
|
||||
]),
|
||||
found: Some(token),
|
||||
})),
|
||||
},
|
||||
_ => None,
|
||||
unexpected => Err(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Either(&[
|
||||
SyntaxKind::Punctuation('&'),
|
||||
SyntaxKind::Punctuation('|'),
|
||||
]),
|
||||
found: Some(unexpected),
|
||||
})),
|
||||
},
|
||||
unexpected => Err(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Either(&[
|
||||
SyntaxKind::Punctuation('&'),
|
||||
SyntaxKind::Punctuation('|'),
|
||||
]),
|
||||
found: unexpected.into_token(),
|
||||
})),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,13 +15,15 @@ use crate::{
|
|||
token_stream::Delimiter,
|
||||
},
|
||||
syntax::{
|
||||
error::{Error, SyntaxKind, UnexpectedSyntax},
|
||||
error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax},
|
||||
parser::{Parser, Reading},
|
||||
},
|
||||
};
|
||||
|
||||
use super::{statement::Block, ConnectedList};
|
||||
use super::{statement::Block, ConnectedList, DelimitedList};
|
||||
|
||||
/// Represents a declaration in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -35,6 +37,7 @@ use super::{statement::Block, ConnectedList};
|
|||
pub enum Declaration {
|
||||
Function(Function),
|
||||
Import(Import),
|
||||
Tag(Tag),
|
||||
}
|
||||
|
||||
impl SourceElement for Declaration {
|
||||
|
|
@ -42,9 +45,12 @@ impl SourceElement for Declaration {
|
|||
match self {
|
||||
Self::Function(function) => function.span(),
|
||||
Self::Import(import) => import.span(),
|
||||
Self::Tag(tag) => tag.span(),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Represents an Annotation with optional value.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -97,6 +103,8 @@ impl SourceElement for Annotation {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a function declaration in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -174,6 +182,8 @@ impl SourceElement for Function {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an import declaration in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -196,6 +206,7 @@ pub struct Import {
|
|||
semicolon: Punctuation,
|
||||
}
|
||||
|
||||
/// Items to import.
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum ImportItems {
|
||||
|
|
@ -226,8 +237,91 @@ impl SourceElement for Import {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a tag declaration in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
/// TagDeclaration:
|
||||
/// 'tag' StringLiteral ('of' StringLiteral)? 'replace'? '[' (StringLiteral (',' StringLiteral)*)? ']'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
|
||||
pub struct Tag {
|
||||
#[get = "pub"]
|
||||
tag_keyword: Keyword,
|
||||
#[get = "pub"]
|
||||
name: StringLiteral,
|
||||
#[get = "pub"]
|
||||
of_type: Option<(Keyword, StringLiteral)>,
|
||||
#[get = "pub"]
|
||||
replace: Option<Keyword>,
|
||||
#[get = "pub"]
|
||||
entries: DelimitedList<StringLiteral>,
|
||||
}
|
||||
|
||||
impl Tag {
|
||||
#[must_use]
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn dissolve(
|
||||
self,
|
||||
) -> (
|
||||
Keyword,
|
||||
StringLiteral,
|
||||
Option<(Keyword, StringLiteral)>,
|
||||
Option<Keyword>,
|
||||
DelimitedList<StringLiteral>,
|
||||
) {
|
||||
(
|
||||
self.tag_keyword,
|
||||
self.name,
|
||||
self.of_type,
|
||||
self.replace,
|
||||
self.entries,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "shulkerbox")]
|
||||
#[must_use]
|
||||
pub fn tag_type(&self) -> shulkerbox::datapack::tag::TagType {
|
||||
use shulkerbox::datapack::tag::TagType;
|
||||
|
||||
self.of_type
|
||||
.as_ref()
|
||||
.map_or(TagType::Function, |(_, tag_type)| {
|
||||
match tag_type.str_content().as_ref() {
|
||||
"function" => TagType::Function,
|
||||
"block" => TagType::Block,
|
||||
"entity_type" => TagType::Entity,
|
||||
"fluid" => TagType::Fluid,
|
||||
"game_event" => TagType::GameEvent,
|
||||
"item" => TagType::Item,
|
||||
other => TagType::Other(other.to_string()),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl SourceElement for Tag {
|
||||
fn span(&self) -> Span {
|
||||
self.tag_keyword
|
||||
.span()
|
||||
.join(&self.entries.close.span)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
pub fn parse_annotation(&mut self, handler: &impl Handler<base::Error>) -> Option<Annotation> {
|
||||
/// Parses an annotation.
|
||||
///
|
||||
/// # Errors
|
||||
/// - if the parser position is not at an annotation.
|
||||
/// - if the parsing of the annotation fails
|
||||
pub fn parse_annotation(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> ParseResult<Annotation> {
|
||||
match self.stop_at_significant() {
|
||||
Reading::Atomic(Token::Punctuation(punctuation)) if punctuation.punctuation == '#' => {
|
||||
// eat the pound sign
|
||||
|
|
@ -239,36 +333,29 @@ impl<'a> Parser<'a> {
|
|||
|parser| {
|
||||
let identifier = parser.parse_identifier(handler)?;
|
||||
|
||||
let value = if let Reading::Atomic(Token::Punctuation(punctuation)) =
|
||||
parser.stop_at_significant()
|
||||
let value = match parser.stop_at_significant() {
|
||||
Reading::Atomic(Token::Punctuation(punc))
|
||||
if punc.punctuation == '=' =>
|
||||
{
|
||||
if punctuation.punctuation == '=' {
|
||||
// eat the equals sign
|
||||
parser.forward();
|
||||
|
||||
// parse the string literal
|
||||
let string_literal = parser
|
||||
.next_significant_token()
|
||||
.into_token()?
|
||||
.into_string_literal()
|
||||
.ok()?;
|
||||
let string_literal = parser.parse_string_literal(handler)?;
|
||||
|
||||
Some((punctuation, string_literal))
|
||||
} else {
|
||||
None
|
||||
Some((punc, string_literal))
|
||||
}
|
||||
} else {
|
||||
None
|
||||
_ => None,
|
||||
};
|
||||
|
||||
Some((identifier, value))
|
||||
Ok((identifier, value))
|
||||
},
|
||||
handler,
|
||||
)?;
|
||||
|
||||
let (identifier, value) = content.tree?;
|
||||
|
||||
Some(Annotation {
|
||||
Ok(Annotation {
|
||||
pound_sign: punctuation,
|
||||
open_bracket: content.open,
|
||||
identifier,
|
||||
|
|
@ -276,7 +363,14 @@ impl<'a> Parser<'a> {
|
|||
close_bracket: content.close,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
unexpected => {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Punctuation('#'),
|
||||
found: unexpected.into_token(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -284,7 +378,7 @@ impl<'a> Parser<'a> {
|
|||
pub fn parse_declaration(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Option<Declaration> {
|
||||
) -> ParseResult<Declaration> {
|
||||
match self.stop_at_significant() {
|
||||
Reading::Atomic(Token::Keyword(function_keyword))
|
||||
if function_keyword.keyword == KeywordKind::Function =>
|
||||
|
|
@ -293,22 +387,17 @@ impl<'a> Parser<'a> {
|
|||
|
||||
tracing::trace!("Parsed function '{:?}'", function.identifier.span.str());
|
||||
|
||||
Some(Declaration::Function(function))
|
||||
Ok(Declaration::Function(function))
|
||||
}
|
||||
|
||||
Reading::Atomic(Token::Keyword(pub_keyword))
|
||||
if pub_keyword.keyword == KeywordKind::Pub =>
|
||||
{
|
||||
// eat the public keyword
|
||||
self.forward();
|
||||
|
||||
// parse the function keyword
|
||||
let function = self.parse_function(handler)?;
|
||||
|
||||
Some(Declaration::Function(Function {
|
||||
public_keyword: Some(pub_keyword),
|
||||
..function
|
||||
}))
|
||||
tracing::trace!("Parsed function '{:?}'", function.identifier.span.str());
|
||||
|
||||
Ok(Declaration::Function(function))
|
||||
}
|
||||
|
||||
// parse annotations
|
||||
|
|
@ -316,23 +405,15 @@ impl<'a> Parser<'a> {
|
|||
// parse the annotation
|
||||
let mut annotations = Vec::new();
|
||||
|
||||
while let Some(annotation) =
|
||||
self.try_parse(|parser| parser.parse_annotation(handler))
|
||||
while let Ok(annotation) =
|
||||
self.try_parse(|parser| parser.parse_annotation(&VoidHandler))
|
||||
{
|
||||
annotations.push(annotation);
|
||||
}
|
||||
|
||||
self.parse_declaration(handler).and_then(|declaration| {
|
||||
if let Declaration::Function(mut function) = declaration {
|
||||
self.parse_function(handler).map(|mut function| {
|
||||
function.annotations.extend(annotations);
|
||||
Some(Declaration::Function(function))
|
||||
} else {
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Keyword(KeywordKind::Function),
|
||||
found: None,
|
||||
}));
|
||||
None
|
||||
}
|
||||
Declaration::Function(function)
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -366,12 +447,12 @@ impl<'a> Parser<'a> {
|
|||
// }
|
||||
;
|
||||
|
||||
if let Some(items) = items {
|
||||
if let Ok(items) = items {
|
||||
let semicolon = self.parse_punctuation(';', true, handler)?;
|
||||
|
||||
tracing::trace!("Parsed import from '{:?}'", module.str_content());
|
||||
|
||||
Some(Declaration::Import(Import {
|
||||
Ok(Declaration::Import(Import {
|
||||
from_keyword,
|
||||
module,
|
||||
import_keyword,
|
||||
|
|
@ -379,31 +460,82 @@ impl<'a> Parser<'a> {
|
|||
semicolon,
|
||||
}))
|
||||
} else {
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Identifier,
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Punctuation('*'),
|
||||
found: self.stop_at_significant().into_token(),
|
||||
}));
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
|
||||
None
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
Reading::Atomic(Token::Keyword(tag_keyword))
|
||||
if tag_keyword.keyword == KeywordKind::Tag =>
|
||||
{
|
||||
// eat the tag keyword
|
||||
self.forward();
|
||||
|
||||
// parse the name
|
||||
let name = self.parse_string_literal(handler)?;
|
||||
|
||||
let of_type = self
|
||||
.try_parse(|parser| {
|
||||
let of_keyword = parser.parse_keyword(KeywordKind::Of, &VoidHandler)?;
|
||||
let of_type = parser.parse_string_literal(handler)?;
|
||||
|
||||
Ok((of_keyword, of_type))
|
||||
})
|
||||
.ok();
|
||||
|
||||
let replace = self
|
||||
.try_parse(|parser| parser.parse_keyword(KeywordKind::Replace, &VoidHandler))
|
||||
.ok();
|
||||
|
||||
let entries = self.parse_enclosed_list(
|
||||
Delimiter::Bracket,
|
||||
',',
|
||||
|parser| parser.parse_string_literal(handler),
|
||||
handler,
|
||||
)?;
|
||||
|
||||
Ok(Declaration::Tag(Tag {
|
||||
tag_keyword,
|
||||
name,
|
||||
of_type,
|
||||
replace,
|
||||
entries,
|
||||
}))
|
||||
}
|
||||
|
||||
unexpected => {
|
||||
// make progress
|
||||
self.forward();
|
||||
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Declaration,
|
||||
found: unexpected.into_token(),
|
||||
}));
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
|
||||
None
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_function(&mut self, handler: &impl Handler<base::Error>) -> Option<Function> {
|
||||
if let Reading::Atomic(Token::Keyword(function_keyword)) = self.stop_at_significant() {
|
||||
/// Parses a function.
|
||||
///
|
||||
/// # Errors
|
||||
/// - if the parser is not at a function (not at annotation).
|
||||
/// - if the parsing of the function fails.
|
||||
pub fn parse_function(&mut self, handler: &impl Handler<base::Error>) -> ParseResult<Function> {
|
||||
let pub_keyword =
|
||||
self.try_parse(|parser| parser.parse_keyword(KeywordKind::Pub, &VoidHandler));
|
||||
|
||||
match self.stop_at_significant() {
|
||||
Reading::Atomic(Token::Keyword(function_keyword))
|
||||
if function_keyword.keyword == KeywordKind::Function =>
|
||||
{
|
||||
// eat the function keyword
|
||||
self.forward();
|
||||
|
||||
|
|
@ -419,8 +551,8 @@ impl<'a> Parser<'a> {
|
|||
// parse the block
|
||||
let block = self.parse_block(handler)?;
|
||||
|
||||
Some(Function {
|
||||
public_keyword: None,
|
||||
Ok(Function {
|
||||
public_keyword: pub_keyword.ok(),
|
||||
annotations: Vec::new(),
|
||||
function_keyword,
|
||||
identifier,
|
||||
|
|
@ -429,12 +561,15 @@ impl<'a> Parser<'a> {
|
|||
close_paren: delimited_tree.close,
|
||||
block,
|
||||
})
|
||||
} else {
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
}
|
||||
unexpected => {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Keyword(KeywordKind::Function),
|
||||
found: self.peek().into_token(),
|
||||
}));
|
||||
None
|
||||
found: unexpected.into_token(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,13 +14,16 @@ use crate::{
|
|||
token_stream::Delimiter,
|
||||
},
|
||||
syntax::{
|
||||
error::{Error, UnexpectedSyntax},
|
||||
self,
|
||||
error::{Error, ParseResult, UnexpectedSyntax},
|
||||
parser::{Parser, Reading},
|
||||
},
|
||||
};
|
||||
|
||||
use super::ConnectedList;
|
||||
|
||||
/// Represents an expression in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ```ebnf
|
||||
|
|
@ -42,6 +45,8 @@ impl SourceElement for Expression {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a primary expression in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -67,6 +72,8 @@ impl SourceElement for Primary {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a function call in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -100,6 +107,8 @@ impl SourceElement for FunctionCall {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a lua code block in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ```ebnf
|
||||
|
|
@ -156,12 +165,22 @@ impl LuaCode {
|
|||
|
||||
impl<'a> Parser<'a> {
|
||||
/// Parses an [`Expression`]
|
||||
pub fn parse_expression(&mut self, handler: &impl Handler<base::Error>) -> Option<Expression> {
|
||||
Some(Expression::Primary(self.parse_primary(handler)?))
|
||||
///
|
||||
/// # Errors
|
||||
/// - If the parser is not at a primary expression.
|
||||
pub fn parse_expression(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> ParseResult<Expression> {
|
||||
self.parse_primary(handler).map(Expression::Primary)
|
||||
}
|
||||
|
||||
/// Parses an [`Primary`]
|
||||
pub fn parse_primary(&mut self, handler: &impl Handler<base::Error>) -> Option<Primary> {
|
||||
///
|
||||
/// # Errors
|
||||
/// - If the parser is not at a primary expression.
|
||||
/// - If the parser is not at a valid primary expression.
|
||||
pub fn parse_primary(&mut self, handler: &impl Handler<base::Error>) -> ParseResult<Primary> {
|
||||
match self.stop_at_significant() {
|
||||
// identifier expression
|
||||
Reading::Atomic(Token::Identifier(identifier)) => {
|
||||
|
|
@ -169,8 +188,8 @@ impl<'a> Parser<'a> {
|
|||
self.forward();
|
||||
|
||||
// function call
|
||||
if matches!(self.stop_at_significant(), Reading::IntoDelimited(punc) if punc.punctuation == '(')
|
||||
{
|
||||
match self.stop_at_significant() {
|
||||
Reading::IntoDelimited(punc) if punc.punctuation == '(' => {
|
||||
let token_tree = self.parse_enclosed_list(
|
||||
Delimiter::Parenthesis,
|
||||
',',
|
||||
|
|
@ -178,15 +197,22 @@ impl<'a> Parser<'a> {
|
|||
handler,
|
||||
)?;
|
||||
|
||||
Some(Primary::FunctionCall(FunctionCall {
|
||||
Ok(Primary::FunctionCall(FunctionCall {
|
||||
identifier,
|
||||
left_parenthesis: token_tree.open,
|
||||
right_parenthesis: token_tree.close,
|
||||
arguments: token_tree.list,
|
||||
}))
|
||||
} else {
|
||||
}
|
||||
unexpected => {
|
||||
// insert parser for regular identifier here
|
||||
None
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: syntax::error::SyntaxKind::Punctuation('('),
|
||||
found: unexpected.into_token(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -195,7 +221,7 @@ impl<'a> Parser<'a> {
|
|||
// eat the string literal
|
||||
self.forward();
|
||||
|
||||
Some(Primary::StringLiteral(literal))
|
||||
Ok(Primary::StringLiteral(literal))
|
||||
}
|
||||
|
||||
// lua code expression
|
||||
|
|
@ -212,9 +238,16 @@ impl<'a> Parser<'a> {
|
|||
|parser| match parser.next_significant_token() {
|
||||
Reading::Atomic(Token::Identifier(identifier)) => {
|
||||
parser.forward();
|
||||
Some(identifier)
|
||||
Ok(identifier)
|
||||
}
|
||||
unexpected => {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: syntax::error::SyntaxKind::Identifier,
|
||||
found: unexpected.into_token(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
handler,
|
||||
)?;
|
||||
|
|
@ -241,12 +274,12 @@ impl<'a> Parser<'a> {
|
|||
})
|
||||
.expect("Invalid lua code span");
|
||||
|
||||
Some(combined.str().trim().to_owned())
|
||||
Ok(combined.str().trim().to_owned())
|
||||
},
|
||||
handler,
|
||||
)?;
|
||||
|
||||
Some(Primary::Lua(Box::new(LuaCode {
|
||||
Ok(Primary::Lua(Box::new(LuaCode {
|
||||
lua_keyword,
|
||||
left_parenthesis: variables.open,
|
||||
variables: variables.list,
|
||||
|
|
@ -261,12 +294,13 @@ impl<'a> Parser<'a> {
|
|||
// make progress
|
||||
self.forward();
|
||||
|
||||
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: crate::syntax::error::SyntaxKind::Expression,
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: syntax::error::SyntaxKind::Expression,
|
||||
found: unexpected.into_token(),
|
||||
}));
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
|
||||
None
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ use crate::{
|
|||
syntax::parser::Reading,
|
||||
};
|
||||
|
||||
use super::parser::Parser;
|
||||
use super::{error::ParseResult, parser::Parser};
|
||||
|
||||
pub mod condition;
|
||||
pub mod declaration;
|
||||
|
|
@ -49,6 +49,7 @@ pub struct ConnectedList<Element, Separator> {
|
|||
|
||||
/// Represents a syntax tree node with a pattern of having [`ConnectedList`] delimited by a pair of
|
||||
/// punctuation like such `(a, b, c)`.
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DelimitedList<T> {
|
||||
/// The open punctuation of the list.
|
||||
|
|
@ -76,9 +77,9 @@ impl<'a> Parser<'a> {
|
|||
&mut self,
|
||||
delimiter: Delimiter,
|
||||
separator: char,
|
||||
mut f: impl FnMut(&mut Self) -> Option<T>,
|
||||
mut f: impl FnMut(&mut Self) -> ParseResult<T>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Option<DelimitedList<T>> {
|
||||
) -> ParseResult<DelimitedList<T>> {
|
||||
fn skip_to_next_separator(this: &mut Parser, separator: char) -> Option<Punctuation> {
|
||||
if let Reading::Atomic(Token::Punctuation(punc)) = this.stop_at(|token| {
|
||||
matches!(
|
||||
|
|
@ -101,7 +102,7 @@ impl<'a> Parser<'a> {
|
|||
let mut trailing_separator: Option<Punctuation> = None;
|
||||
|
||||
while !parser.is_exhausted() {
|
||||
let Some(element) = f(parser) else {
|
||||
let Ok(element) = f(parser) else {
|
||||
skip_to_next_separator(parser, separator);
|
||||
continue;
|
||||
};
|
||||
|
|
@ -122,7 +123,7 @@ impl<'a> Parser<'a> {
|
|||
|
||||
// expect separator if not exhausted
|
||||
if !parser.is_exhausted() {
|
||||
let Some(separator) = parser.parse_punctuation(separator, true, handler)
|
||||
let Ok(separator) = parser.parse_punctuation(separator, true, handler)
|
||||
else {
|
||||
if let Some(punctuation) = skip_to_next_separator(parser, separator) {
|
||||
trailing_separator = Some(punctuation);
|
||||
|
|
@ -135,7 +136,7 @@ impl<'a> Parser<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
Some(first.map(|first| ConnectedList {
|
||||
Ok(first.map(|first| ConnectedList {
|
||||
first,
|
||||
rest,
|
||||
trailing_separator,
|
||||
|
|
@ -144,7 +145,7 @@ impl<'a> Parser<'a> {
|
|||
handler,
|
||||
)?;
|
||||
|
||||
Some(DelimitedList {
|
||||
Ok(DelimitedList {
|
||||
open: delimited_tree.open,
|
||||
list: delimited_tree.tree.unwrap(),
|
||||
close: delimited_tree.close,
|
||||
|
|
@ -162,20 +163,20 @@ impl<'a> Parser<'a> {
|
|||
pub fn parse_connected_list<T>(
|
||||
&mut self,
|
||||
seperator: char,
|
||||
mut f: impl FnMut(&mut Self) -> Option<T>,
|
||||
mut f: impl FnMut(&mut Self) -> ParseResult<T>,
|
||||
_handler: &impl Handler<base::Error>,
|
||||
) -> Option<ConnectedList<T, Punctuation>> {
|
||||
) -> ParseResult<ConnectedList<T, Punctuation>> {
|
||||
let first = f(self)?;
|
||||
|
||||
let mut rest = Vec::new();
|
||||
|
||||
while let Some(sep) =
|
||||
while let Ok(sep) =
|
||||
self.try_parse(|parser| parser.parse_punctuation(seperator, true, &VoidHandler))
|
||||
{
|
||||
if let Some(element) = self.try_parse(&mut f) {
|
||||
if let Ok(element) = self.try_parse(&mut f) {
|
||||
rest.push((sep, element));
|
||||
} else {
|
||||
return Some(ConnectedList {
|
||||
return Ok(ConnectedList {
|
||||
first,
|
||||
rest,
|
||||
trailing_separator: Some(sep),
|
||||
|
|
@ -183,7 +184,7 @@ impl<'a> Parser<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
Some(ConnectedList {
|
||||
Ok(ConnectedList {
|
||||
first,
|
||||
rest,
|
||||
trailing_separator: None,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
//! The program node of the syntax tree.
|
||||
|
||||
use getset::Getters;
|
||||
use itertools::Itertools;
|
||||
|
||||
use crate::{
|
||||
base::{
|
||||
|
|
@ -11,7 +12,7 @@ use crate::{
|
|||
lexical::token::{Keyword, KeywordKind, Punctuation, StringLiteral, Token},
|
||||
syntax::{
|
||||
self,
|
||||
error::{SyntaxKind, UnexpectedSyntax},
|
||||
error::{InvalidArgument, ParseResult, SyntaxKind, UnexpectedSyntax},
|
||||
parser::{Parser, Reading},
|
||||
},
|
||||
};
|
||||
|
|
@ -70,18 +71,34 @@ impl Namespace {
|
|||
}
|
||||
|
||||
/// Validates a namespace string.
|
||||
#[must_use]
|
||||
pub fn validate_str(namespace: &str) -> bool {
|
||||
///
|
||||
/// # Errors
|
||||
/// - If the namespace contains invalid characters.
|
||||
pub fn validate_str(namespace: &str) -> Result<(), String> {
|
||||
const VALID_CHARS: &str = "0123456789abcdefghijklmnopqrstuvwxyz_-.";
|
||||
|
||||
namespace.chars().all(|c| VALID_CHARS.contains(c))
|
||||
let invalid_chars = namespace
|
||||
.chars()
|
||||
.filter(|c| !VALID_CHARS.contains(*c))
|
||||
.sorted()
|
||||
.unique()
|
||||
.collect::<String>();
|
||||
|
||||
if invalid_chars.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_chars)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// Parses a [`ProgramFile`].
|
||||
#[tracing::instrument(level = "debug", skip_all)]
|
||||
pub fn parse_program(&mut self, handler: &impl Handler<base::Error>) -> Option<ProgramFile> {
|
||||
pub fn parse_program(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> ParseResult<ProgramFile> {
|
||||
tracing::debug!("Parsing program");
|
||||
|
||||
let namespace = match self.stop_at_significant() {
|
||||
|
|
@ -92,23 +109,37 @@ impl<'a> Parser<'a> {
|
|||
self.forward();
|
||||
|
||||
let namespace_name = self.parse_string_literal(handler).and_then(|name| {
|
||||
Namespace::validate_str(name.str_content().as_ref()).then_some(name)
|
||||
Namespace::validate_str(name.str_content().as_ref())
|
||||
.map(|()| name.clone())
|
||||
.map_err(|invalid| {
|
||||
let err = syntax::error::Error::InvalidArgument(InvalidArgument {
|
||||
message: format!(
|
||||
"Invalid characters in namespace '{}'. The following characters are not allowed in namespace definitions: '{}'",
|
||||
name.str_content(),
|
||||
invalid
|
||||
),
|
||||
span: name.span(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
err
|
||||
})
|
||||
})?;
|
||||
|
||||
let semicolon = self.parse_punctuation(';', true, handler)?;
|
||||
|
||||
Some(Namespace {
|
||||
Ok(Namespace {
|
||||
namespace_keyword,
|
||||
namespace_name,
|
||||
semicolon,
|
||||
})
|
||||
}
|
||||
unexpected => {
|
||||
handler.receive(syntax::error::Error::from(UnexpectedSyntax {
|
||||
let err = syntax::error::Error::from(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Keyword(KeywordKind::Namespace),
|
||||
found: unexpected.into_token(),
|
||||
}));
|
||||
None
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}?;
|
||||
|
||||
|
|
@ -123,7 +154,7 @@ impl<'a> Parser<'a> {
|
|||
let result = self.parse_declaration(handler);
|
||||
|
||||
#[allow(clippy::option_if_let_else)]
|
||||
if let Some(x) = result {
|
||||
if let Ok(x) = result {
|
||||
declarations.push(x);
|
||||
} else {
|
||||
self.stop_at(|reading| {
|
||||
|
|
@ -137,7 +168,7 @@ impl<'a> Parser<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
Some(ProgramFile {
|
||||
Ok(ProgramFile {
|
||||
namespace,
|
||||
declarations,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -15,13 +15,18 @@ use crate::{
|
|||
token::{CommandLiteral, DocComment, Keyword, KeywordKind, Punctuation, Token},
|
||||
token_stream::Delimiter,
|
||||
},
|
||||
syntax::parser::{Parser, Reading},
|
||||
syntax::{
|
||||
error::ParseResult,
|
||||
parser::{Parser, Reading},
|
||||
},
|
||||
};
|
||||
|
||||
use self::execute_block::ExecuteBlock;
|
||||
|
||||
use super::expression::Expression;
|
||||
|
||||
/// Represents a statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -62,6 +67,8 @@ impl SourceElement for Statement {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a block in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -100,6 +107,8 @@ impl SourceElement for Block {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a run statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -138,6 +147,8 @@ impl Run {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a grouping statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -173,6 +184,8 @@ impl SourceElement for Grouping {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a statement that ends with a semicolon in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ``` ebnf
|
||||
/// Semicolon:
|
||||
|
|
@ -209,7 +222,10 @@ impl Semicolon {
|
|||
|
||||
impl<'a> Parser<'a> {
|
||||
/// Parses a [`Block`].
|
||||
pub fn parse_block(&mut self, handler: &impl Handler<base::Error>) -> Option<Block> {
|
||||
///
|
||||
/// # Errors
|
||||
/// - if the parser is not at a block.
|
||||
pub fn parse_block(&mut self, handler: &impl Handler<base::Error>) -> ParseResult<Block> {
|
||||
let token_tree = self.step_into(
|
||||
Delimiter::Brace,
|
||||
|parser| {
|
||||
|
|
@ -217,7 +233,7 @@ impl<'a> Parser<'a> {
|
|||
|
||||
while !parser.is_exhausted() {
|
||||
parser.parse_statement(handler).map_or_else(
|
||||
|| {
|
||||
|_| {
|
||||
// error recovery
|
||||
parser.stop_at(|reading| matches!(
|
||||
reading,
|
||||
|
|
@ -234,12 +250,12 @@ impl<'a> Parser<'a> {
|
|||
);
|
||||
}
|
||||
|
||||
Some(statements)
|
||||
Ok(statements)
|
||||
},
|
||||
handler,
|
||||
)?;
|
||||
|
||||
Some(Block {
|
||||
Ok(Block {
|
||||
open_brace: token_tree.open,
|
||||
statements: token_tree.tree?,
|
||||
close_brace: token_tree.close,
|
||||
|
|
@ -248,19 +264,22 @@ impl<'a> Parser<'a> {
|
|||
|
||||
/// Parses a [`Statement`].
|
||||
#[tracing::instrument(level = "trace", skip_all)]
|
||||
pub fn parse_statement(&mut self, handler: &impl Handler<base::Error>) -> Option<Statement> {
|
||||
pub fn parse_statement(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> ParseResult<Statement> {
|
||||
match self.stop_at_significant() {
|
||||
// variable declaration
|
||||
Reading::Atomic(Token::CommandLiteral(command)) => {
|
||||
self.forward();
|
||||
tracing::trace!("Parsed literal command '{}'", command.clean_command());
|
||||
Some(Statement::LiteralCommand(command))
|
||||
Ok(Statement::LiteralCommand(command))
|
||||
}
|
||||
// block statement
|
||||
Reading::IntoDelimited(open_brace) if open_brace.punctuation == '{' => {
|
||||
let block = self.parse_block(handler)?;
|
||||
|
||||
Some(Statement::Block(block))
|
||||
Ok(Statement::Block(block))
|
||||
}
|
||||
|
||||
// execute block
|
||||
|
|
@ -274,7 +293,7 @@ impl<'a> Parser<'a> {
|
|||
// doc comment
|
||||
Reading::Atomic(Token::DocComment(doc_comment)) => {
|
||||
self.forward();
|
||||
Some(Statement::DocComment(doc_comment))
|
||||
Ok(Statement::DocComment(doc_comment))
|
||||
}
|
||||
|
||||
// grouping statement
|
||||
|
|
@ -288,7 +307,7 @@ impl<'a> Parser<'a> {
|
|||
|
||||
tracing::trace!("Parsed group command");
|
||||
|
||||
Some(Statement::Grouping(Grouping {
|
||||
Ok(Statement::Grouping(Grouping {
|
||||
group_keyword,
|
||||
block,
|
||||
}))
|
||||
|
|
@ -306,7 +325,7 @@ impl<'a> Parser<'a> {
|
|||
|
||||
tracing::trace!("Parsed run statement: {:?}", expression);
|
||||
|
||||
Some(Statement::Run(Run {
|
||||
Ok(Statement::Run(Run {
|
||||
run_keyword,
|
||||
expression,
|
||||
semicolon,
|
||||
|
|
@ -320,7 +339,7 @@ impl<'a> Parser<'a> {
|
|||
|
||||
tracing::trace!("Parsed semicolon statement: {:?}", expression);
|
||||
|
||||
Some(Statement::Semicolon(Semicolon {
|
||||
Ok(Statement::Semicolon(Semicolon {
|
||||
expression,
|
||||
semicolon,
|
||||
}))
|
||||
|
|
|
|||
|
|
@ -8,15 +8,14 @@ use crate::{
|
|||
base::{
|
||||
self,
|
||||
source_file::{SourceElement, Span},
|
||||
VoidHandler, Handler,
|
||||
Handler, VoidHandler,
|
||||
},
|
||||
lexical::{
|
||||
token::{Keyword, KeywordKind, Punctuation, StringLiteral, Token},
|
||||
token_stream::Delimiter,
|
||||
},
|
||||
syntax::{
|
||||
self,
|
||||
error::{SyntaxKind, UnexpectedSyntax},
|
||||
error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax},
|
||||
parser::{DelimitedTree, Parser, Reading},
|
||||
syntax_tree::condition::ParenthesizedCondition,
|
||||
},
|
||||
|
|
@ -24,6 +23,8 @@ use crate::{
|
|||
|
||||
use super::Block;
|
||||
|
||||
/// Represents an execute block statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// ExecuteBlock:
|
||||
|
|
@ -52,11 +53,25 @@ impl SourceElement for ExecuteBlock {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents the head of an execute block statement.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ```ebnf
|
||||
/// ExecuteBlockHead:
|
||||
/// Conditional
|
||||
/// | Align
|
||||
/// | Anchored
|
||||
/// | As
|
||||
/// | AsAt
|
||||
/// | At
|
||||
/// | Facing
|
||||
/// | In
|
||||
/// | On
|
||||
/// | Positioned
|
||||
/// | Rotated
|
||||
/// | Store
|
||||
/// | Summon
|
||||
/// ;
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, EnumAsInner, From)]
|
||||
|
|
@ -97,6 +112,8 @@ impl SourceElement for ExecuteBlockHead {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents the tail of an execute block statement.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// ExecuteBlockTail:
|
||||
|
|
@ -123,6 +140,8 @@ impl SourceElement for ExecuteBlockTail {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an conditional `if` statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -158,6 +177,8 @@ impl SourceElement for Conditional {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `else` block in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -190,6 +211,8 @@ impl SourceElement for Else {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `as` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ```ebnf
|
||||
|
|
@ -235,6 +258,8 @@ impl As {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `align` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Align:
|
||||
|
|
@ -279,6 +304,8 @@ impl Align {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `anchored` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Anchored:
|
||||
|
|
@ -322,6 +349,8 @@ impl Anchored {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `asat` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// AsAt:
|
||||
|
|
@ -365,6 +394,8 @@ impl AsAt {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `at` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// At:
|
||||
|
|
@ -408,6 +439,8 @@ impl At {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a `facing` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Facing:
|
||||
|
|
@ -451,6 +484,8 @@ impl Facing {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `in` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// In:
|
||||
|
|
@ -494,6 +529,8 @@ impl In {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `on` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// On:
|
||||
|
|
@ -537,6 +574,8 @@ impl On {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a `positioned` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Positioned:
|
||||
|
|
@ -580,6 +619,8 @@ impl Positioned {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a `rotated` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Rotated:
|
||||
|
|
@ -623,6 +664,8 @@ impl Rotated {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a `store` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Store:
|
||||
|
|
@ -666,6 +709,8 @@ impl Store {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a `summon` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Summon:
|
||||
|
|
@ -711,10 +756,14 @@ impl Summon {
|
|||
|
||||
impl<'a> Parser<'a> {
|
||||
/// Parses an [`ExecuteBlock`].
|
||||
///
|
||||
/// # Errors
|
||||
/// - if not at the start of an execute block statement.
|
||||
/// - if the parsing of the execute block statement fails.
|
||||
pub fn parse_execute_block_statement(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Option<ExecuteBlock> {
|
||||
) -> ParseResult<ExecuteBlock> {
|
||||
match self.stop_at_significant() {
|
||||
Reading::Atomic(Token::Keyword(if_keyword))
|
||||
if if_keyword.keyword == KeywordKind::If =>
|
||||
|
|
@ -739,14 +788,17 @@ impl<'a> Parser<'a> {
|
|||
// eat the else keyword
|
||||
parser.forward();
|
||||
|
||||
let else_block = parser.parse_block(handler)?;
|
||||
let else_block = parser.parse_block(&VoidHandler)?;
|
||||
|
||||
Some((else_keyword, else_block))
|
||||
Ok((else_keyword, else_block))
|
||||
}
|
||||
_ => None,
|
||||
unexpected => Err(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Keyword(KeywordKind::Else),
|
||||
found: unexpected.into_token(),
|
||||
}),
|
||||
}?;
|
||||
|
||||
Some((
|
||||
Ok((
|
||||
block,
|
||||
Else {
|
||||
else_keyword,
|
||||
|
|
@ -755,11 +807,11 @@ impl<'a> Parser<'a> {
|
|||
))
|
||||
});
|
||||
|
||||
if let Some((block, else_tail)) = else_tail {
|
||||
Some(ExecuteBlock::IfElse(conditional, block, else_tail))
|
||||
if let Ok((block, else_tail)) = else_tail {
|
||||
Ok(ExecuteBlock::IfElse(conditional, block, else_tail))
|
||||
} else {
|
||||
let tail = self.parse_execute_block_tail(handler)?;
|
||||
Some(ExecuteBlock::HeadTail(
|
||||
Ok(ExecuteBlock::HeadTail(
|
||||
ExecuteBlockHead::Conditional(conditional),
|
||||
tail,
|
||||
))
|
||||
|
|
@ -777,11 +829,12 @@ impl<'a> Parser<'a> {
|
|||
handler,
|
||||
),
|
||||
unexpected => {
|
||||
handler.receive(syntax::error::Error::from(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::Punctuation('('),
|
||||
found: unexpected.into_token(),
|
||||
}));
|
||||
None
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}?;
|
||||
|
||||
|
|
@ -789,16 +842,17 @@ impl<'a> Parser<'a> {
|
|||
|
||||
let head = head_from_keyword(keyword, argument)?;
|
||||
|
||||
Some(ExecuteBlock::HeadTail(head, tail))
|
||||
Ok(ExecuteBlock::HeadTail(head, tail))
|
||||
}
|
||||
|
||||
// unexpected
|
||||
unexpected => {
|
||||
handler.receive(syntax::error::Error::from(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::ExecuteBlock,
|
||||
found: unexpected.into_token(),
|
||||
}));
|
||||
None
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -806,7 +860,7 @@ impl<'a> Parser<'a> {
|
|||
fn parse_execute_block_tail(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Option<ExecuteBlockTail> {
|
||||
) -> ParseResult<ExecuteBlockTail> {
|
||||
match self.stop_at_significant() {
|
||||
// nested execute block
|
||||
Reading::Atomic(Token::Punctuation(punc)) if punc.punctuation == ',' => {
|
||||
|
|
@ -815,7 +869,7 @@ impl<'a> Parser<'a> {
|
|||
|
||||
let execute_block = self.parse_execute_block_statement(handler)?;
|
||||
|
||||
Some(ExecuteBlockTail::ExecuteBlock(
|
||||
Ok(ExecuteBlockTail::ExecuteBlock(
|
||||
punc,
|
||||
Box::new(execute_block),
|
||||
))
|
||||
|
|
@ -825,15 +879,16 @@ impl<'a> Parser<'a> {
|
|||
Reading::IntoDelimited(punc) if punc.punctuation == '{' => {
|
||||
let block = self.parse_block(handler)?;
|
||||
|
||||
Some(ExecuteBlockTail::Block(block))
|
||||
Ok(ExecuteBlockTail::Block(block))
|
||||
}
|
||||
|
||||
unexpected => {
|
||||
handler.receive(syntax::error::Error::from(UnexpectedSyntax {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::ExecuteBlockTail,
|
||||
found: unexpected.into_token(),
|
||||
}));
|
||||
None
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -842,8 +897,8 @@ impl<'a> Parser<'a> {
|
|||
fn head_from_keyword(
|
||||
keyword: Keyword,
|
||||
argument: DelimitedTree<StringLiteral>,
|
||||
) -> Option<ExecuteBlockHead> {
|
||||
Some(match keyword.keyword {
|
||||
) -> ParseResult<ExecuteBlockHead> {
|
||||
Ok(match keyword.keyword {
|
||||
KeywordKind::Align => Align {
|
||||
align_keyword: keyword,
|
||||
open_paren: argument.open,
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ impl From<PrimaryCondition> for DpCondition {
|
|||
Self::Atom(literal.str_content().to_string())
|
||||
}
|
||||
PrimaryCondition::Parenthesized(cond) => cond.dissolve().1.into(),
|
||||
PrimaryCondition::Prefix(prefix) => match prefix.operator() {
|
||||
PrimaryCondition::Unary(prefix) => match prefix.operator() {
|
||||
ConditionalPrefixOperator::LogicalNot(_) => {
|
||||
Self::Not(Box::new(prefix.dissolve().1.into()))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
//! Errors that can occur during transpilation.
|
||||
|
||||
use std::fmt::Display;
|
||||
use std::{collections::BTreeMap, fmt::Display};
|
||||
|
||||
use getset::Getters;
|
||||
use itertools::Itertools;
|
||||
|
||||
use crate::{
|
||||
base::{
|
||||
|
|
@ -10,27 +13,64 @@ use crate::{
|
|||
syntax::syntax_tree::expression::Expression,
|
||||
};
|
||||
|
||||
use super::transpiler::FunctionData;
|
||||
|
||||
/// Errors that can occur during transpilation.
|
||||
#[allow(clippy::module_name_repetitions, missing_docs)]
|
||||
#[derive(Debug, thiserror::Error, Clone)]
|
||||
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
|
||||
pub enum TranspileError {
|
||||
#[error(transparent)]
|
||||
MissingFunctionDeclaration(#[from] MissingFunctionDeclaration),
|
||||
#[error("Unexpected expression: {}", .0.span().str())]
|
||||
UnexpectedExpression(Expression),
|
||||
#[error(transparent)]
|
||||
UnexpectedExpression(#[from] UnexpectedExpression),
|
||||
#[error("Lua code evaluation is disabled.")]
|
||||
LuaDisabled,
|
||||
#[error("Lua runtime error: {}", .0)]
|
||||
LuaRuntimeError(String),
|
||||
#[error(transparent)]
|
||||
LuaRuntimeError(#[from] LuaRuntimeError),
|
||||
#[error(transparent)]
|
||||
ConflictingFunctionNames(#[from] ConflictingFunctionNames),
|
||||
}
|
||||
|
||||
/// The result of a transpilation operation.
|
||||
pub type TranspileResult<T> = Result<T, TranspileError>;
|
||||
|
||||
/// An error that occurs when a function declaration is missing.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Getters)]
|
||||
pub struct MissingFunctionDeclaration {
|
||||
pub span: Span,
|
||||
#[get = "pub"]
|
||||
span: Span,
|
||||
#[get = "pub"]
|
||||
alternatives: Vec<FunctionData>,
|
||||
}
|
||||
|
||||
impl MissingFunctionDeclaration {
|
||||
pub(super) fn from_context(
|
||||
identifier_span: Span,
|
||||
functions: &BTreeMap<(String, String), FunctionData>,
|
||||
) -> Self {
|
||||
let own_name = identifier_span.str();
|
||||
let own_program_identifier = identifier_span.source_file().identifier();
|
||||
let alternatives = functions
|
||||
.iter()
|
||||
.filter_map(|((program_identifier, function_name), data)| {
|
||||
let normalized_distance =
|
||||
strsim::normalized_damerau_levenshtein(own_name, function_name);
|
||||
(program_identifier == own_program_identifier
|
||||
&& (normalized_distance > 0.8
|
||||
|| strsim::damerau_levenshtein(own_name, function_name) < 3))
|
||||
.then_some((normalized_distance, data))
|
||||
})
|
||||
.sorted_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal))
|
||||
.map(|(_, data)| data)
|
||||
.take(8)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Self {
|
||||
alternatives,
|
||||
span: identifier_span,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for MissingFunctionDeclaration {
|
||||
|
|
@ -41,12 +81,114 @@ impl Display for MissingFunctionDeclaration {
|
|||
);
|
||||
write!(f, "{}", Message::new(Severity::Error, message))?;
|
||||
|
||||
let help_message = if self.alternatives.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let mut message = String::from("did you mean ");
|
||||
for (i, alternative) in self.alternatives.iter().enumerate() {
|
||||
if i > 0 {
|
||||
message.push_str(", ");
|
||||
}
|
||||
message.push_str(&format!("`{}`", alternative.identifier_span.str()));
|
||||
}
|
||||
Some(message + "?")
|
||||
};
|
||||
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.span, Option::<u8>::None)
|
||||
SourceCodeDisplay::new(&self.span, help_message.as_ref())
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for MissingFunctionDeclaration {}
|
||||
|
||||
/// An error that occurs when a function declaration is missing.
|
||||
#[allow(clippy::module_name_repetitions)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LuaRuntimeError {
|
||||
pub code_block: Span,
|
||||
pub error_message: String,
|
||||
}
|
||||
|
||||
impl Display for LuaRuntimeError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let message = format!(
|
||||
r#"error during lua code execution: "{}""#,
|
||||
self.error_message
|
||||
);
|
||||
write!(f, "{}", Message::new(Severity::Error, message))?;
|
||||
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.code_block, Option::<u8>::None)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for LuaRuntimeError {}
|
||||
|
||||
#[cfg(feature = "lua")]
|
||||
impl LuaRuntimeError {
|
||||
pub fn from_lua_err(err: &mlua::Error, span: Span) -> Self {
|
||||
let err_string = err.to_string();
|
||||
Self {
|
||||
error_message: err_string
|
||||
.strip_prefix("runtime error: ")
|
||||
.unwrap_or(&err_string)
|
||||
.to_string(),
|
||||
code_block: span,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An error that occurs when a function declaration is missing.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UnexpectedExpression(pub Expression);
|
||||
|
||||
impl Display for UnexpectedExpression {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
Message::new(Severity::Error, "encountered unexpected expression")
|
||||
)?;
|
||||
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.0.span(), Option::<u8>::None)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for UnexpectedExpression {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ConflictingFunctionNames {
|
||||
pub definition: Span,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl Display for ConflictingFunctionNames {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
Message::new(
|
||||
Severity::Error,
|
||||
format!("the following function declaration conflicts with an existing function with name `{}`", self.name)
|
||||
)
|
||||
)?;
|
||||
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.definition, Option::<u8>::None)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ConflictingFunctionNames {}
|
||||
|
|
|
|||
|
|
@ -2,12 +2,12 @@
|
|||
|
||||
#[cfg(feature = "lua")]
|
||||
mod enabled {
|
||||
use mlua::Lua;
|
||||
use mlua::{Lua, Value};
|
||||
|
||||
use crate::{
|
||||
base::{self, source_file::SourceElement, Handler},
|
||||
syntax::syntax_tree::expression::LuaCode,
|
||||
transpile::error::{TranspileError, TranspileResult},
|
||||
transpile::error::{LuaRuntimeError, TranspileError, TranspileResult},
|
||||
};
|
||||
|
||||
impl LuaCode {
|
||||
|
|
@ -16,7 +16,10 @@ mod enabled {
|
|||
/// # Errors
|
||||
/// - If Lua code evaluation is disabled.
|
||||
#[tracing::instrument(level = "debug", name = "eval_lua", skip_all, ret)]
|
||||
pub fn eval_string(&self, handler: &impl Handler<base::Error>) -> TranspileResult<String> {
|
||||
pub fn eval_string(
|
||||
&self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> TranspileResult<Option<String>> {
|
||||
tracing::debug!("Evaluating Lua code");
|
||||
|
||||
let lua = Lua::new();
|
||||
|
|
@ -24,7 +27,7 @@ mod enabled {
|
|||
let name = {
|
||||
let span = self.span();
|
||||
let file = span.source_file();
|
||||
let path = file.path();
|
||||
let path = file.path_relative().unwrap_or_else(|| file.path().clone());
|
||||
|
||||
let start = span.start_location();
|
||||
let end = span.end_location().unwrap_or_else(|| {
|
||||
|
|
@ -43,29 +46,61 @@ mod enabled {
|
|||
)
|
||||
};
|
||||
|
||||
self.add_globals(&lua).unwrap();
|
||||
|
||||
let lua_result = lua
|
||||
.load(self.code())
|
||||
.set_name(name)
|
||||
.eval::<String>()
|
||||
.eval::<Value>()
|
||||
.map_err(|err| {
|
||||
let err = TranspileError::from(err);
|
||||
handler.receive(err.clone());
|
||||
let err =
|
||||
TranspileError::from(LuaRuntimeError::from_lua_err(&err, self.span()));
|
||||
handler.receive(crate::Error::from(err.clone()));
|
||||
err
|
||||
})?;
|
||||
|
||||
Ok(lua_result)
|
||||
}
|
||||
self.handle_lua_result(lua_result).map_err(|err| {
|
||||
handler.receive(err.clone());
|
||||
err
|
||||
})
|
||||
}
|
||||
|
||||
impl From<mlua::Error> for TranspileError {
|
||||
fn from(value: mlua::Error) -> Self {
|
||||
let string = value.to_string();
|
||||
Self::LuaRuntimeError(
|
||||
string
|
||||
.strip_prefix("runtime error: ")
|
||||
.unwrap_or(&string)
|
||||
.to_string(),
|
||||
)
|
||||
fn add_globals(&self, lua: &Lua) -> mlua::Result<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
let location = {
|
||||
let span = self.span();
|
||||
let file = span.source_file();
|
||||
file.path_relative().unwrap_or_else(|| file.path().clone())
|
||||
};
|
||||
globals.set("shu_location", location.to_string_lossy())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_lua_result(&self, value: Value) -> TranspileResult<Option<String>> {
|
||||
match value {
|
||||
Value::Nil => Ok(None),
|
||||
Value::String(s) => Ok(Some(s.to_string_lossy())),
|
||||
Value::Integer(i) => Ok(Some(i.to_string())),
|
||||
Value::Number(n) => Ok(Some(n.to_string())),
|
||||
Value::Function(f) => self.handle_lua_result(f.call(()).map_err(|err| {
|
||||
TranspileError::LuaRuntimeError(LuaRuntimeError::from_lua_err(
|
||||
&err,
|
||||
self.span(),
|
||||
))
|
||||
})?),
|
||||
Value::Boolean(_)
|
||||
| Value::Error(_)
|
||||
| Value::Table(_)
|
||||
| Value::Thread(_)
|
||||
| Value::UserData(_)
|
||||
| Value::LightUserData(_)
|
||||
| Value::Other(..) => Err(TranspileError::LuaRuntimeError(LuaRuntimeError {
|
||||
code_block: self.span(),
|
||||
error_message: format!("invalid return type {}", value.type_name()),
|
||||
})),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -84,7 +119,10 @@ mod disabled {
|
|||
///
|
||||
/// # Errors
|
||||
/// - If Lua code evaluation is disabled.
|
||||
pub fn eval_string(&self, handler: &impl Handler<base::Error>) -> TranspileResult<String> {
|
||||
pub fn eval_string(
|
||||
&self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> TranspileResult<Option<String>> {
|
||||
handler.receive(TranspileError::LuaDisabled);
|
||||
tracing::error!("Lua code evaluation is disabled");
|
||||
Err(TranspileError::LuaDisabled)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,11 @@
|
|||
//! Transpiler for `ShulkerScript`
|
||||
//! Transpiler for `Shulkerscript`
|
||||
|
||||
use chksum_md5 as md5;
|
||||
use std::{collections::HashMap, iter, sync::RwLock};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
iter,
|
||||
sync::RwLock,
|
||||
};
|
||||
|
||||
use shulkerbox::datapack::{self, Command, Datapack, Execute};
|
||||
|
||||
|
|
@ -20,28 +24,28 @@ use crate::{
|
|||
Statement,
|
||||
},
|
||||
},
|
||||
transpile::error::MissingFunctionDeclaration,
|
||||
transpile::error::{ConflictingFunctionNames, MissingFunctionDeclaration},
|
||||
};
|
||||
|
||||
use super::error::{TranspileError, TranspileResult};
|
||||
use super::error::{TranspileError, TranspileResult, UnexpectedExpression};
|
||||
|
||||
/// A transpiler for `ShulkerScript`.
|
||||
/// A transpiler for `Shulkerscript`.
|
||||
#[derive(Debug)]
|
||||
pub struct Transpiler {
|
||||
datapack: shulkerbox::datapack::Datapack,
|
||||
/// Key: (program identifier, function name)
|
||||
functions: RwLock<HashMap<(String, String), FunctionData>>,
|
||||
functions: RwLock<BTreeMap<(String, String), FunctionData>>,
|
||||
function_locations: RwLock<HashMap<(String, String), (String, bool)>>,
|
||||
aliases: RwLock<HashMap<(String, String), (String, String)>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct FunctionData {
|
||||
namespace: String,
|
||||
identifier_span: Span,
|
||||
statements: Vec<Statement>,
|
||||
public: bool,
|
||||
annotations: HashMap<String, Option<String>>,
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct FunctionData {
|
||||
pub(super) namespace: String,
|
||||
pub(super) identifier_span: Span,
|
||||
pub(super) statements: Vec<Statement>,
|
||||
pub(super) public: bool,
|
||||
pub(super) annotations: HashMap<String, Option<String>>,
|
||||
}
|
||||
|
||||
impl Transpiler {
|
||||
|
|
@ -50,7 +54,7 @@ impl Transpiler {
|
|||
pub fn new(pack_format: u8) -> Self {
|
||||
Self {
|
||||
datapack: shulkerbox::datapack::Datapack::new(pack_format),
|
||||
functions: RwLock::new(HashMap::new()),
|
||||
functions: RwLock::new(BTreeMap::new()),
|
||||
function_locations: RwLock::new(HashMap::new()),
|
||||
aliases: RwLock::new(HashMap::new()),
|
||||
}
|
||||
|
|
@ -80,7 +84,6 @@ impl Transpiler {
|
|||
|
||||
let mut always_transpile_functions = Vec::new();
|
||||
|
||||
#[allow(clippy::significant_drop_in_scrutinee)]
|
||||
{
|
||||
let functions = self.functions.read().unwrap();
|
||||
for (_, data) in functions.iter() {
|
||||
|
|
@ -144,6 +147,7 @@ impl Transpiler {
|
|||
)
|
||||
})
|
||||
.collect();
|
||||
#[allow(clippy::significant_drop_tightening)]
|
||||
self.functions.write().unwrap().insert(
|
||||
(program_identifier, name),
|
||||
FunctionData {
|
||||
|
|
@ -178,6 +182,22 @@ impl Transpiler {
|
|||
}
|
||||
}
|
||||
}
|
||||
Declaration::Tag(tag) => {
|
||||
let namespace = self
|
||||
.datapack
|
||||
.namespace_mut(&namespace.namespace_name().str_content());
|
||||
let sb_tag = namespace.tag_mut(&tag.name().str_content(), tag.tag_type());
|
||||
|
||||
if let Some(list) = &tag.entries().list {
|
||||
for value in list.elements() {
|
||||
sb_tag.add_value(value.str_content().as_ref().into());
|
||||
}
|
||||
}
|
||||
|
||||
if tag.replace().is_some() {
|
||||
sb_tag.set_replace(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -224,9 +244,10 @@ impl Transpiler {
|
|||
})
|
||||
.ok_or_else(|| {
|
||||
let error = TranspileError::MissingFunctionDeclaration(
|
||||
MissingFunctionDeclaration {
|
||||
span: identifier_span.clone(),
|
||||
},
|
||||
MissingFunctionDeclaration::from_context(
|
||||
identifier_span.clone(),
|
||||
&functions,
|
||||
),
|
||||
);
|
||||
handler.receive(error.clone());
|
||||
error
|
||||
|
|
@ -244,10 +265,12 @@ impl Transpiler {
|
|||
.and_then(|q| functions.get(&q).filter(|f| f.public))
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
let error =
|
||||
TranspileError::MissingFunctionDeclaration(MissingFunctionDeclaration {
|
||||
span: identifier_span.clone(),
|
||||
});
|
||||
let error = TranspileError::MissingFunctionDeclaration(
|
||||
MissingFunctionDeclaration::from_context(
|
||||
identifier_span.clone(),
|
||||
&functions,
|
||||
),
|
||||
);
|
||||
handler.receive(error.clone());
|
||||
error
|
||||
})?;
|
||||
|
|
@ -259,16 +282,24 @@ impl Transpiler {
|
|||
|| {
|
||||
let hash_data =
|
||||
program_identifier.to_string() + "\0" + identifier_span.str();
|
||||
Some("shu/".to_string() + &md5::hash(hash_data).to_hex_lowercase()[..16])
|
||||
Some("shu/".to_string() + &md5::hash(hash_data).to_hex_lowercase())
|
||||
},
|
||||
Clone::clone,
|
||||
)
|
||||
.unwrap_or_else(|| identifier_span.str().to_string());
|
||||
|
||||
let function = self
|
||||
.datapack
|
||||
.namespace_mut(&function_data.namespace)
|
||||
.function_mut(&modified_name);
|
||||
let namespace = self.datapack.namespace_mut(&function_data.namespace);
|
||||
|
||||
if namespace.function(&modified_name).is_some() {
|
||||
let err = TranspileError::ConflictingFunctionNames(ConflictingFunctionNames {
|
||||
name: modified_name,
|
||||
definition: identifier_span.clone(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let function = namespace.function_mut(&modified_name);
|
||||
function.get_commands_mut().extend(commands);
|
||||
|
||||
let function_location = format!(
|
||||
|
|
@ -297,10 +328,12 @@ impl Transpiler {
|
|||
.get(&program_query)
|
||||
.or_else(|| alias_query.and_then(|q| locations.get(&q).filter(|(_, p)| *p)))
|
||||
.ok_or_else(|| {
|
||||
let error =
|
||||
TranspileError::MissingFunctionDeclaration(MissingFunctionDeclaration {
|
||||
span: identifier_span.clone(),
|
||||
});
|
||||
let error = TranspileError::MissingFunctionDeclaration(
|
||||
MissingFunctionDeclaration::from_context(
|
||||
identifier_span.clone(),
|
||||
&self.functions.read().unwrap(),
|
||||
),
|
||||
);
|
||||
handler.receive(error.clone());
|
||||
error
|
||||
})
|
||||
|
|
@ -350,7 +383,7 @@ impl Transpiler {
|
|||
Ok(Some(Command::Raw(string.str_content().to_string())))
|
||||
}
|
||||
Expression::Primary(Primary::Lua(code)) => {
|
||||
Ok(Some(Command::Raw(code.eval_string(handler)?)))
|
||||
Ok(code.eval_string(handler)?.map(Command::Raw))
|
||||
}
|
||||
},
|
||||
Statement::Block(_) => {
|
||||
|
|
@ -391,7 +424,9 @@ impl Transpiler {
|
|||
self.transpile_function_call(func, handler).map(Some)
|
||||
}
|
||||
unexpected => {
|
||||
let error = TranspileError::UnexpectedExpression(unexpected.clone());
|
||||
let error = TranspileError::UnexpectedExpression(UnexpectedExpression(
|
||||
unexpected.clone(),
|
||||
));
|
||||
handler.receive(error.clone());
|
||||
Err(error)
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue