Compare commits
35 Commits
3d4ad4bdf4
...
e177760f2c
| Author | SHA1 | Date |
|---|---|---|
|
|
e177760f2c | |
|
|
fe293b2dc4 | |
|
|
0bf9625620 | |
|
|
52ee83e0da | |
|
|
f3f69faace | |
|
|
c30bcc3018 | |
|
|
4a5f34a07b | |
|
|
9ee888f996 | |
|
|
572c68ca10 | |
|
|
b11f4d1caf | |
|
|
5fbe40c41f | |
|
|
346b97a58a | |
|
|
a99a155d76 | |
|
|
3a423e1de5 | |
|
|
95153f2912 | |
|
|
c0b266caca | |
|
|
134f181635 | |
|
|
c880b58f64 | |
|
|
550459922d | |
|
|
09400afa13 | |
|
|
320eef8ed7 | |
|
|
1f36650b50 | |
|
|
5e6f158993 | |
|
|
f7414ad23f | |
|
|
4d57e5ac61 | |
|
|
973e6c2c1f | |
|
|
1f4cad5634 | |
|
|
536c8479aa | |
|
|
01a2d66503 | |
|
|
9581da3c04 | |
|
|
301ceb3efa | |
|
|
a2de2d7338 | |
|
|
6094fc0df3 | |
|
|
4efcb55d7c | |
|
|
befdc2bfd4 |
|
|
@ -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
|
||||
- develop
|
||||
- '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
|
||||
|
|
@ -1,2 +1 @@
|
|||
/target
|
||||
/Cargo.lock
|
||||
|
|
|
|||
20
CHANGELOG.md
20
CHANGELOG.md
|
|
@ -9,6 +9,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
### Added
|
||||
|
||||
- Macro strings
|
||||
- Function parameters/arguments
|
||||
- Example: barebones compiler
|
||||
|
||||
### Changed
|
||||
|
||||
- Option to deduplicate source files during serialization when using `SerdeWrapper`
|
||||
|
||||
### Removed
|
||||
|
||||
## [0.1.0] - 2024-10-01
|
||||
|
||||
### Added
|
||||
|
||||
- Functions
|
||||
- without arguments
|
||||
- Raw commands
|
||||
|
|
@ -20,7 +34,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)!
|
||||
File diff suppressed because it is too large
Load Diff
43
Cargo.toml
43
Cargo.toml
|
|
@ -4,34 +4,45 @@ 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"]
|
||||
serde = ["dep:serde", "shulkerbox?/serde"]
|
||||
shulkerbox = ["dep:shulkerbox"]
|
||||
default = ["fs_access", "lua", "shulkerbox", "zip"]
|
||||
fs_access = ["shulkerbox?/fs_access"]
|
||||
lua = ["dep:mlua"]
|
||||
serde = ["dep:serde", "dep:flexbuffers", "shulkerbox?/serde"]
|
||||
shulkerbox = ["dep:shulkerbox", "dep:chksum-md5"]
|
||||
zip = ["shulkerbox?/zip"]
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
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"] }
|
||||
chksum-md5 = { version = "0.1.0", optional = true }
|
||||
colored = "3.0.0"
|
||||
derive_more = { version = "2.0.1", default-features = false, features = ["deref", "deref_mut", "from"] }
|
||||
enum-as-inner = "0.6.0"
|
||||
flexbuffers = { version = "25.2.10", optional = true }
|
||||
getset = "0.1.2"
|
||||
mlua = { version = "0.9.7", features = ["lua54", "vendored"], optional = true }
|
||||
itertools = "0.14.0"
|
||||
mlua = { version = "0.10.2", 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" }
|
||||
strum = { version = "0.26.2", features = ["derive"] }
|
||||
strum_macros = "0.26.2"
|
||||
thiserror = "1.0.58"
|
||||
tracing = "0.1.40"
|
||||
pathdiff = "0.2.3"
|
||||
serde = { version = "1.0.217", features = ["derive"], optional = true }
|
||||
# shulkerbox = { version = "0.1.0", default-features = false, optional = true }
|
||||
shulkerbox = { git = "https://github.com/moritz-hoelting/shulkerbox", rev = "6fefa27f2f1d22e4974a8b62fdadc087b5c2be22", default-features = false, optional = true }
|
||||
strsim = "0.11.1"
|
||||
strum = { version = "0.27.0", features = ["derive"] }
|
||||
thiserror = "2.0.11"
|
||||
tracing = "0.1.41"
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1.0.138"
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
//! This example demonstrates how to compile a shulkerscript file into a datapack using the shulkerscript compiler.
|
||||
//! Most basic version of a shulkerscript compiler, which takes a single input file and places the resulting datapack in the specified output directory.
|
||||
//!
|
||||
//! For a ready-to-use compiler, see the `shulkerscript-cli` crate.
|
||||
|
||||
use shulkerscript::{
|
||||
base::{FsProvider, PrintHandler},
|
||||
compile,
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "shulkerbox"))]
|
||||
compile_error!("Need feature 'shulkerbox' to compile this example");
|
||||
|
||||
fn main() {
|
||||
let mut args = std::env::args();
|
||||
let _ = args.next().unwrap();
|
||||
let input = args.next().expect("Expect path to shulkerscript file");
|
||||
|
||||
let output = args.next().expect("Expect path to output directory");
|
||||
|
||||
let code = compile(
|
||||
&PrintHandler::new(),
|
||||
&FsProvider::default(),
|
||||
shulkerbox::datapack::Datapack::LATEST_FORMAT,
|
||||
&[("main".to_string(), &input)],
|
||||
)
|
||||
.expect("failed to compile");
|
||||
|
||||
code.place(output).expect("failed to place datapack");
|
||||
}
|
||||
28
grammar.md
28
grammar.md
|
|
@ -1,4 +1,4 @@
|
|||
# Grammar of the ShulkerScript language
|
||||
# Grammar of the Shulkerscript language
|
||||
|
||||
## Table of contents
|
||||
|
||||
|
|
@ -12,9 +12,24 @@ Program: Namespace Declaration*;
|
|||
Namespace: 'namespace' StringLiteral;
|
||||
```
|
||||
|
||||
### StringLiteral
|
||||
```ebnf
|
||||
StringLiteral: '"' TEXT '"';
|
||||
```
|
||||
|
||||
### MacroStringLiteral
|
||||
```ebnf
|
||||
MacroStringLiteral: '`' ( TEXT | '$(' [a-zA-Z0-9_]+ ')' )* '`';
|
||||
```
|
||||
|
||||
### AnyStringLiteral
|
||||
```ebnf
|
||||
AnyStringLiteral: StringLiteral | MacroStringLiteral;
|
||||
```
|
||||
|
||||
### Declaration
|
||||
```ebnf
|
||||
Declaration: FunctionDeclaration | Import;
|
||||
Declaration: FunctionDeclaration | Import | TagDeclaration;
|
||||
```
|
||||
|
||||
### Import
|
||||
|
|
@ -22,6 +37,11 @@ Declaration: FunctionDeclaration | Import;
|
|||
Import: 'from' StringLiteral 'import' Identifier;
|
||||
```
|
||||
|
||||
### TagDeclaration
|
||||
```ebnf
|
||||
TagDeclaration: 'tag' StringLiteral ('of' StringLiteral)? 'replace'? '[' (StringLiteral (',' StringLiteral)*)? ']';
|
||||
```
|
||||
|
||||
### FunctionDeclaration
|
||||
```ebnf
|
||||
Function:
|
||||
|
|
@ -82,7 +102,7 @@ Condition:
|
|||
PrimaryCondition:
|
||||
ConditionalPrefix
|
||||
| ParenthesizedCondition
|
||||
| StringLiteral
|
||||
| AnyStringLiteral
|
||||
;
|
||||
```
|
||||
|
||||
|
|
@ -139,6 +159,8 @@ Expression:
|
|||
```ebnf
|
||||
Primary:
|
||||
FunctionCall
|
||||
| AnyStringLiteral
|
||||
| LuaCode
|
||||
;
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -1,19 +1,26 @@
|
|||
/// 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)]
|
||||
SemanticError(#[from] crate::semantic::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,11 +136,17 @@ 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.
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Clone, Getters, CopyGetters)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Span {
|
||||
/// Get the start byte index of the span.
|
||||
#[get_copy = "pub"]
|
||||
|
|
@ -148,6 +158,7 @@ pub struct Span {
|
|||
|
||||
/// Get the source file that the span is located in.
|
||||
#[get = "pub"]
|
||||
#[cfg_attr(feature = "serde", serde(with = "crate::serde::source_file"))]
|
||||
source_file: Arc<SourceFile>,
|
||||
}
|
||||
|
||||
|
|
@ -243,6 +254,26 @@ impl Span {
|
|||
})
|
||||
}
|
||||
|
||||
/// Create a span from the given start byte index to the end of the source file with an offset.
|
||||
#[must_use]
|
||||
pub fn to_end_with_offset(
|
||||
source_file: Arc<SourceFile>,
|
||||
start: usize,
|
||||
end_offset: isize,
|
||||
) -> Option<Self> {
|
||||
if !source_file.content().is_char_boundary(start) {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
start,
|
||||
end: source_file
|
||||
.content()
|
||||
.len()
|
||||
.saturating_add_signed(end_offset),
|
||||
source_file,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the string slice of the source code that the span represents.
|
||||
#[must_use]
|
||||
pub fn str(&self) -> &str {
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -4,13 +4,13 @@ use std::{borrow::Cow, collections::HashMap, fmt::Display, str::FromStr, sync::O
|
|||
|
||||
use crate::base::{
|
||||
self,
|
||||
log::SourceCodeDisplay,
|
||||
source_file::{SourceElement, SourceIterator, Span},
|
||||
Handler,
|
||||
};
|
||||
use derive_more::From;
|
||||
use enum_as_inner::EnumAsInner;
|
||||
use strum::IntoEnumIterator;
|
||||
use strum_macros::EnumIter;
|
||||
use strum::{EnumIter, IntoEnumIterator};
|
||||
|
||||
use super::error::{self, UnterminatedDelimitedComment};
|
||||
|
||||
|
|
@ -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",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -140,24 +146,7 @@ pub enum Token {
|
|||
DocComment(DocComment),
|
||||
CommandLiteral(CommandLiteral),
|
||||
StringLiteral(StringLiteral),
|
||||
}
|
||||
|
||||
impl Token {
|
||||
/// Returns the span of the token.
|
||||
#[must_use]
|
||||
pub fn span(&self) -> &Span {
|
||||
match self {
|
||||
Self::WhiteSpaces(token) => &token.span,
|
||||
Self::Identifier(token) => &token.span,
|
||||
Self::Keyword(token) => &token.span,
|
||||
Self::Punctuation(token) => &token.span,
|
||||
Self::Numeric(token) => &token.span,
|
||||
Self::Comment(token) => &token.span,
|
||||
Self::DocComment(token) => &token.span,
|
||||
Self::CommandLiteral(token) => &token.span,
|
||||
Self::StringLiteral(token) => &token.span,
|
||||
}
|
||||
}
|
||||
MacroStringLiteral(MacroStringLiteral),
|
||||
}
|
||||
|
||||
impl SourceElement for Token {
|
||||
|
|
@ -172,6 +161,7 @@ impl SourceElement for Token {
|
|||
Self::DocComment(token) => token.span(),
|
||||
Self::CommandLiteral(token) => token.span(),
|
||||
Self::StringLiteral(token) => token.span(),
|
||||
Self::MacroStringLiteral(token) => token.span(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -285,6 +275,76 @@ impl SourceElement for StringLiteral {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a hardcoded macro string literal value in the source code.
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct MacroStringLiteral {
|
||||
/// The backtick that starts the macro string literal.
|
||||
starting_backtick: Punctuation,
|
||||
/// The parts that make up the macro string literal.
|
||||
parts: Vec<MacroStringLiteralPart>,
|
||||
/// The backtick that ends the macro string literal.
|
||||
ending_backtick: Punctuation,
|
||||
}
|
||||
|
||||
impl MacroStringLiteral {
|
||||
/// Returns the string content without escapement characters, leading and trailing double quotes.
|
||||
#[cfg(feature = "shulkerbox")]
|
||||
#[must_use]
|
||||
pub fn str_content(&self) -> String {
|
||||
use std::fmt::Write;
|
||||
|
||||
let mut content = String::new();
|
||||
|
||||
for part in &self.parts {
|
||||
match part {
|
||||
MacroStringLiteralPart::Text(span) => {
|
||||
content += &crate::util::unescape_macro_string(span.str());
|
||||
}
|
||||
MacroStringLiteralPart::MacroUsage { identifier, .. } => {
|
||||
write!(
|
||||
content,
|
||||
"$({})",
|
||||
crate::transpile::util::identifier_to_macro(identifier.span.str())
|
||||
)
|
||||
.expect("can always write to string");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
content
|
||||
}
|
||||
|
||||
/// Returns the parts that make up the macro string literal.
|
||||
#[must_use]
|
||||
pub fn parts(&self) -> &[MacroStringLiteralPart] {
|
||||
&self.parts
|
||||
}
|
||||
}
|
||||
|
||||
impl SourceElement for MacroStringLiteral {
|
||||
fn span(&self) -> Span {
|
||||
self.starting_backtick
|
||||
.span
|
||||
.join(&self.ending_backtick.span)
|
||||
.expect("Invalid macro string literal span")
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a part of a macro string literal value in the source code.
|
||||
#[allow(missing_docs)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum MacroStringLiteralPart {
|
||||
Text(Span),
|
||||
MacroUsage {
|
||||
dollar: Punctuation,
|
||||
open_brace: Punctuation,
|
||||
identifier: Identifier,
|
||||
close_brace: Punctuation,
|
||||
},
|
||||
}
|
||||
|
||||
/// Is an enumeration representing the two kinds of comments in the Shulkerscript programming language.
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
|
|
@ -357,7 +417,7 @@ impl CommandLiteral {
|
|||
}
|
||||
|
||||
/// Is an error that can occur when invoking the [`Token::tokenize`] method.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, thiserror::Error, From)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, thiserror::Error)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum TokenizeError {
|
||||
#[error("encountered a fatal lexical error that causes the process to stop.")]
|
||||
|
|
@ -365,8 +425,95 @@ pub enum TokenizeError {
|
|||
|
||||
#[error("the iterator argument is at the end of the source code.")]
|
||||
EndOfSourceCodeIteratorArgument,
|
||||
|
||||
#[error(transparent)]
|
||||
InvalidMacroNameCharacter(#[from] InvalidMacroNameCharacter),
|
||||
|
||||
#[error(transparent)]
|
||||
UnclosedMacroUsage(#[from] UnclosedMacroUsage),
|
||||
|
||||
#[error(transparent)]
|
||||
EmptyMacroUsage(#[from] EmptyMacroUsage),
|
||||
}
|
||||
|
||||
/// Is an error that can occur when the macro name contains invalid characters.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct InvalidMacroNameCharacter {
|
||||
/// The span of the invalid characters.
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl Display for InvalidMacroNameCharacter {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
base::log::Message::new(base::log::Severity::Error, format!("The macro name contains invalid characters: `{}`. Only alphanumeric characters and underscores are allowed.", self.span.str()))
|
||||
)?;
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.span, Option::<u8>::None)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidMacroNameCharacter {}
|
||||
|
||||
/// Is an error that can occur when the macro usage is not closed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct UnclosedMacroUsage {
|
||||
/// The span of the unclosed macro usage.
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl Display for UnclosedMacroUsage {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
base::log::Message::new(
|
||||
base::log::Severity::Error,
|
||||
"A macro usage was opened with `$(` but never closed."
|
||||
)
|
||||
)?;
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.span, Option::<u8>::None)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for UnclosedMacroUsage {}
|
||||
|
||||
/// Is an error that can occur when the macro usage is not closed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct EmptyMacroUsage {
|
||||
/// The span of the unclosed macro usage.
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl Display for EmptyMacroUsage {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
base::log::Message::new(
|
||||
base::log::Severity::Error,
|
||||
"A macro usage was opened with `$(` but closed immediately with `)`."
|
||||
)
|
||||
)?;
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.span, Option::<u8>::None)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for EmptyMacroUsage {}
|
||||
|
||||
impl Token {
|
||||
/// Increments the iterator while the predicate returns true.
|
||||
pub fn walk_iter(iter: &mut SourceIterator, predicate: impl Fn(char) -> bool) {
|
||||
|
|
@ -380,6 +527,7 @@ impl Token {
|
|||
}
|
||||
|
||||
/// Creates a span from the given start location to the current location of the iterator.
|
||||
#[must_use]
|
||||
fn create_span(start: usize, iter: &mut SourceIterator) -> Span {
|
||||
iter.peek().map_or_else(
|
||||
|| Span::to_end(iter.source_file().clone(), start).unwrap(),
|
||||
|
|
@ -387,6 +535,26 @@ impl Token {
|
|||
)
|
||||
}
|
||||
|
||||
/// Creates a span from the given start location to the current location of the iterator with the given offset.
|
||||
#[must_use]
|
||||
fn create_span_with_end_offset(
|
||||
start: usize,
|
||||
iter: &mut SourceIterator,
|
||||
end_offset: isize,
|
||||
) -> Span {
|
||||
iter.peek().map_or_else(
|
||||
|| Span::to_end_with_offset(iter.source_file().clone(), start, end_offset).unwrap(),
|
||||
|(index, _)| {
|
||||
Span::new(
|
||||
iter.source_file().clone(),
|
||||
start,
|
||||
index.saturating_add_signed(end_offset),
|
||||
)
|
||||
.unwrap()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Checks if the given character is a valid first character of an identifier.
|
||||
fn is_first_identifier_character(character: char) -> bool {
|
||||
character == '_'
|
||||
|
|
@ -455,17 +623,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 {
|
||||
|
|
@ -555,6 +714,113 @@ impl Token {
|
|||
.into()
|
||||
}
|
||||
|
||||
/// Handles a sequence of characters that are enclosed in backticks and contain macro usages
|
||||
fn handle_macro_string_literal(
|
||||
iter: &mut SourceIterator,
|
||||
mut start: usize,
|
||||
) -> Result<Self, TokenizeError> {
|
||||
let mut is_escaped = false;
|
||||
let mut is_inside_macro = false;
|
||||
let mut encountered_open_parenthesis = false;
|
||||
let starting_backtick = Punctuation {
|
||||
span: Self::create_span(start, iter),
|
||||
punctuation: '`',
|
||||
};
|
||||
start += 1;
|
||||
let mut parts = Vec::new();
|
||||
|
||||
while iter.peek().is_some() {
|
||||
let (index, character) = iter.next().unwrap();
|
||||
|
||||
#[expect(clippy::collapsible_else_if)]
|
||||
if is_inside_macro {
|
||||
if character == ')' {
|
||||
// Check if the macro usage is empty
|
||||
if start + 2 == index {
|
||||
return Err(EmptyMacroUsage {
|
||||
span: Span::new(iter.source_file().clone(), start, index + 1).unwrap(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
parts.push(MacroStringLiteralPart::MacroUsage {
|
||||
dollar: Punctuation {
|
||||
span: Span::new(iter.source_file().clone(), start, start + 1).unwrap(),
|
||||
punctuation: '$',
|
||||
},
|
||||
open_brace: Punctuation {
|
||||
span: Span::new(iter.source_file().clone(), start + 1, start + 2)
|
||||
.unwrap(),
|
||||
punctuation: '(',
|
||||
},
|
||||
identifier: Identifier {
|
||||
span: Self::create_span_with_end_offset(start + 2, iter, -1),
|
||||
},
|
||||
close_brace: Punctuation {
|
||||
span: Span::new(iter.source_file().clone(), index, index + 1).unwrap(),
|
||||
punctuation: ')',
|
||||
},
|
||||
});
|
||||
start = index + 1;
|
||||
is_inside_macro = false;
|
||||
} else if !encountered_open_parenthesis && character == '(' {
|
||||
encountered_open_parenthesis = true;
|
||||
} else if encountered_open_parenthesis && !Self::is_identifier_character(character)
|
||||
{
|
||||
if character == '`' {
|
||||
return Err(UnclosedMacroUsage {
|
||||
span: Span::new(iter.source_file().clone(), start, start + 2).unwrap(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
|
||||
Self::walk_iter(iter, |c| c != ')' && !Self::is_identifier_character(c));
|
||||
return Err(InvalidMacroNameCharacter {
|
||||
span: Self::create_span(index, iter),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
} else {
|
||||
if character == '$' && iter.peek().is_some_and(|(_, c)| c == '(') {
|
||||
parts.push(MacroStringLiteralPart::Text(
|
||||
Self::create_span_with_end_offset(start, iter, -1),
|
||||
));
|
||||
start = index;
|
||||
is_inside_macro = true;
|
||||
encountered_open_parenthesis = false;
|
||||
} else if character == '\\' {
|
||||
is_escaped = !is_escaped;
|
||||
} else if character == '`' && !is_escaped {
|
||||
if start != index {
|
||||
parts.push(MacroStringLiteralPart::Text(
|
||||
Self::create_span_with_end_offset(start, iter, -1),
|
||||
));
|
||||
}
|
||||
start = index;
|
||||
break;
|
||||
} else {
|
||||
is_escaped = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if is_inside_macro {
|
||||
Err(UnclosedMacroUsage {
|
||||
span: Span::new(iter.source_file().clone(), start, start + 2).unwrap(),
|
||||
}
|
||||
.into())
|
||||
} else {
|
||||
Ok(MacroStringLiteral {
|
||||
starting_backtick,
|
||||
parts,
|
||||
ending_backtick: Punctuation {
|
||||
span: Self::create_span(start, iter),
|
||||
punctuation: '`',
|
||||
},
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles a command that is preceeded by a slash
|
||||
fn handle_command_literal(iter: &mut SourceIterator, start: usize) -> Self {
|
||||
Self::walk_iter(iter, |c| !(c.is_whitespace() && c.is_ascii_control()));
|
||||
|
|
@ -596,9 +862,15 @@ impl Token {
|
|||
// Found comment/single slash punctuation
|
||||
else if character == '/' {
|
||||
Self::handle_comment(iter, start, character, prev_token, handler)
|
||||
} else if character == '"' {
|
||||
}
|
||||
// Found string literal
|
||||
else if character == '"' {
|
||||
Ok(Self::handle_string_literal(iter, start))
|
||||
}
|
||||
// Found macro string literal
|
||||
else if character == '`' {
|
||||
Self::handle_macro_string_literal(iter, start)
|
||||
}
|
||||
// Found numeric literal
|
||||
else if character.is_ascii_digit() {
|
||||
Ok(Self::handle_numeric_literal(iter, start))
|
||||
|
|
|
|||
|
|
@ -5,10 +5,13 @@ use std::{fmt::Debug, sync::Arc};
|
|||
use derive_more::{Deref, From};
|
||||
use enum_as_inner::EnumAsInner;
|
||||
|
||||
use crate::base::{
|
||||
use crate::{
|
||||
base::{
|
||||
self,
|
||||
source_file::{SourceElement, SourceFile, Span},
|
||||
Handler,
|
||||
},
|
||||
lexical::Error,
|
||||
};
|
||||
|
||||
use super::{
|
||||
|
|
@ -62,6 +65,17 @@ impl TokenStream {
|
|||
Err(TokenizeError::FatalLexicalError) => {
|
||||
tracing::error!("Fatal lexical error encountered while tokenizing source code");
|
||||
}
|
||||
Err(TokenizeError::InvalidMacroNameCharacter(err)) => {
|
||||
handler.receive(Error::TokenizeError(
|
||||
TokenizeError::InvalidMacroNameCharacter(err),
|
||||
));
|
||||
}
|
||||
Err(TokenizeError::UnclosedMacroUsage(err)) => {
|
||||
handler.receive(Error::TokenizeError(TokenizeError::UnclosedMacroUsage(err)));
|
||||
}
|
||||
Err(TokenizeError::EmptyMacroUsage(err)) => {
|
||||
handler.receive(Error::TokenizeError(TokenizeError::EmptyMacroUsage(err)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -184,7 +198,7 @@ pub enum TokenTree {
|
|||
impl SourceElement for TokenTree {
|
||||
fn span(&self) -> Span {
|
||||
match self {
|
||||
Self::Token(token) => token.span().to_owned(),
|
||||
Self::Token(token) => token.span(),
|
||||
Self::Delimited(delimited) => delimited
|
||||
.open
|
||||
.span()
|
||||
|
|
|
|||
30
src/lib.rs
30
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,
|
||||
|
|
@ -12,12 +12,21 @@
|
|||
#![warn(missing_docs, clippy::all, clippy::pedantic)]
|
||||
#![allow(clippy::missing_panics_doc, clippy::missing_const_for_fn)]
|
||||
|
||||
#[cfg(feature = "shulkerbox")]
|
||||
pub use shulkerbox;
|
||||
|
||||
pub mod base;
|
||||
pub mod lexical;
|
||||
pub mod semantic;
|
||||
pub mod syntax;
|
||||
pub mod transpile;
|
||||
pub mod util;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
pub(crate) mod serde;
|
||||
#[cfg(feature = "serde")]
|
||||
#[cfg_attr(feature = "serde", doc(inline))]
|
||||
pub use serde::SerdeWrapper;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
|
|
@ -29,6 +38,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 +92,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,16 +100,16 @@ 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.",
|
||||
));
|
||||
}
|
||||
|
||||
program.analyze_semantics(handler)?;
|
||||
|
||||
Ok(program)
|
||||
}
|
||||
|
||||
|
|
@ -165,7 +179,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.",
|
||||
));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,286 @@
|
|||
//! Error types for the semantic analysis phase of the compiler.
|
||||
|
||||
#![allow(missing_docs)]
|
||||
|
||||
use std::{collections::HashSet, fmt::Display};
|
||||
|
||||
use getset::Getters;
|
||||
use itertools::Itertools as _;
|
||||
|
||||
use crate::{
|
||||
base::{
|
||||
log::{Message, Severity, SourceCodeDisplay},
|
||||
source_file::{SourceElement as _, Span},
|
||||
},
|
||||
lexical::token::StringLiteral,
|
||||
syntax::syntax_tree::expression::Expression,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
MissingFunctionDeclaration(#[from] MissingFunctionDeclaration),
|
||||
#[error(transparent)]
|
||||
UnexpectedExpression(#[from] UnexpectedExpression),
|
||||
#[error(transparent)]
|
||||
ConflictingFunctionNames(#[from] ConflictingFunctionNames),
|
||||
#[error(transparent)]
|
||||
InvalidNamespaceName(#[from] InvalidNamespaceName),
|
||||
#[error(transparent)]
|
||||
UnresolvedMacroUsage(#[from] UnresolvedMacroUsage),
|
||||
#[error(transparent)]
|
||||
IncompatibleFunctionAnnotation(#[from] IncompatibleFunctionAnnotation),
|
||||
}
|
||||
|
||||
/// An error that occurs when a function declaration is missing.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Getters)]
|
||||
pub struct MissingFunctionDeclaration {
|
||||
#[get = "pub"]
|
||||
span: Span,
|
||||
#[get = "pub"]
|
||||
alternatives: Vec<String>,
|
||||
}
|
||||
|
||||
impl MissingFunctionDeclaration {
|
||||
pub(super) fn from_context(identifier_span: Span, functions: &HashSet<String>) -> Self {
|
||||
let own_name = identifier_span.str();
|
||||
let alternatives = functions
|
||||
.iter()
|
||||
.filter_map(|function_name| {
|
||||
let normalized_distance =
|
||||
strsim::normalized_damerau_levenshtein(own_name, function_name);
|
||||
(normalized_distance > 0.8
|
||||
|| strsim::damerau_levenshtein(own_name, function_name) < 3)
|
||||
.then_some((normalized_distance, function_name))
|
||||
})
|
||||
.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 {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
use std::fmt::Write;
|
||||
|
||||
let message = format!(
|
||||
"no matching function declaration found for invocation of function `{}`",
|
||||
self.span.str()
|
||||
);
|
||||
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(", ");
|
||||
}
|
||||
write!(message, "`{alternative}`")?;
|
||||
}
|
||||
Some(message + "?")
|
||||
};
|
||||
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.span, help_message.as_ref())
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for MissingFunctionDeclaration {}
|
||||
|
||||
/// An error that occurs when a function declaration is missing.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
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, Hash)]
|
||||
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 {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct InvalidNamespaceName {
|
||||
pub name: StringLiteral,
|
||||
pub invalid_chars: String,
|
||||
}
|
||||
|
||||
impl Display for InvalidNamespaceName {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
Message::new(
|
||||
Severity::Error,
|
||||
format!(
|
||||
"Invalid characters in namespace `{}`. The following characters are not allowed in namespace definitions: `{}`",
|
||||
self.name.str_content(),
|
||||
self.invalid_chars
|
||||
)
|
||||
)
|
||||
)?;
|
||||
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.name.span, Option::<u8>::None)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidNamespaceName {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct UnresolvedMacroUsage {
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl Display for UnresolvedMacroUsage {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
Message::new(
|
||||
Severity::Error,
|
||||
format!(
|
||||
"Macro `{}` was used, but could not be resolved.",
|
||||
self.span.str(),
|
||||
)
|
||||
)
|
||||
)?;
|
||||
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(
|
||||
&self.span,
|
||||
Some(format!(
|
||||
"You might want to add `{}` to the function parameters.",
|
||||
self.span.str()
|
||||
))
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for UnresolvedMacroUsage {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct IncompatibleFunctionAnnotation {
|
||||
pub span: Span,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
impl Display for IncompatibleFunctionAnnotation {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
Message::new(
|
||||
Severity::Error,
|
||||
format!(
|
||||
"Annotation `{}` cannot be used here, because {}.",
|
||||
self.span.str(),
|
||||
self.reason
|
||||
)
|
||||
)
|
||||
)?;
|
||||
|
||||
write!(f, "\n{}", SourceCodeDisplay::new(&self.span, None::<u8>))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IncompatibleFunctionAnnotation {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct InvalidFunctionArguments {
|
||||
pub span: Span,
|
||||
pub expected: usize,
|
||||
pub actual: usize,
|
||||
}
|
||||
|
||||
impl Display for InvalidFunctionArguments {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
Message::new(
|
||||
Severity::Error,
|
||||
format!(
|
||||
"Expected {} arguments, but got {}.",
|
||||
self.expected, self.actual
|
||||
)
|
||||
)
|
||||
)?;
|
||||
|
||||
let help_message = if self.expected > self.actual {
|
||||
format!(
|
||||
"You might want to add {} more arguments.",
|
||||
self.expected - self.actual
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"You might want to remove {} arguments.",
|
||||
self.actual - self.expected
|
||||
)
|
||||
};
|
||||
|
||||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(&self.span, Some(help_message))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidFunctionArguments {}
|
||||
|
|
@ -0,0 +1,574 @@
|
|||
//! This module contains the semantic analysis of the AST.
|
||||
|
||||
#![allow(clippy::missing_errors_doc)]
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use error::{
|
||||
IncompatibleFunctionAnnotation, InvalidNamespaceName, MissingFunctionDeclaration,
|
||||
UnexpectedExpression, UnresolvedMacroUsage,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
base::{self, source_file::SourceElement as _, Handler},
|
||||
lexical::token::{MacroStringLiteral, MacroStringLiteralPart},
|
||||
syntax::syntax_tree::{
|
||||
condition::{
|
||||
BinaryCondition, Condition, ParenthesizedCondition, PrimaryCondition, UnaryCondition,
|
||||
},
|
||||
declaration::{Declaration, Function, ImportItems},
|
||||
expression::{Expression, FunctionCall, Primary},
|
||||
program::{Namespace, ProgramFile},
|
||||
statement::{
|
||||
execute_block::{
|
||||
Conditional, Else, ExecuteBlock, ExecuteBlockHead, ExecuteBlockHeadItem as _,
|
||||
ExecuteBlockTail,
|
||||
},
|
||||
Block, Grouping, Run, Semicolon, Statement,
|
||||
},
|
||||
AnyStringLiteral,
|
||||
},
|
||||
};
|
||||
|
||||
pub mod error;
|
||||
|
||||
impl ProgramFile {
|
||||
/// Analyzes the semantics of the program.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
self.namespace().analyze_semantics(handler)?;
|
||||
|
||||
let mut errs = Vec::new();
|
||||
let function_names = extract_all_function_names(self.declarations(), handler)?;
|
||||
|
||||
for declaration in self.declarations() {
|
||||
if let Err(err) = declaration.analyze_semantics(&function_names, handler) {
|
||||
errs.push(err);
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::option_if_let_else)]
|
||||
if let Some(err) = errs.first() {
|
||||
Err(err.clone())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_all_function_names(
|
||||
declarations: &[Declaration],
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<HashSet<String>, error::Error> {
|
||||
let mut function_names = HashSet::new();
|
||||
let mut errs = Vec::new();
|
||||
|
||||
for declaration in declarations {
|
||||
match declaration {
|
||||
Declaration::Function(func) => {
|
||||
let name = func.identifier();
|
||||
if function_names.contains(name.span.str()) {
|
||||
let err = error::Error::from(error::ConflictingFunctionNames {
|
||||
name: name.span.str().to_string(),
|
||||
definition: name.span(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
errs.push(err);
|
||||
}
|
||||
function_names.insert(name.span.str().to_string());
|
||||
}
|
||||
|
||||
Declaration::Import(imp) => match imp.items() {
|
||||
ImportItems::All(_) => {
|
||||
handler.receive(base::Error::Other(
|
||||
"Importing all items is not yet supported.".to_string(),
|
||||
));
|
||||
}
|
||||
ImportItems::Named(items) => {
|
||||
for item in items.elements() {
|
||||
if function_names.contains(item.span.str()) {
|
||||
let err = error::Error::from(error::ConflictingFunctionNames {
|
||||
name: item.span.str().to_string(),
|
||||
definition: item.span(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
errs.push(err);
|
||||
}
|
||||
function_names.insert(item.span.str().to_string());
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
Declaration::Tag(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::option_if_let_else)]
|
||||
if let Some(err) = errs.first() {
|
||||
Err(err.clone())
|
||||
} else {
|
||||
Ok(function_names)
|
||||
}
|
||||
}
|
||||
|
||||
impl Namespace {
|
||||
/// Analyzes the semantics of the namespace.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
let name = self.namespace_name();
|
||||
Self::validate_str(name.str_content().as_ref()).map_err(|invalid_chars| {
|
||||
let err = error::Error::from(InvalidNamespaceName {
|
||||
name: name.clone(),
|
||||
invalid_chars,
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
err
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Declaration {
|
||||
/// Analyzes the semantics of the declaration.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
match self {
|
||||
Self::Function(func) => func.analyze_semantics(function_names, handler),
|
||||
Self::Import(_) | Self::Tag(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Function {
|
||||
/// Analyzes the semantics of the function.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
let macro_names = if let Some(parameters) = self.parameters() {
|
||||
if let Some(incompatible) = self
|
||||
.annotations()
|
||||
.iter()
|
||||
.find(|a| ["tick", "load"].contains(&a.identifier().span.str()))
|
||||
{
|
||||
let err =
|
||||
error::Error::IncompatibleFunctionAnnotation(IncompatibleFunctionAnnotation {
|
||||
span: incompatible.identifier().span(),
|
||||
reason:
|
||||
"functions with the `tick` or `load` annotation cannot have parameters"
|
||||
.to_string(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
parameters
|
||||
.elements()
|
||||
.map(|el| el.span.str().to_string())
|
||||
.collect()
|
||||
} else {
|
||||
HashSet::new()
|
||||
};
|
||||
|
||||
self.block()
|
||||
.analyze_semantics(function_names, ¯o_names, handler)
|
||||
}
|
||||
}
|
||||
|
||||
impl Block {
|
||||
/// Analyzes the semantics of a block.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
let mut errs = Vec::new();
|
||||
for statement in &self.statements {
|
||||
if let Err(err) = match statement {
|
||||
Statement::Block(block) => {
|
||||
block.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
Statement::DocComment(_) | Statement::LiteralCommand(_) => Ok(()),
|
||||
Statement::ExecuteBlock(ex) => {
|
||||
ex.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
Statement::Grouping(group) => {
|
||||
group.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
Statement::Run(run) => run.analyze_semantics(function_names, macro_names, handler),
|
||||
Statement::Semicolon(sem) => {
|
||||
sem.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
} {
|
||||
errs.push(err);
|
||||
};
|
||||
}
|
||||
|
||||
#[expect(clippy::option_if_let_else)]
|
||||
if let Some(err) = errs.first() {
|
||||
Err(err.clone())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlock {
|
||||
/// Analyzes the semantics of the execute block.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
match self {
|
||||
Self::HeadTail(head, tail) => {
|
||||
let head_res = head.analyze_semantics(function_names, macro_names, handler);
|
||||
let tail_res = tail.analyze_semantics(function_names, macro_names, handler);
|
||||
|
||||
if head_res.is_err() {
|
||||
head_res
|
||||
} else {
|
||||
tail_res
|
||||
}
|
||||
}
|
||||
Self::IfElse(cond, then, el) => {
|
||||
let cond_res = cond.analyze_semantics(function_names, macro_names, handler);
|
||||
let then_res = then.analyze_semantics(function_names, macro_names, handler);
|
||||
let else_res = el.analyze_semantics(function_names, macro_names, handler);
|
||||
|
||||
if cond_res.is_err() {
|
||||
cond_res
|
||||
} else if then_res.is_err() {
|
||||
then_res
|
||||
} else {
|
||||
else_res
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Grouping {
|
||||
/// Analyzes the semantics of the grouping.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
self.block()
|
||||
.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
}
|
||||
|
||||
impl Run {
|
||||
/// Analyzes the semantics of the run statement.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
self.expression()
|
||||
.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
}
|
||||
|
||||
impl Semicolon {
|
||||
/// Analyzes the semantics of the semicolon statement.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
match self.expression() {
|
||||
Expression::Primary(Primary::FunctionCall(func)) => {
|
||||
func.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
Expression::Primary(unexpected) => {
|
||||
let error = error::Error::UnexpectedExpression(UnexpectedExpression(
|
||||
Expression::Primary(unexpected.clone()),
|
||||
));
|
||||
handler.receive(error.clone());
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHead {
|
||||
/// Analyzes the semantics of the execute block head.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
match self {
|
||||
Self::Align(align) => align.analyze_semantics(macro_names, handler),
|
||||
Self::Anchored(anchored) => anchored.analyze_semantics(macro_names, handler),
|
||||
Self::As(r#as) => r#as.analyze_semantics(macro_names, handler),
|
||||
Self::At(at) => at.analyze_semantics(macro_names, handler),
|
||||
Self::AsAt(asat) => asat.analyze_semantics(macro_names, handler),
|
||||
Self::Conditional(cond) => cond.analyze_semantics(function_names, macro_names, handler),
|
||||
Self::Facing(facing) => facing.analyze_semantics(macro_names, handler),
|
||||
Self::In(r#in) => r#in.analyze_semantics(macro_names, handler),
|
||||
Self::On(on) => on.analyze_semantics(macro_names, handler),
|
||||
Self::Positioned(pos) => pos.analyze_semantics(macro_names, handler),
|
||||
Self::Rotated(rot) => rot.analyze_semantics(macro_names, handler),
|
||||
Self::Store(store) => store.analyze_semantics(macro_names, handler),
|
||||
Self::Summon(summon) => summon.analyze_semantics(macro_names, handler),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockTail {
|
||||
/// Analyzes the semantics of the execute block tail.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
match self {
|
||||
Self::Block(block) => block.analyze_semantics(function_names, macro_names, handler),
|
||||
Self::ExecuteBlock(_, ex) => ex.analyze_semantics(function_names, macro_names, handler),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Conditional {
|
||||
/// Analyzes the semantics of the conditional.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
self.condition()
|
||||
.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
}
|
||||
|
||||
impl ParenthesizedCondition {
|
||||
/// Analyzes the semantics of the parenthesized condition.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
self.condition
|
||||
.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
}
|
||||
|
||||
impl Condition {
|
||||
/// Analyzes the semantics of the condition.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
match self {
|
||||
Self::Primary(prim) => prim.analyze_semantics(function_names, macro_names, handler),
|
||||
Self::Binary(bin) => bin.analyze_semantics(function_names, macro_names, handler),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Else {
|
||||
/// Analyzes the semantics of the else block.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
self.block()
|
||||
.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
}
|
||||
|
||||
impl MacroStringLiteral {
|
||||
/// Analyzes the semantics of the macro string literal.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
let mut errors = Vec::new();
|
||||
for part in self.parts() {
|
||||
if let MacroStringLiteralPart::MacroUsage { identifier, .. } = part {
|
||||
if !macro_names.contains(identifier.span.str()) {
|
||||
let err = error::Error::UnresolvedMacroUsage(UnresolvedMacroUsage {
|
||||
span: identifier.span(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
errors.push(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::option_if_let_else)]
|
||||
if let Some(err) = errors.first() {
|
||||
Err(err.clone())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Expression {
|
||||
/// Analyzes the semantics of an expression.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
match self {
|
||||
Self::Primary(prim) => prim.analyze_semantics(function_names, macro_names, handler),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Primary {
|
||||
/// Analyzes the semantics of a primary expression.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
match self {
|
||||
Self::FunctionCall(func) => {
|
||||
func.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
Self::Lua(_) | Self::StringLiteral(_) => Ok(()),
|
||||
Self::MacroStringLiteral(literal) => literal.analyze_semantics(macro_names, handler),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FunctionCall {
|
||||
/// Analyzes the semantics of a function call.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
let mut errors = Vec::new();
|
||||
|
||||
if !function_names.contains(self.identifier().span.str()) {
|
||||
let err = error::Error::MissingFunctionDeclaration(
|
||||
MissingFunctionDeclaration::from_context(self.identifier().span(), function_names),
|
||||
);
|
||||
handler.receive(err.clone());
|
||||
errors.push(err);
|
||||
}
|
||||
|
||||
for expression in self
|
||||
.arguments()
|
||||
.iter()
|
||||
.flat_map(super::syntax::syntax_tree::ConnectedList::elements)
|
||||
{
|
||||
if let Err(err) = expression.analyze_semantics(function_names, macro_names, handler) {
|
||||
handler.receive(err.clone());
|
||||
errors.push(err);
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::option_if_let_else)]
|
||||
if let Some(err) = errors.first() {
|
||||
Err(err.clone())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AnyStringLiteral {
|
||||
/// Analyzes the semantics of any string literal.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
match self {
|
||||
Self::StringLiteral(_) => Ok(()),
|
||||
Self::MacroStringLiteral(literal) => literal.analyze_semantics(macro_names, handler),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PrimaryCondition {
|
||||
/// Analyzes the semantics of a primary condition.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
match self {
|
||||
Self::Parenthesized(paren) => {
|
||||
paren.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
Self::StringLiteral(_) => Ok(()),
|
||||
Self::Unary(unary) => unary.analyze_semantics(function_names, macro_names, handler),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UnaryCondition {
|
||||
/// Analyzes the semantics of an unary condition.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
self.operand()
|
||||
.analyze_semantics(function_names, macro_names, handler)
|
||||
}
|
||||
}
|
||||
|
||||
impl BinaryCondition {
|
||||
/// Analyzes the semantics of a binary condition.
|
||||
pub fn analyze_semantics(
|
||||
&self,
|
||||
function_names: &HashSet<String>,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), error::Error> {
|
||||
let a = self
|
||||
.left_operand()
|
||||
.analyze_semantics(function_names, macro_names, handler)
|
||||
.inspect_err(|err| {
|
||||
handler.receive(err.clone());
|
||||
});
|
||||
let b = self
|
||||
.right_operand()
|
||||
.analyze_semantics(function_names, macro_names, handler)
|
||||
.inspect_err(|err| {
|
||||
handler.receive(err.clone());
|
||||
});
|
||||
if a.is_err() {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,289 @@
|
|||
//! Utilities for (de-)serializing
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
marker::PhantomData,
|
||||
sync::{Arc, LazyLock, Mutex, RwLock},
|
||||
};
|
||||
|
||||
use serde::{
|
||||
de::{self, Visitor},
|
||||
ser::SerializeStruct,
|
||||
Deserialize, Serialize,
|
||||
};
|
||||
|
||||
use crate::base::source_file::SourceFile;
|
||||
|
||||
thread_local! {
|
||||
static DEDUPLICATE_SOURCE_FILES: LazyLock<RwLock<bool>> = LazyLock::new(|| RwLock::new(false));
|
||||
|
||||
static SERIALIZE_DATA: LazyLock<Mutex<SerializeData>> =
|
||||
LazyLock::new(|| Mutex::new(SerializeData::default()));
|
||||
|
||||
static DESERIALIZE_DATA: LazyLock<RwLock<Option<DeserializeData>>> =
|
||||
LazyLock::new(|| RwLock::new(None));
|
||||
}
|
||||
|
||||
/// Wrapper to remove duplicate source file data during (de-)serialization
|
||||
#[expect(clippy::module_name_repetitions)]
|
||||
#[derive(Debug)]
|
||||
pub struct SerdeWrapper<T>(pub T);
|
||||
|
||||
impl<T> Serialize for SerdeWrapper<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
DEDUPLICATE_SOURCE_FILES.with(|d| *d.write().unwrap() = true);
|
||||
SERIALIZE_DATA.with(|d| d.lock().unwrap().clear());
|
||||
// hold guard so no other can serialize at the same time in same thread
|
||||
let s = DEDUPLICATE_SOURCE_FILES.with(|d| {
|
||||
let guard = d.read().unwrap();
|
||||
let mut serialized_data = flexbuffers::FlexbufferSerializer::new();
|
||||
self.0
|
||||
.serialize(&mut serialized_data)
|
||||
.map_err(|_| serde::ser::Error::custom("could not buffer serialization"))?;
|
||||
drop(serialized_data);
|
||||
let mut s = serializer.serialize_struct("SerdeWrapper", 3)?;
|
||||
|
||||
SERIALIZE_DATA.with(|d| {
|
||||
s.serialize_field("source_files", &d.lock().unwrap().id_to_source_file)
|
||||
})?;
|
||||
s.serialize_field("data", &self.0)?;
|
||||
drop(guard);
|
||||
Ok(s)
|
||||
})?;
|
||||
|
||||
DEDUPLICATE_SOURCE_FILES.with(|d| *d.write().unwrap() = false);
|
||||
s.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T> Deserialize<'de> for SerdeWrapper<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: de::Deserializer<'de>,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum Field {
|
||||
Data,
|
||||
SourceFiles,
|
||||
}
|
||||
|
||||
struct WrapperVisitor<T>(PhantomData<T>);
|
||||
|
||||
impl<'de, T> Visitor<'de> for WrapperVisitor<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
type Value = SerdeWrapper<T>;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("struct SerdeWrapper")
|
||||
}
|
||||
|
||||
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
|
||||
where
|
||||
V: de::SeqAccess<'de>,
|
||||
{
|
||||
let source_files: BTreeMap<u64, SourceFile> = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::invalid_length(0, &self))?;
|
||||
DESERIALIZE_DATA.with(|d| {
|
||||
*d.write().unwrap() = Some(DeserializeData {
|
||||
id_to_source_file: source_files
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k, Arc::new(v)))
|
||||
.collect(),
|
||||
})
|
||||
});
|
||||
let data = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| de::Error::invalid_length(1, &self))?;
|
||||
|
||||
Ok(SerdeWrapper(data))
|
||||
}
|
||||
|
||||
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
|
||||
where
|
||||
V: de::MapAccess<'de>,
|
||||
{
|
||||
let mut source_files: Option<BTreeMap<u64, SourceFile>> = None;
|
||||
let mut data = None;
|
||||
|
||||
while let Some(key) = map.next_key()? {
|
||||
match key {
|
||||
Field::Data => {
|
||||
if data.is_some() {
|
||||
return Err(de::Error::duplicate_field("data"));
|
||||
}
|
||||
DESERIALIZE_DATA.with(|d| {
|
||||
*d.write().unwrap() =
|
||||
source_files.as_ref().map(|source_files| DeserializeData {
|
||||
id_to_source_file: source_files
|
||||
.iter()
|
||||
.map(|(&k, v)| (k, Arc::new(v.clone())))
|
||||
.collect(),
|
||||
})
|
||||
});
|
||||
data = Some(map.next_value()?);
|
||||
}
|
||||
Field::SourceFiles => {
|
||||
if source_files.is_some() {
|
||||
return Err(de::Error::duplicate_field("source_files"));
|
||||
}
|
||||
source_files = Some(map.next_value()?);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let data = data.ok_or_else(|| de::Error::missing_field("data"))?;
|
||||
Ok(SerdeWrapper(data))
|
||||
}
|
||||
}
|
||||
|
||||
DEDUPLICATE_SOURCE_FILES.with(|d| *d.write().unwrap() = true);
|
||||
DESERIALIZE_DATA.with(|d| *d.write().unwrap() = None);
|
||||
let res = deserializer.deserialize_struct(
|
||||
"SerdeWrapper",
|
||||
&["source_files", "data"],
|
||||
WrapperVisitor(PhantomData::<T>),
|
||||
);
|
||||
DEDUPLICATE_SOURCE_FILES.with(|d| *d.write().unwrap() = false);
|
||||
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
/// Internally used for Serialization
|
||||
#[derive(Debug, Default)]
|
||||
struct SerializeData {
|
||||
id_counter: u64,
|
||||
ptr_to_id: BTreeMap<usize, u64>,
|
||||
id_to_source_file: BTreeMap<u64, SourceFile>,
|
||||
}
|
||||
|
||||
impl SerializeData {
|
||||
fn clear(&mut self) {
|
||||
self.id_counter = 0;
|
||||
self.id_to_source_file.clear();
|
||||
self.ptr_to_id.clear();
|
||||
}
|
||||
|
||||
/// Get id of already stored [`Arc`] or store it and return new id
|
||||
pub fn get_id_of(&mut self, source_file: &Arc<SourceFile>) -> u64 {
|
||||
let ptr = Arc::as_ptr(source_file);
|
||||
if let Some(&id) = self.ptr_to_id.get(&(ptr as usize)) {
|
||||
id
|
||||
} else {
|
||||
let id = self.id_counter;
|
||||
self.id_counter += 1;
|
||||
|
||||
self.ptr_to_id.insert(ptr as usize, id);
|
||||
self.id_to_source_file
|
||||
.insert(id, Arc::unwrap_or_clone(source_file.to_owned()));
|
||||
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct DeserializeData {
|
||||
id_to_source_file: BTreeMap<u64, Arc<SourceFile>>,
|
||||
}
|
||||
|
||||
pub mod source_file {
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{de, Deserialize, Serialize};
|
||||
|
||||
use crate::{base::source_file::SourceFile, serde::DESERIALIZE_DATA};
|
||||
|
||||
use super::{DEDUPLICATE_SOURCE_FILES, SERIALIZE_DATA};
|
||||
|
||||
pub fn serialize<S>(this: &Arc<SourceFile>, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
if DEDUPLICATE_SOURCE_FILES.with(|d| *d.read().unwrap()) {
|
||||
SERIALIZE_DATA.with(|d| {
|
||||
let mut data = d.lock().unwrap();
|
||||
serializer.serialize_u64(data.get_id_of(this))
|
||||
})
|
||||
} else {
|
||||
this.as_ref().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D>(deserializer: D) -> Result<Arc<SourceFile>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
if DEDUPLICATE_SOURCE_FILES.with(|d| *d.read().unwrap()) {
|
||||
let id = u64::deserialize(deserializer)?;
|
||||
Ok(DESERIALIZE_DATA.with(|d| {
|
||||
d.read()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.ok_or_else(|| de::Error::custom("SourceFiles do not have been loaded yet"))?
|
||||
.id_to_source_file
|
||||
.get(&id)
|
||||
.map(Arc::clone)
|
||||
.ok_or_else(|| serde::de::Error::custom("invalid source_file id"))
|
||||
}))?
|
||||
} else {
|
||||
Ok(Arc::new(SourceFile::deserialize(deserializer)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "shulkerbox"))]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
|
||||
use shulkerbox::virtual_fs::{VFile, VFolder};
|
||||
|
||||
use crate::{base::SilentHandler, syntax::syntax_tree::program::ProgramFile};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_serde_wrapper() {
|
||||
let mut vfolder = VFolder::new();
|
||||
let vfile = VFile::Text(r#"namespace "test";"#.to_string());
|
||||
vfolder.add_file("main.shu", vfile);
|
||||
|
||||
let parsed = crate::parse(
|
||||
&SilentHandler::new(),
|
||||
&vfolder,
|
||||
Path::new("main.shu"),
|
||||
"main".to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let wrapper = SerdeWrapper(parsed);
|
||||
|
||||
let serialized = serde_json::to_string_pretty(&wrapper).unwrap();
|
||||
let SerdeWrapper(deserialized) =
|
||||
serde_json::from_str::<SerdeWrapper<ProgramFile>>(&serialized).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
Arc::as_ptr(
|
||||
deserialized
|
||||
.namespace()
|
||||
.namespace_keyword()
|
||||
.span
|
||||
.source_file()
|
||||
),
|
||||
Arc::as_ptr(deserialized.namespace().namespace_name().span.source_file())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -3,20 +3,39 @@
|
|||
use std::fmt::Display;
|
||||
|
||||
use crate::{
|
||||
base::log::{Message, Severity, SourceCodeDisplay},
|
||||
base::{
|
||||
log::{Message, Severity, SourceCodeDisplay},
|
||||
source_file::{SourceElement as _, 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,
|
||||
Declaration,
|
||||
Numeric,
|
||||
StringLiteral,
|
||||
MacroStringLiteral,
|
||||
AnyStringLiteral,
|
||||
Statement,
|
||||
Expression,
|
||||
Type,
|
||||
|
|
@ -24,6 +43,45 @@ 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::MacroStringLiteral => "a macro string literal".to_string(),
|
||||
Self::AnyStringLiteral => "a (macro) 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 +94,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(),
|
||||
|
|
@ -63,6 +109,7 @@ impl Display for UnexpectedSyntax {
|
|||
Some(Token::Numeric(..)) => "a numeric token".to_string(),
|
||||
Some(Token::CommandLiteral(..)) => "a literal command token".to_string(),
|
||||
Some(Token::StringLiteral(..)) => "a string literal token".to_string(),
|
||||
Some(Token::MacroStringLiteral(..)) => "a macro string literal token".to_string(),
|
||||
|
||||
None => "EOF".to_string(),
|
||||
};
|
||||
|
|
@ -75,7 +122,7 @@ impl Display for UnexpectedSyntax {
|
|||
write!(
|
||||
f,
|
||||
"\n{}",
|
||||
SourceCodeDisplay::new(span.span(), Option::<u8>::None)
|
||||
SourceCodeDisplay::new(&span.span(), Option::<u8>::None)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
|
@ -83,10 +130,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;
|
||||
|
|
|
|||
|
|
@ -6,12 +6,18 @@ use enum_as_inner::EnumAsInner;
|
|||
use crate::{
|
||||
base::{self, Handler},
|
||||
lexical::{
|
||||
token::{Identifier, Keyword, KeywordKind, Numeric, Punctuation, StringLiteral, Token},
|
||||
token::{
|
||||
Identifier, Keyword, KeywordKind, MacroStringLiteral, Numeric, Punctuation,
|
||||
StringLiteral, Token,
|
||||
},
|
||||
token_stream::{Delimited, Delimiter, TokenStream, TokenTree},
|
||||
},
|
||||
};
|
||||
|
||||
use super::error::{Error, SyntaxKind, UnexpectedSyntax};
|
||||
use super::{
|
||||
error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax},
|
||||
syntax_tree::AnyStringLiteral,
|
||||
};
|
||||
|
||||
/// 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 +44,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 +71,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 +79,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 +110,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 +125,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 +144,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 +153,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 +176,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 +382,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 +403,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 +424,59 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Expects the next [`Token`] to be an [`MacroStringLiteral`], and returns it.
|
||||
///
|
||||
/// # Errors
|
||||
/// If the next [`Token`] is not an [`MacroStringLiteral`].
|
||||
pub fn parse_macro_string_literal(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> ParseResult<MacroStringLiteral> {
|
||||
match self.next_significant_token() {
|
||||
Reading::Atomic(Token::MacroStringLiteral(literal)) => Ok(literal),
|
||||
found => {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::MacroStringLiteral,
|
||||
found: found.into_token(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Expects the next [`Token`] to be an [`AnyStringLiteral`], and returns it.
|
||||
///
|
||||
/// # Errors
|
||||
/// If the next [`Token`] is not an [`AnyStringLiteral`].
|
||||
pub fn parse_any_string_literal(
|
||||
&mut self,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> ParseResult<AnyStringLiteral> {
|
||||
match self.next_significant_token() {
|
||||
Reading::Atomic(Token::StringLiteral(literal)) => Ok(literal.into()),
|
||||
Reading::Atomic(Token::MacroStringLiteral(literal)) => Ok(literal.into()),
|
||||
found => {
|
||||
let err = Error::UnexpectedSyntax(UnexpectedSyntax {
|
||||
expected: SyntaxKind::AnyStringLiteral,
|
||||
found: found.into_token(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -421,17 +489,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 +514,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 +523,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,45 +11,51 @@ use crate::{
|
|||
base::{
|
||||
self,
|
||||
source_file::{SourceElement, Span},
|
||||
VoidHandler, Handler,
|
||||
Handler, VoidHandler,
|
||||
},
|
||||
lexical::{
|
||||
token::{Punctuation, StringLiteral, Token},
|
||||
token::{Punctuation, Token},
|
||||
token_stream::Delimiter,
|
||||
},
|
||||
syntax::{
|
||||
error::{Error, SyntaxKind, UnexpectedSyntax},
|
||||
error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax},
|
||||
parser::{Parser, Reading},
|
||||
},
|
||||
};
|
||||
|
||||
use super::AnyStringLiteral;
|
||||
|
||||
/// Condition that is viewed as a single entity during precedence parsing.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
/// PrimaryCondition:
|
||||
/// ConditionalPrefix
|
||||
/// UnaryCondition
|
||||
/// | ParenthesizedCondition
|
||||
/// | StringLiteral
|
||||
/// | AnyStringLiteral
|
||||
/// ```
|
||||
#[allow(missing_docs)]
|
||||
#[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),
|
||||
StringLiteral(AnyStringLiteral),
|
||||
}
|
||||
|
||||
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 +94,8 @@ impl BinaryCondition {
|
|||
}
|
||||
}
|
||||
|
||||
/// Operator that is used to combine two conditions.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -126,6 +136,8 @@ impl SourceElement for ConditionalBinaryOperator {
|
|||
}
|
||||
}
|
||||
|
||||
/// Condition that is enclosed in parentheses.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -163,6 +175,8 @@ impl SourceElement for ParenthesizedCondition {
|
|||
}
|
||||
}
|
||||
|
||||
/// Operator that is used to prefix a condition.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -183,16 +197,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 +217,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 +230,8 @@ impl ConditionalPrefix {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a condition in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -241,12 +259,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 +326,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 +347,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 +356,13 @@ impl<'a> Parser<'a> {
|
|||
// string literal
|
||||
Reading::Atomic(Token::StringLiteral(literal)) => {
|
||||
self.forward();
|
||||
Some(PrimaryCondition::StringLiteral(literal))
|
||||
Ok(PrimaryCondition::StringLiteral(literal.into()))
|
||||
}
|
||||
|
||||
// macro string literal
|
||||
Reading::Atomic(Token::MacroStringLiteral(literal)) => {
|
||||
self.forward();
|
||||
Ok(PrimaryCondition::StringLiteral(literal.into()))
|
||||
}
|
||||
|
||||
// parenthesized condition
|
||||
|
|
@ -342,12 +374,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 +393,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,17 +10,22 @@ use crate::{
|
|||
Handler,
|
||||
},
|
||||
lexical::{
|
||||
token::{Identifier, Keyword, KeywordKind, Punctuation, StringLiteral, Token},
|
||||
token::{
|
||||
Identifier, Keyword, KeywordKind, MacroStringLiteral, Punctuation, StringLiteral, Token,
|
||||
},
|
||||
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,11 +47,16 @@ impl SourceElement for Expression {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a primary expression in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
/// Primary:
|
||||
/// FunctionCall
|
||||
/// | StringLiteral
|
||||
/// | MacroStringLiteral
|
||||
/// | LuaCode
|
||||
/// ```
|
||||
#[allow(missing_docs)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -54,6 +64,7 @@ impl SourceElement for Expression {
|
|||
pub enum Primary {
|
||||
FunctionCall(FunctionCall),
|
||||
StringLiteral(StringLiteral),
|
||||
MacroStringLiteral(MacroStringLiteral),
|
||||
Lua(Box<LuaCode>),
|
||||
}
|
||||
|
||||
|
|
@ -62,11 +73,14 @@ impl SourceElement for Primary {
|
|||
match self {
|
||||
Self::FunctionCall(function_call) => function_call.span(),
|
||||
Self::StringLiteral(string_literal) => string_literal.span(),
|
||||
Self::MacroStringLiteral(macro_string_literal) => macro_string_literal.span(),
|
||||
Self::Lua(lua_code) => lua_code.span(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a function call in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -100,6 +114,8 @@ impl SourceElement for FunctionCall {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a lua code block in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ```ebnf
|
||||
|
|
@ -156,12 +172,23 @@ 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.
|
||||
#[expect(clippy::too_many_lines)]
|
||||
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 +196,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 +205,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 +229,15 @@ impl<'a> Parser<'a> {
|
|||
// eat the string literal
|
||||
self.forward();
|
||||
|
||||
Some(Primary::StringLiteral(literal))
|
||||
Ok(Primary::StringLiteral(literal))
|
||||
}
|
||||
|
||||
// macro string literal expression
|
||||
Reading::Atomic(Token::MacroStringLiteral(macro_string_literal)) => {
|
||||
// eat the macro string literal
|
||||
self.forward();
|
||||
|
||||
Ok(Primary::MacroStringLiteral(macro_string_literal))
|
||||
}
|
||||
|
||||
// lua code expression
|
||||
|
|
@ -212,9 +254,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,
|
||||
)?;
|
||||
|
|
@ -234,19 +283,20 @@ impl<'a> Parser<'a> {
|
|||
let combined = first
|
||||
.into_token()
|
||||
.and_then(|first| {
|
||||
first.span().join(&last.into_token().map_or_else(
|
||||
|| first.span().to_owned(),
|
||||
|last| last.span().to_owned(),
|
||||
))
|
||||
first.span().join(
|
||||
&last
|
||||
.into_token()
|
||||
.map_or_else(|| first.span(), |last| last.span()),
|
||||
)
|
||||
})
|
||||
.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 +311,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
//! Contains the syntax tree nodes that represent the structure of the source code.
|
||||
|
||||
use derive_more::derive::From;
|
||||
use getset::Getters;
|
||||
|
||||
use crate::{
|
||||
|
|
@ -9,13 +10,13 @@ use crate::{
|
|||
Handler, VoidHandler,
|
||||
},
|
||||
lexical::{
|
||||
token::{Punctuation, Token},
|
||||
token::{MacroStringLiteral, Punctuation, StringLiteral, Token},
|
||||
token_stream::Delimiter,
|
||||
},
|
||||
syntax::parser::Reading,
|
||||
};
|
||||
|
||||
use super::parser::Parser;
|
||||
use super::{error::ParseResult, parser::Parser};
|
||||
|
||||
pub mod condition;
|
||||
pub mod declaration;
|
||||
|
|
@ -49,6 +50,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.
|
||||
|
|
@ -63,6 +65,29 @@ pub struct DelimitedList<T> {
|
|||
pub close: Punctuation,
|
||||
}
|
||||
|
||||
/// Represents a syntax tree node that can be either a string literal or a macro string literal.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// AnyStringLiteral: StringLiteral | MacroStringLiteral ;
|
||||
/// ```
|
||||
#[allow(missing_docs)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, From)]
|
||||
pub enum AnyStringLiteral {
|
||||
StringLiteral(StringLiteral),
|
||||
MacroStringLiteral(MacroStringLiteral),
|
||||
}
|
||||
|
||||
impl SourceElement for AnyStringLiteral {
|
||||
fn span(&self) -> Span {
|
||||
match self {
|
||||
Self::StringLiteral(string_literal) => string_literal.span(),
|
||||
Self::MacroStringLiteral(macro_string_literal) => macro_string_literal.span(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// Parses a list of elements enclosed by a pair of delimiters, separated by a separator.
|
||||
///
|
||||
|
|
@ -76,9 +101,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 +126,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 +147,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 +160,7 @@ impl<'a> Parser<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
Some(first.map(|first| ConnectedList {
|
||||
Ok(first.map(|first| ConnectedList {
|
||||
first,
|
||||
rest,
|
||||
trailing_separator,
|
||||
|
|
@ -144,7 +169,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 +187,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 +208,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::{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() {
|
||||
|
|
@ -91,24 +108,23 @@ impl<'a> Parser<'a> {
|
|||
// eat the keyword
|
||||
self.forward();
|
||||
|
||||
let namespace_name = self.parse_string_literal(handler).and_then(|name| {
|
||||
Namespace::validate_str(name.str_content().as_ref()).then_some(name)
|
||||
})?;
|
||||
let namespace_name = self.parse_string_literal(handler)?;
|
||||
|
||||
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 +139,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 +153,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,
|
||||
}))
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
//! Execute block statement syntax tree.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use derive_more::From;
|
||||
use enum_as_inner::EnumAsInner;
|
||||
use getset::Getters;
|
||||
|
|
@ -8,22 +10,23 @@ use crate::{
|
|||
base::{
|
||||
self,
|
||||
source_file::{SourceElement, Span},
|
||||
VoidHandler, Handler,
|
||||
Handler, VoidHandler,
|
||||
},
|
||||
lexical::{
|
||||
token::{Keyword, KeywordKind, Punctuation, StringLiteral, Token},
|
||||
token::{Keyword, KeywordKind, Punctuation, Token},
|
||||
token_stream::Delimiter,
|
||||
},
|
||||
syntax::{
|
||||
self,
|
||||
error::{SyntaxKind, UnexpectedSyntax},
|
||||
error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax},
|
||||
parser::{DelimitedTree, Parser, Reading},
|
||||
syntax_tree::condition::ParenthesizedCondition,
|
||||
syntax_tree::{condition::ParenthesizedCondition, AnyStringLiteral},
|
||||
},
|
||||
};
|
||||
|
||||
use super::Block;
|
||||
|
||||
/// Represents an execute block statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// ExecuteBlock:
|
||||
|
|
@ -52,11 +55,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 +114,8 @@ impl SourceElement for ExecuteBlockHead {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents the tail of an execute block statement.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// ExecuteBlockTail:
|
||||
|
|
@ -123,6 +142,8 @@ impl SourceElement for ExecuteBlockTail {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an conditional `if` statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -158,6 +179,8 @@ impl SourceElement for Conditional {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `else` block in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ``` ebnf
|
||||
|
|
@ -190,11 +213,13 @@ impl SourceElement for Else {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `as` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
///
|
||||
/// ```ebnf
|
||||
/// As:
|
||||
/// 'as' '(' StringLiteral ')'
|
||||
/// 'as' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -208,7 +233,7 @@ pub struct As {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the as statement.
|
||||
#[get = "pub"]
|
||||
as_selector: StringLiteral,
|
||||
as_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -225,7 +250,7 @@ impl SourceElement for As {
|
|||
impl As {
|
||||
/// Dissolves the [`As`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.as_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -235,10 +260,12 @@ impl As {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `align` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Align:
|
||||
/// 'align' '(' StringLiteral ')'
|
||||
/// 'align' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
|
||||
|
|
@ -251,7 +278,7 @@ pub struct Align {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the align statement.
|
||||
#[get = "pub"]
|
||||
align_selector: StringLiteral,
|
||||
align_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -269,7 +296,7 @@ impl SourceElement for Align {
|
|||
impl Align {
|
||||
/// Dissolves the [`Align`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.align_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -279,10 +306,12 @@ impl Align {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `anchored` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Anchored:
|
||||
/// 'anchored' '(' StringLiteral ')'
|
||||
/// 'anchored' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -296,7 +325,7 @@ pub struct Anchored {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the anchored statement.
|
||||
#[get = "pub"]
|
||||
anchored_selector: StringLiteral,
|
||||
anchored_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -312,7 +341,7 @@ impl SourceElement for Anchored {
|
|||
impl Anchored {
|
||||
/// Dissolves the [`Anchored`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.anchored_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -322,10 +351,12 @@ impl Anchored {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `asat` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// AsAt:
|
||||
/// 'asat' '(' StringLiteral ')'
|
||||
/// 'asat' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -339,7 +370,7 @@ pub struct AsAt {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the asat statement.
|
||||
#[get = "pub"]
|
||||
asat_selector: StringLiteral,
|
||||
asat_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -355,7 +386,7 @@ impl SourceElement for AsAt {
|
|||
impl AsAt {
|
||||
/// Dissolves the [`AsAt`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.asat_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -365,10 +396,12 @@ impl AsAt {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `at` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// At:
|
||||
/// 'at' '(' StringLiteral ')'
|
||||
/// 'at' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -382,7 +415,7 @@ pub struct At {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the at statement.
|
||||
#[get = "pub"]
|
||||
at_selector: StringLiteral,
|
||||
at_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -398,7 +431,7 @@ impl SourceElement for At {
|
|||
impl At {
|
||||
/// Dissolves the [`At`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.at_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -408,10 +441,12 @@ impl At {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a `facing` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Facing:
|
||||
/// 'facing' '(' StringLiteral ')'
|
||||
/// 'facing' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -425,7 +460,7 @@ pub struct Facing {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the facing statement.
|
||||
#[get = "pub"]
|
||||
facing_selector: StringLiteral,
|
||||
facing_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -441,7 +476,7 @@ impl SourceElement for Facing {
|
|||
impl Facing {
|
||||
/// Dissolves the [`Facing`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.facing_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -451,10 +486,12 @@ impl Facing {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `in` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// In:
|
||||
/// 'in' '(' StringLiteral ')'
|
||||
/// 'in' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -468,7 +505,7 @@ pub struct In {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the in statement.
|
||||
#[get = "pub"]
|
||||
in_selector: StringLiteral,
|
||||
in_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -484,7 +521,7 @@ impl SourceElement for In {
|
|||
impl In {
|
||||
/// Dissolves the [`In`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.in_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -494,10 +531,12 @@ impl In {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents an `on` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// On:
|
||||
/// 'on' '(' StringLiteral ')'
|
||||
/// 'on' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -511,7 +550,7 @@ pub struct On {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the on statement.
|
||||
#[get = "pub"]
|
||||
on_selector: StringLiteral,
|
||||
on_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -527,7 +566,7 @@ impl SourceElement for On {
|
|||
impl On {
|
||||
/// Dissolves the [`On`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.on_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -537,10 +576,12 @@ impl On {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a `positioned` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Positioned:
|
||||
/// 'positioned' '(' StringLiteral ')'
|
||||
/// 'positioned' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -554,7 +595,7 @@ pub struct Positioned {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the positioned statement.
|
||||
#[get = "pub"]
|
||||
positioned_selector: StringLiteral,
|
||||
positioned_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -570,7 +611,7 @@ impl SourceElement for Positioned {
|
|||
impl Positioned {
|
||||
/// Dissolves the [`Positioned`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.positioned_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -580,10 +621,12 @@ impl Positioned {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a `rotated` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Rotated:
|
||||
/// 'rotated' '(' StringLiteral ')'
|
||||
/// 'rotated' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -597,7 +640,7 @@ pub struct Rotated {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the rotated statement.
|
||||
#[get = "pub"]
|
||||
rotated_selector: StringLiteral,
|
||||
rotated_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -613,7 +656,7 @@ impl SourceElement for Rotated {
|
|||
impl Rotated {
|
||||
/// Dissolves the [`Rotated`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.rotated_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -623,10 +666,12 @@ impl Rotated {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a `store` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Store:
|
||||
/// 'store' '(' StringLiteral ')'
|
||||
/// 'store' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -640,7 +685,7 @@ pub struct Store {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the store statement.
|
||||
#[get = "pub"]
|
||||
store_selector: StringLiteral,
|
||||
store_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -656,7 +701,7 @@ impl SourceElement for Store {
|
|||
impl Store {
|
||||
/// Dissolves the [`Store`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.store_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -666,10 +711,12 @@ impl Store {
|
|||
}
|
||||
}
|
||||
|
||||
/// Represents a `summon` execute statement in the syntax tree.
|
||||
///
|
||||
/// Syntax Synopsis:
|
||||
/// ```ebnf
|
||||
/// Summon:
|
||||
/// 'summon' '(' StringLiteral ')'
|
||||
/// 'summon' '(' AnyStringLiteral ')'
|
||||
/// ;
|
||||
/// ```
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
|
@ -683,7 +730,7 @@ pub struct Summon {
|
|||
open_paren: Punctuation,
|
||||
/// The selector of the summon statement.
|
||||
#[get = "pub"]
|
||||
summon_selector: StringLiteral,
|
||||
summon_selector: AnyStringLiteral,
|
||||
/// The close parenthesis.
|
||||
#[get = "pub"]
|
||||
close_paren: Punctuation,
|
||||
|
|
@ -699,7 +746,7 @@ impl SourceElement for Summon {
|
|||
impl Summon {
|
||||
/// Dissolves the [`Summon`] into its components.
|
||||
#[must_use]
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) {
|
||||
pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
|
||||
(
|
||||
self.summon_keyword,
|
||||
self.open_paren,
|
||||
|
|
@ -711,10 +758,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 +790,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 +809,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,
|
||||
))
|
||||
|
|
@ -773,15 +827,16 @@ impl<'a> Parser<'a> {
|
|||
let argument = match self.stop_at_significant() {
|
||||
Reading::IntoDelimited(punc) if punc.punctuation == '(' => self.step_into(
|
||||
Delimiter::Parenthesis,
|
||||
|parser| parser.parse_string_literal(handler),
|
||||
|parser| parser.parse_any_string_literal(handler),
|
||||
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 +844,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 +862,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 +871,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 +881,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -841,9 +898,9 @@ impl<'a> Parser<'a> {
|
|||
|
||||
fn head_from_keyword(
|
||||
keyword: Keyword,
|
||||
argument: DelimitedTree<StringLiteral>,
|
||||
) -> Option<ExecuteBlockHead> {
|
||||
Some(match keyword.keyword {
|
||||
argument: DelimitedTree<AnyStringLiteral>,
|
||||
) -> ParseResult<ExecuteBlockHead> {
|
||||
Ok(match keyword.keyword {
|
||||
KeywordKind::Align => Align {
|
||||
align_keyword: keyword,
|
||||
open_paren: argument.open,
|
||||
|
|
@ -931,3 +988,91 @@ fn head_from_keyword(
|
|||
_ => unreachable!("The keyword is not a valid execute block head."),
|
||||
})
|
||||
}
|
||||
|
||||
/// Trait for the execute block head items with a [`AnyStringLiteral`] as their selector.
|
||||
pub trait ExecuteBlockHeadItem {
|
||||
/// Returns a reference to the selector of the execute block head item.
|
||||
fn selector(&self) -> &AnyStringLiteral;
|
||||
|
||||
/// Analyzes the semantics of the execute block head item.
|
||||
#[expect(clippy::missing_errors_doc)]
|
||||
fn analyze_semantics(
|
||||
&self,
|
||||
macro_names: &HashSet<String>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> Result<(), crate::semantic::error::Error> {
|
||||
self.selector().analyze_semantics(macro_names, handler)
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for Align {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.align_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for Anchored {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.anchored_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for As {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.as_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for At {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.at_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for AsAt {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.asat_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for Facing {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.facing_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for In {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.in_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for On {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.on_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for Positioned {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.positioned_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for Rotated {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.rotated_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for Store {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.store_selector
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecuteBlockHeadItem for Summon {
|
||||
fn selector(&self) -> &AnyStringLiteral {
|
||||
&self.summon_selector
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,19 @@
|
|||
//! Conversion functions for converting between tokens/ast-nodes and [`shulkerbox`] types
|
||||
|
||||
use shulkerbox::datapack::Condition as DpCondition;
|
||||
use shulkerbox::{
|
||||
datapack::Condition as DpCondition,
|
||||
util::{MacroString, MacroStringPart},
|
||||
};
|
||||
|
||||
use crate::syntax::syntax_tree::condition::{
|
||||
use crate::{
|
||||
lexical::token::{MacroStringLiteral, MacroStringLiteralPart},
|
||||
syntax::syntax_tree::{
|
||||
condition::{
|
||||
BinaryCondition, Condition, ConditionalBinaryOperator, ConditionalPrefixOperator,
|
||||
PrimaryCondition,
|
||||
},
|
||||
AnyStringLiteral,
|
||||
},
|
||||
};
|
||||
|
||||
impl From<Condition> for DpCondition {
|
||||
|
|
@ -19,11 +28,9 @@ impl From<Condition> for DpCondition {
|
|||
impl From<PrimaryCondition> for DpCondition {
|
||||
fn from(value: PrimaryCondition) -> Self {
|
||||
match value {
|
||||
PrimaryCondition::StringLiteral(literal) => {
|
||||
Self::Atom(literal.str_content().to_string())
|
||||
}
|
||||
PrimaryCondition::StringLiteral(literal) => Self::Atom(literal.into()),
|
||||
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()))
|
||||
}
|
||||
|
|
@ -32,6 +39,56 @@ impl From<PrimaryCondition> for DpCondition {
|
|||
}
|
||||
}
|
||||
|
||||
impl From<&AnyStringLiteral> for MacroString {
|
||||
fn from(value: &AnyStringLiteral) -> Self {
|
||||
match value {
|
||||
AnyStringLiteral::StringLiteral(literal) => Self::from(literal.str_content().as_ref()),
|
||||
AnyStringLiteral::MacroStringLiteral(literal) => Self::from(literal),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AnyStringLiteral> for MacroString {
|
||||
fn from(value: AnyStringLiteral) -> Self {
|
||||
Self::from(&value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&MacroStringLiteral> for MacroString {
|
||||
fn from(value: &MacroStringLiteral) -> Self {
|
||||
if value
|
||||
.parts()
|
||||
.iter()
|
||||
.any(|p| matches!(p, MacroStringLiteralPart::MacroUsage { .. }))
|
||||
{
|
||||
Self::MacroString(
|
||||
value
|
||||
.parts()
|
||||
.iter()
|
||||
.map(|part| match part {
|
||||
MacroStringLiteralPart::Text(span) => MacroStringPart::String(
|
||||
crate::util::unescape_macro_string(span.str()).to_string(),
|
||||
),
|
||||
MacroStringLiteralPart::MacroUsage { identifier, .. } => {
|
||||
MacroStringPart::MacroUsage(
|
||||
super::util::identifier_to_macro(identifier.span.str()).to_string(),
|
||||
)
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
} else {
|
||||
Self::String(value.str_content())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MacroStringLiteral> for MacroString {
|
||||
fn from(value: MacroStringLiteral) -> Self {
|
||||
Self::from(&value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BinaryCondition> for DpCondition {
|
||||
fn from(value: BinaryCondition) -> Self {
|
||||
let (lhs, op, rhs) = value.dissolve();
|
||||
|
|
|
|||
|
|
@ -1,36 +1,79 @@
|
|||
//! 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::{
|
||||
log::{Message, Severity, SourceCodeDisplay},
|
||||
source_file::{SourceElement, Span},
|
||||
source_file::Span,
|
||||
},
|
||||
syntax::syntax_tree::expression::Expression,
|
||||
semantic::error::{ConflictingFunctionNames, InvalidFunctionArguments, UnexpectedExpression},
|
||||
};
|
||||
|
||||
use super::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),
|
||||
#[error(transparent)]
|
||||
InvalidFunctionArguments(#[from] InvalidFunctionArguments),
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
#[cfg_attr(not(feature = "shulkerbox"), expect(unused))]
|
||||
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 +84,65 @@ 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,60 @@ 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).inspect_err(|err| {
|
||||
handler.receive(err.clone());
|
||||
})
|
||||
}
|
||||
|
||||
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 +118,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,9 +1,14 @@
|
|||
//! The transpile module is responsible for transpiling the abstract syntax tree into a data pack.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{base::source_file::Span, syntax::syntax_tree::statement::Statement};
|
||||
|
||||
#[doc(hidden)]
|
||||
#[cfg(feature = "shulkerbox")]
|
||||
pub mod conversions;
|
||||
mod error;
|
||||
|
||||
#[doc(inline)]
|
||||
#[allow(clippy::module_name_repetitions)]
|
||||
pub use error::{TranspileError, TranspileResult};
|
||||
|
|
@ -11,7 +16,18 @@ pub use error::{TranspileError, TranspileResult};
|
|||
pub mod lua;
|
||||
#[cfg(feature = "shulkerbox")]
|
||||
mod transpiler;
|
||||
#[doc(inline)]
|
||||
#[cfg(feature = "shulkerbox")]
|
||||
#[cfg_attr(feature = "shulkerbox", doc(inline))]
|
||||
pub use transpiler::Transpiler;
|
||||
|
||||
mod util;
|
||||
pub mod util;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct FunctionData {
|
||||
pub(super) namespace: String,
|
||||
pub(super) identifier_span: Span,
|
||||
pub(super) parameters: Vec<String>,
|
||||
pub(super) statements: Vec<Statement>,
|
||||
pub(super) public: bool,
|
||||
pub(super) annotations: HashMap<String, Option<String>>,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
//! Transpiler for `ShulkerScript`
|
||||
//! Transpiler for `Shulkerscript`
|
||||
|
||||
use chksum_md5 as md5;
|
||||
use std::{collections::HashMap, iter, sync::RwLock};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
ops::Deref,
|
||||
};
|
||||
|
||||
use shulkerbox::datapack::{self, Command, Datapack, Execute};
|
||||
|
||||
|
|
@ -11,6 +14,7 @@ use crate::{
|
|||
source_file::{SourceElement, Span},
|
||||
Handler,
|
||||
},
|
||||
semantic::error::{ConflictingFunctionNames, InvalidFunctionArguments, UnexpectedExpression},
|
||||
syntax::syntax_tree::{
|
||||
declaration::{Declaration, ImportItems},
|
||||
expression::{Expression, FunctionCall, Primary},
|
||||
|
|
@ -23,25 +27,21 @@ use crate::{
|
|||
transpile::error::MissingFunctionDeclaration,
|
||||
};
|
||||
|
||||
use super::error::{TranspileError, TranspileResult};
|
||||
use super::{
|
||||
error::{TranspileError, TranspileResult},
|
||||
FunctionData,
|
||||
};
|
||||
|
||||
/// 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>>,
|
||||
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>>,
|
||||
functions: BTreeMap<(String, String), FunctionData>,
|
||||
/// Key: (program identifier, function name), Value: (function location, public)
|
||||
function_locations: HashMap<(String, String), (String, bool)>,
|
||||
/// Key: alias, Value: target
|
||||
aliases: HashMap<(String, String), (String, String)>,
|
||||
}
|
||||
|
||||
impl Transpiler {
|
||||
|
|
@ -50,9 +50,9 @@ impl Transpiler {
|
|||
pub fn new(pack_format: u8) -> Self {
|
||||
Self {
|
||||
datapack: shulkerbox::datapack::Datapack::new(pack_format),
|
||||
functions: RwLock::new(HashMap::new()),
|
||||
function_locations: RwLock::new(HashMap::new()),
|
||||
aliases: RwLock::new(HashMap::new()),
|
||||
functions: BTreeMap::new(),
|
||||
function_locations: HashMap::new(),
|
||||
aliases: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -80,9 +80,8 @@ impl Transpiler {
|
|||
|
||||
let mut always_transpile_functions = Vec::new();
|
||||
|
||||
#[allow(clippy::significant_drop_in_scrutinee)]
|
||||
{
|
||||
let functions = self.functions.read().unwrap();
|
||||
let functions = &mut self.functions;
|
||||
for (_, data) in functions.iter() {
|
||||
let always_transpile_function = data.annotations.contains_key("tick")
|
||||
|| data.annotations.contains_key("load")
|
||||
|
|
@ -99,7 +98,7 @@ impl Transpiler {
|
|||
);
|
||||
|
||||
for identifier_span in always_transpile_functions {
|
||||
self.get_or_transpile_function(&identifier_span, handler)?;
|
||||
self.get_or_transpile_function(&identifier_span, None, handler)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
|
@ -124,7 +123,7 @@ impl Transpiler {
|
|||
&mut self,
|
||||
declaration: &Declaration,
|
||||
namespace: &Namespace,
|
||||
_handler: &impl Handler<base::Error>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) {
|
||||
let program_identifier = declaration.span().source_file().identifier().clone();
|
||||
match declaration {
|
||||
|
|
@ -144,11 +143,21 @@ impl Transpiler {
|
|||
)
|
||||
})
|
||||
.collect();
|
||||
self.functions.write().unwrap().insert(
|
||||
#[allow(clippy::significant_drop_tightening)]
|
||||
self.functions.insert(
|
||||
(program_identifier, name),
|
||||
FunctionData {
|
||||
namespace: namespace.namespace_name().str_content().to_string(),
|
||||
identifier_span: identifier_span.clone(),
|
||||
parameters: function
|
||||
.parameters()
|
||||
.as_ref()
|
||||
.map(|l| {
|
||||
l.elements()
|
||||
.map(|i| i.span.str().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
statements,
|
||||
public: function.is_public(),
|
||||
annotations,
|
||||
|
|
@ -160,15 +169,16 @@ impl Transpiler {
|
|||
let import_identifier =
|
||||
super::util::calculate_import_identifier(&program_identifier, path);
|
||||
|
||||
let mut aliases = self.aliases.write().unwrap();
|
||||
let aliases = &mut self.aliases;
|
||||
|
||||
match import.items() {
|
||||
ImportItems::All(_) => todo!("Importing all items is not yet supported."),
|
||||
ImportItems::All(_) => {
|
||||
handler.receive(base::Error::Other(
|
||||
"Importing all items is not yet supported.".to_string(),
|
||||
));
|
||||
}
|
||||
ImportItems::Named(list) => {
|
||||
let items = iter::once(list.first())
|
||||
.chain(list.rest().iter().map(|(_, ident)| ident));
|
||||
|
||||
for item in items {
|
||||
for item in list.elements() {
|
||||
let name = item.span.str();
|
||||
aliases.insert(
|
||||
(program_identifier.clone(), name.to_string()),
|
||||
|
|
@ -178,6 +188,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);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -188,19 +214,17 @@ impl Transpiler {
|
|||
fn get_or_transpile_function(
|
||||
&mut self,
|
||||
identifier_span: &Span,
|
||||
arguments: Option<&[&Expression]>,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> TranspileResult<String> {
|
||||
) -> TranspileResult<(String, Option<BTreeMap<String, String>>)> {
|
||||
let program_identifier = identifier_span.source_file().identifier();
|
||||
let program_query = (
|
||||
program_identifier.to_string(),
|
||||
identifier_span.str().to_string(),
|
||||
);
|
||||
let alias_query = {
|
||||
let aliases = self.aliases.read().unwrap();
|
||||
aliases.get(&program_query).cloned()
|
||||
};
|
||||
let alias_query = self.aliases.get(&program_query).cloned();
|
||||
let already_transpiled = {
|
||||
let locations = self.function_locations.read().unwrap();
|
||||
let locations = &self.function_locations;
|
||||
locations
|
||||
.get(&program_query)
|
||||
.or_else(|| {
|
||||
|
|
@ -214,7 +238,7 @@ impl Transpiler {
|
|||
tracing::trace!("Function not transpiled yet, transpiling.");
|
||||
|
||||
let statements = {
|
||||
let functions = self.functions.read().unwrap();
|
||||
let functions = &self.functions;
|
||||
let function_data = functions
|
||||
.get(&program_query)
|
||||
.or_else(|| {
|
||||
|
|
@ -224,18 +248,20 @@ 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
|
||||
})?;
|
||||
|
||||
function_data.statements.clone()
|
||||
};
|
||||
let commands = self.transpile_function(&statements, program_identifier, handler)?;
|
||||
|
||||
let functions = self.functions.read().unwrap();
|
||||
let functions = &self.functions;
|
||||
let function_data = functions
|
||||
.get(&program_query)
|
||||
.or_else(|| {
|
||||
|
|
@ -244,10 +270,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 +287,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!(
|
||||
|
|
@ -283,7 +319,7 @@ impl Transpiler {
|
|||
self.datapack.add_load(&function_location);
|
||||
}
|
||||
|
||||
self.function_locations.write().unwrap().insert(
|
||||
self.function_locations.insert(
|
||||
(
|
||||
program_identifier.to_string(),
|
||||
identifier_span.str().to_string(),
|
||||
|
|
@ -292,19 +328,96 @@ impl Transpiler {
|
|||
);
|
||||
}
|
||||
|
||||
let locations = self.function_locations.read().unwrap();
|
||||
locations
|
||||
let parameters = {
|
||||
let function_data = self
|
||||
.functions
|
||||
.get(&program_query)
|
||||
.or_else(|| alias_query.and_then(|q| locations.get(&q).filter(|(_, p)| *p)))
|
||||
.or_else(|| {
|
||||
alias_query
|
||||
.clone()
|
||||
.and_then(|q| self.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(),
|
||||
&self.functions,
|
||||
),
|
||||
);
|
||||
handler.receive(error.clone());
|
||||
error
|
||||
})?;
|
||||
|
||||
function_data.parameters.clone()
|
||||
};
|
||||
|
||||
let function_location = self
|
||||
.function_locations
|
||||
.get(&program_query)
|
||||
.or_else(|| {
|
||||
alias_query.and_then(|q| self.function_locations.get(&q).filter(|(_, p)| *p))
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
let error = TranspileError::MissingFunctionDeclaration(
|
||||
MissingFunctionDeclaration::from_context(
|
||||
identifier_span.clone(),
|
||||
&self.functions,
|
||||
),
|
||||
);
|
||||
handler.receive(error.clone());
|
||||
error
|
||||
})
|
||||
.map(|(s, _)| s.to_owned())
|
||||
.map(|(s, _)| s.to_owned())?;
|
||||
|
||||
let arg_count = arguments.iter().flat_map(|x| x.iter()).count();
|
||||
if arg_count != parameters.len() {
|
||||
let err = TranspileError::InvalidFunctionArguments(InvalidFunctionArguments {
|
||||
expected: parameters.len(),
|
||||
actual: arg_count,
|
||||
span: identifier_span.clone(),
|
||||
});
|
||||
handler.receive(err.clone());
|
||||
Err(err)
|
||||
} else if arg_count > 0 {
|
||||
let mut compiled_args = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
for expression in arguments.iter().flat_map(|x| x.iter()) {
|
||||
let value = match expression {
|
||||
Expression::Primary(Primary::FunctionCall(func)) => self
|
||||
.transpile_function_call(func, handler)
|
||||
.map(|cmd| match cmd {
|
||||
Command::Raw(s) => s,
|
||||
_ => unreachable!("Function call should always return a raw command"),
|
||||
}),
|
||||
Expression::Primary(Primary::Lua(lua)) => {
|
||||
lua.eval_string(handler).map(Option::unwrap_or_default)
|
||||
}
|
||||
Expression::Primary(Primary::StringLiteral(string)) => {
|
||||
Ok(string.str_content().to_string())
|
||||
}
|
||||
Expression::Primary(Primary::MacroStringLiteral(literal)) => {
|
||||
Ok(literal.str_content())
|
||||
}
|
||||
};
|
||||
|
||||
match value {
|
||||
Ok(value) => {
|
||||
compiled_args.push(value);
|
||||
}
|
||||
Err(err) => {
|
||||
compiled_args.push(String::new());
|
||||
errs.push(err.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(err) = errs.first() {
|
||||
return Err(err.clone());
|
||||
}
|
||||
let function_args = parameters.into_iter().zip(compiled_args).collect();
|
||||
Ok((function_location, Some(function_args)))
|
||||
} else {
|
||||
Ok((function_location, None))
|
||||
}
|
||||
}
|
||||
|
||||
fn transpile_function(
|
||||
|
|
@ -349,8 +462,11 @@ impl Transpiler {
|
|||
Expression::Primary(Primary::StringLiteral(string)) => {
|
||||
Ok(Some(Command::Raw(string.str_content().to_string())))
|
||||
}
|
||||
Expression::Primary(Primary::MacroStringLiteral(string)) => {
|
||||
Ok(Some(Command::UsesMacro(string.into())))
|
||||
}
|
||||
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 +507,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)
|
||||
}
|
||||
|
|
@ -404,8 +522,29 @@ impl Transpiler {
|
|||
func: &FunctionCall,
|
||||
handler: &impl Handler<base::Error>,
|
||||
) -> TranspileResult<Command> {
|
||||
let location = self.get_or_transpile_function(&func.identifier().span, handler)?;
|
||||
Ok(Command::Raw(format!("function {location}")))
|
||||
let arguments = func
|
||||
.arguments()
|
||||
.as_ref()
|
||||
.map(|l| l.elements().map(Deref::deref).collect::<Vec<_>>());
|
||||
let (location, arguments) =
|
||||
self.get_or_transpile_function(&func.identifier().span, arguments.as_deref(), handler)?;
|
||||
let mut function_call = format!("function {location}");
|
||||
if let Some(arguments) = arguments {
|
||||
use std::fmt::Write;
|
||||
let arguments = arguments
|
||||
.iter()
|
||||
.map(|(ident, v)| {
|
||||
format!(
|
||||
r#"{macro_name}:"{escaped}""#,
|
||||
macro_name = super::util::identifier_to_macro(ident),
|
||||
escaped = crate::util::escape_str(v)
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
write!(function_call, " {{{arguments}}}").unwrap();
|
||||
}
|
||||
Ok(Command::Raw(function_call))
|
||||
}
|
||||
|
||||
fn transpile_execute_block(
|
||||
|
|
@ -568,53 +707,53 @@ impl Transpiler {
|
|||
None
|
||||
}
|
||||
}
|
||||
ExecuteBlockHead::As(as_) => {
|
||||
let selector = as_.as_selector().str_content();
|
||||
tail.map(|tail| Execute::As(selector.to_string(), Box::new(tail)))
|
||||
ExecuteBlockHead::As(r#as) => {
|
||||
let selector = r#as.as_selector();
|
||||
tail.map(|tail| Execute::As(selector.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::At(at) => {
|
||||
let selector = at.at_selector().str_content();
|
||||
tail.map(|tail| Execute::At(selector.to_string(), Box::new(tail)))
|
||||
let selector = at.at_selector();
|
||||
tail.map(|tail| Execute::At(selector.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::Align(align) => {
|
||||
let align = align.align_selector().str_content();
|
||||
tail.map(|tail| Execute::Align(align.to_string(), Box::new(tail)))
|
||||
let align = align.align_selector();
|
||||
tail.map(|tail| Execute::Align(align.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::Anchored(anchored) => {
|
||||
let anchor = anchored.anchored_selector().str_content();
|
||||
tail.map(|tail| Execute::Anchored(anchor.to_string(), Box::new(tail)))
|
||||
let anchor = anchored.anchored_selector();
|
||||
tail.map(|tail| Execute::Anchored(anchor.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::In(in_) => {
|
||||
let dimension = in_.in_selector().str_content();
|
||||
tail.map(|tail| Execute::In(dimension.to_string(), Box::new(tail)))
|
||||
ExecuteBlockHead::In(r#in) => {
|
||||
let dimension = r#in.in_selector();
|
||||
tail.map(|tail| Execute::In(dimension.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::Positioned(positioned) => {
|
||||
let position = positioned.positioned_selector().str_content();
|
||||
tail.map(|tail| Execute::Positioned(position.to_string(), Box::new(tail)))
|
||||
let position = positioned.positioned_selector();
|
||||
tail.map(|tail| Execute::Positioned(position.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::Rotated(rotated) => {
|
||||
let rotation = rotated.rotated_selector().str_content();
|
||||
tail.map(|tail| Execute::Rotated(rotation.to_string(), Box::new(tail)))
|
||||
let rotation = rotated.rotated_selector();
|
||||
tail.map(|tail| Execute::Rotated(rotation.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::Facing(facing) => {
|
||||
let facing = facing.facing_selector().str_content();
|
||||
tail.map(|tail| Execute::Facing(facing.to_string(), Box::new(tail)))
|
||||
let facing = facing.facing_selector();
|
||||
tail.map(|tail| Execute::Facing(facing.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::AsAt(as_at) => {
|
||||
let selector = as_at.asat_selector().str_content();
|
||||
tail.map(|tail| Execute::AsAt(selector.to_string(), Box::new(tail)))
|
||||
let selector = as_at.asat_selector();
|
||||
tail.map(|tail| Execute::AsAt(selector.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::On(on) => {
|
||||
let dimension = on.on_selector().str_content();
|
||||
tail.map(|tail| Execute::On(dimension.to_string(), Box::new(tail)))
|
||||
let dimension = on.on_selector();
|
||||
tail.map(|tail| Execute::On(dimension.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::Store(store) => {
|
||||
let store = store.store_selector().str_content();
|
||||
tail.map(|tail| Execute::Store(store.to_string(), Box::new(tail)))
|
||||
let store = store.store_selector();
|
||||
tail.map(|tail| Execute::Store(store.into(), Box::new(tail)))
|
||||
}
|
||||
ExecuteBlockHead::Summon(summon) => {
|
||||
let entity = summon.summon_selector().str_content();
|
||||
tail.map(|tail| Execute::Summon(entity.to_string(), Box::new(tail)))
|
||||
let entity = summon.summon_selector();
|
||||
tail.map(|tail| Execute::Summon(entity.into(), Box::new(tail)))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
//! Utility methods for transpiling
|
||||
|
||||
#[cfg(feature = "shulkerbox")]
|
||||
use chksum_md5 as md5;
|
||||
|
||||
fn normalize_program_identifier<S>(identifier: S) -> String
|
||||
where
|
||||
S: AsRef<str>,
|
||||
|
|
@ -19,6 +24,8 @@ where
|
|||
.join("/")
|
||||
}
|
||||
|
||||
/// Calculate the identifier to import the function based on the current identifier and the import path
|
||||
#[must_use]
|
||||
pub fn calculate_import_identifier<S, T>(current_identifier: S, import_path: T) -> String
|
||||
where
|
||||
S: AsRef<str>,
|
||||
|
|
@ -32,3 +39,25 @@ where
|
|||
normalize_program_identifier(identifier_elements.join("/") + "/" + import_path.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// Transforms an identifier to a macro name that only contains `a-zA-Z0-9_`.
|
||||
#[cfg(feature = "shulkerbox")]
|
||||
#[must_use]
|
||||
pub fn identifier_to_macro(ident: &str) -> std::borrow::Cow<str> {
|
||||
if ident.contains("__")
|
||||
|| ident
|
||||
.chars()
|
||||
.any(|c| !(c == '_' && c.is_ascii_alphanumeric()))
|
||||
{
|
||||
let new_ident = ident
|
||||
.chars()
|
||||
.filter(|c| *c == '_' || c.is_ascii_alphanumeric())
|
||||
.collect::<String>();
|
||||
|
||||
let chksum = md5::hash(ident).to_hex_lowercase();
|
||||
|
||||
std::borrow::Cow::Owned(new_ident + "__" + &chksum[..8])
|
||||
} else {
|
||||
std::borrow::Cow::Borrowed(ident)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,82 @@
|
|||
//! Utility functions for the `Shulkerscript` language.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// Escapes `"` and `\` in a string.
|
||||
#[must_use]
|
||||
pub fn escape_str(s: &str) -> Cow<str> {
|
||||
if s.contains('"') || s.contains('\\') {
|
||||
let mut escaped = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' => escaped.push_str("\\\""),
|
||||
'\\' => escaped.push_str("\\\\"),
|
||||
_ => escaped.push(c),
|
||||
}
|
||||
}
|
||||
Cow::Owned(escaped)
|
||||
} else {
|
||||
Cow::Borrowed(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// Unescapes '\`', `\`, `\n`, `\r` and `\t` in a string.
|
||||
#[must_use]
|
||||
pub fn unescape_macro_string(s: &str) -> Cow<str> {
|
||||
if s.contains('\\') || s.contains('`') {
|
||||
Cow::Owned(
|
||||
s.replace("\\n", "\n")
|
||||
.replace("\\r", "\r")
|
||||
.replace("\\t", "\t")
|
||||
.replace("\\`", "`")
|
||||
.replace("\\\\", "\\"),
|
||||
)
|
||||
} else {
|
||||
Cow::Borrowed(s)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_escape_str() {
|
||||
assert_eq!(escape_str("Hello, world!"), "Hello, world!");
|
||||
assert_eq!(escape_str(r#"Hello, "world"!"#), r#"Hello, \"world\"!"#);
|
||||
assert_eq!(escape_str(r"Hello, \world\!"), r"Hello, \\world\\!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unescape_macro_string() {
|
||||
assert_eq!(unescape_macro_string("Hello, world!"), "Hello, world!");
|
||||
assert_eq!(
|
||||
unescape_macro_string(r#"Hello, "world"!"#),
|
||||
r#"Hello, "world"!"#
|
||||
);
|
||||
assert_eq!(
|
||||
unescape_macro_string(r"Hello, \world\!"),
|
||||
r"Hello, \world\!"
|
||||
);
|
||||
assert_eq!(
|
||||
unescape_macro_string(r"Hello, \nworld\!"),
|
||||
"Hello, \nworld\\!"
|
||||
);
|
||||
assert_eq!(
|
||||
unescape_macro_string(r"Hello, \rworld\!"),
|
||||
"Hello, \rworld\\!"
|
||||
);
|
||||
assert_eq!(
|
||||
unescape_macro_string(r"Hello, \tworld\!"),
|
||||
"Hello, \tworld\\!"
|
||||
);
|
||||
assert_eq!(
|
||||
unescape_macro_string(r"Hello, \`world\!"),
|
||||
r"Hello, `world\!"
|
||||
);
|
||||
assert_eq!(
|
||||
unescape_macro_string(r"Hello, \\world\!"),
|
||||
r"Hello, \world\!"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -28,9 +28,9 @@ fn transpile_test1() {
|
|||
main_fn.add_command(Command::Raw("say Hello, World!".to_string()));
|
||||
|
||||
let exec_cmd = Command::Execute(Execute::As(
|
||||
"@a".to_string(),
|
||||
"@a".to_string().into(),
|
||||
Box::new(Execute::If(
|
||||
Condition::Atom("entity @p[distance=..5]".to_string()),
|
||||
Condition::Atom("entity @p[distance=..5]".to_string().into()),
|
||||
Box::new(Execute::Run(Box::new(Command::Raw(
|
||||
"say You are close to me!".to_string(),
|
||||
)))),
|
||||
|
|
|
|||
Loading…
Reference in New Issue