Compare commits

...

35 Commits

Author SHA1 Message Date
Moritz Hölting e177760f2c update shulkerbox dependency 2025-03-05 17:00:53 +01:00
Moritz Hölting fe293b2dc4 make serialization of source file thread local 2025-02-19 09:32:47 +01:00
Moritz Hölting 0bf9625620 Change development branch name in github action workflow 2025-02-18 10:18:16 +01:00
Moritz Hölting 52ee83e0da add example compiler to demonstrate basic functionality and usage 2025-02-17 23:05:51 +01:00
Moritz Hölting f3f69faace Merge branch 'feature/macro-functions' into develop 2025-02-17 13:58:58 +01:00
Moritz Hölting c30bcc3018 remove dependency on feature "rc" of serde 2025-02-16 20:41:20 +01:00
Moritz Hölting 4a5f34a07b change back to derive (de-)serialize for Span 2025-02-16 20:41:20 +01:00
Moritz Hölting 9ee888f996 update changelog and make flexbuffers dependency optional 2025-02-16 20:41:20 +01:00
Moritz Hölting 572c68ca10 change order of serialization of Span by serializing to temporary buffer 2025-02-16 20:41:20 +01:00
Moritz Hölting b11f4d1caf implement custom deserialize
- requires opposite order of data and source_files than what is serialized
2025-02-16 20:41:20 +01:00
Moritz Hölting 5fbe40c41f implement custom serialize for Span 2025-02-16 20:41:20 +01:00
Moritz Hölting 346b97a58a update dependencies 2025-02-15 14:40:58 +01:00
Moritz Hölting a99a155d76 fix compilation errors depending on feature selection and update dependency version 2025-01-17 12:27:25 +01:00
Moritz Hölting 3a423e1de5 remove unnecessary RwLocks in Transpiler 2024-11-15 10:42:52 +01:00
Moritz Hölting 95153f2912 unescape macro string contents 2024-11-15 10:33:55 +01:00
Moritz Hölting c0b266caca allow passing in parameters to functions that will be used as macros 2024-11-12 14:40:40 +01:00
Moritz Hölting 134f181635 show multiple errors and mark tick/load annotation incompatible with parameters 2024-11-11 23:19:36 +01:00
Moritz Hölting c880b58f64 require macros to be present in function parameters 2024-11-11 22:54:24 +01:00
Moritz Hölting 550459922d implement first version of macros 2024-11-10 16:04:10 +01:00
Moritz Hölting 09400afa13 remove debug statement in lua handling 2024-11-09 15:24:58 +01:00
Moritz Hölting 320eef8ed7 update mlua to 0.10.0 2024-10-30 20:44:05 +01:00
Moritz Hölting 1f36650b50 prepare release of version 0.1.0 2024-10-01 12:01:20 +02:00
Moritz Hölting 5e6f158993 change to dual license, add code of conduct, contributing 2024-09-30 16:55:43 +02:00
Moritz Hölting f7414ad23f use full hash length as name, improve docs 2024-09-27 16:26:24 +02:00
Moritz Hölting 4d57e5ac61 update shulkerbox dependency for VFolder fix 2024-09-22 22:48:49 +02:00
Moritz Hölting 973e6c2c1f update shulkerbox dependency 2024-09-22 13:33:00 +02:00
Moritz Hölting 1f4cad5634 implement tag declaration 2024-09-21 22:45:05 +02:00
Moritz Hölting 536c8479aa implement error on conflicting function names and deterministic function generation order 2024-09-20 16:50:40 +02:00
Moritz Hölting 01a2d66503 improve lua integration by allowing more flexible return types and introducing globals 2024-09-20 14:55:48 +02:00
Moritz Hölting 9581da3c04 change return type of parse_* functions from Option to Result 2024-09-19 20:54:39 +02:00
Moritz Hölting 301ceb3efa improve error display 2024-09-19 00:12:24 +02:00
Moritz Hölting a2de2d7338 add source code display to UnexpectedExpression, LuaRuntimeError errors 2024-09-03 22:21:03 +02:00
Moritz Hölting 6094fc0df3 extend file provider with read_bytes method and return cow 2024-09-01 22:41:43 +02:00
Moritz Hölting 4efcb55d7c suggest similarly named functions if invoked function does not exist 2024-08-29 00:57:11 +02:00
Moritz Hölting befdc2bfd4 fix error on literal command directly after comment 2024-08-28 13:09:19 +02:00
43 changed files with 4791 additions and 561 deletions

20
.github/workflows/publish.yml vendored Normal file
View File

@ -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}

19
.github/workflows/test.yml vendored Normal file
View File

@ -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
.gitignore vendored
View File

@ -1,2 +1 @@
/target /target
/Cargo.lock

View File

@ -9,6 +9,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added ### 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 - Functions
- without arguments - without arguments
- Raw commands - Raw commands
@ -20,7 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- lua blocks - lua blocks
- imports - imports
- group - group
- Tags
### Changed [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
### Removed

70
CODE_OF_CONDUCT.md Normal file
View File

@ -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).

146
CONTRIBUTING.md Normal file
View File

@ -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)!

1018
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -4,34 +4,45 @@ version = "0.1.0"
edition = "2021" edition = "2021"
authors = ["Moritz Hölting <moritz@hoelting.dev>"] 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" repository = "https://github.com/moritz-hoelting/shulkerscript-lang"
homepage = "https://shulkerscript.hoelting.dev/"
readme = "README.md" 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 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features] [features]
default = ["lua", "shulkerbox"] default = ["fs_access", "lua", "shulkerbox", "zip"]
serde = ["dep:serde", "shulkerbox?/serde"] fs_access = ["shulkerbox?/fs_access"]
shulkerbox = ["dep:shulkerbox"]
lua = ["dep:mlua"] 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] [target.'cfg(target_arch = "wasm32")'.dependencies]
path-absolutize = { version = "3.1.1", features = ["use_unix_paths_on_wasm"] } path-absolutize = { version = "3.1.1", features = ["use_unix_paths_on_wasm"] }
[dependencies] [dependencies]
chksum-md5 = "0.0.0" chksum-md5 = { version = "0.1.0", optional = true }
colored = "2.1.0" colored = "3.0.0"
derive_more = { version = "0.99.17", default-features = false, features = ["deref", "from", "deref_mut"] } derive_more = { version = "2.0.1", default-features = false, features = ["deref", "deref_mut", "from"] }
enum-as-inner = "0.6.0" enum-as-inner = "0.6.0"
flexbuffers = { version = "25.2.10", optional = true }
getset = "0.1.2" 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" path-absolutize = "3.1.1"
serde = { version = "1.0.197", features = ["derive", "rc"], optional = true } pathdiff = "0.2.3"
shulkerbox = { git = "https://github.com/moritz-hoelting/shulkerbox", default-features = false, optional = true, rev = "a2d20dab8ea97bbd873edafb23afaad34292457f" } serde = { version = "1.0.217", features = ["derive"], optional = true }
strum = { version = "0.26.2", features = ["derive"] } # shulkerbox = { version = "0.1.0", default-features = false, optional = true }
strum_macros = "0.26.2" shulkerbox = { git = "https://github.com/moritz-hoelting/shulkerbox", rev = "6fefa27f2f1d22e4974a8b62fdadc087b5c2be22", default-features = false, optional = true }
thiserror = "1.0.58" strsim = "0.11.1"
tracing = "0.1.40" strum = { version = "0.27.0", features = ["derive"] }
thiserror = "2.0.11"
tracing = "0.1.41"
[dev-dependencies]
serde_json = "1.0.138"

201
LICENSE-APACHE Normal file
View File

@ -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.

View File

@ -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 ## Usage
Add the following to your dependencies in `Cargo.toml`: Add the following to your dependencies in `Cargo.toml`:
```toml ```toml
[dependencies] [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 ## Features
### Functions ### Functions

30
examples/compiler.rs Normal file
View File

@ -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");
}

View File

@ -1,4 +1,4 @@
# Grammar of the ShulkerScript language # Grammar of the Shulkerscript language
## Table of contents ## Table of contents
@ -12,9 +12,24 @@ Program: Namespace Declaration*;
Namespace: 'namespace' StringLiteral; Namespace: 'namespace' StringLiteral;
``` ```
### StringLiteral
```ebnf
StringLiteral: '"' TEXT '"';
```
### MacroStringLiteral
```ebnf
MacroStringLiteral: '`' ( TEXT | '$(' [a-zA-Z0-9_]+ ')' )* '`';
```
### AnyStringLiteral
```ebnf
AnyStringLiteral: StringLiteral | MacroStringLiteral;
```
### Declaration ### Declaration
```ebnf ```ebnf
Declaration: FunctionDeclaration | Import; Declaration: FunctionDeclaration | Import | TagDeclaration;
``` ```
### Import ### Import
@ -22,6 +37,11 @@ Declaration: FunctionDeclaration | Import;
Import: 'from' StringLiteral 'import' Identifier; Import: 'from' StringLiteral 'import' Identifier;
``` ```
### TagDeclaration
```ebnf
TagDeclaration: 'tag' StringLiteral ('of' StringLiteral)? 'replace'? '[' (StringLiteral (',' StringLiteral)*)? ']';
```
### FunctionDeclaration ### FunctionDeclaration
```ebnf ```ebnf
Function: Function:
@ -82,7 +102,7 @@ Condition:
PrimaryCondition: PrimaryCondition:
ConditionalPrefix ConditionalPrefix
| ParenthesizedCondition | ParenthesizedCondition
| StringLiteral | AnyStringLiteral
; ;
``` ```
@ -139,6 +159,8 @@ Expression:
```ebnf ```ebnf
Primary: Primary:
FunctionCall FunctionCall
| AnyStringLiteral
| LuaCode
; ;
``` ```

View File

@ -1,19 +1,26 @@
/// An error that occurred during compilation. /// An error that occurred during compilation.
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum Error { pub enum Error {
#[error("An error occurred while working with Input/Output.")] #[error("FileProviderError: {0}")]
IoError(String), FileProviderError(#[from] super::FileProviderError),
#[error("An error occurred while lexing the source code.")] #[error(transparent)]
LexicalError(#[from] crate::lexical::Error), LexicalError(#[from] crate::lexical::Error),
#[error("An error occured while tokenizing the source code.")]
TokenizeError(#[from] crate::lexical::token::TokenizeError),
#[error(transparent)] #[error(transparent)]
ParseError(#[from] crate::syntax::error::Error), ParseError(#[from] crate::syntax::error::Error),
#[error(transparent)] #[error(transparent)]
SemanticError(#[from] crate::semantic::error::Error),
#[error(transparent)]
TranspileError(#[from] crate::transpile::TranspileError), TranspileError(#[from] crate::transpile::TranspileError),
#[error("An error occurred")] #[error("An error occurred: {0}")]
Other(&'static str), 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. /// A specialized [`Result`] type for this crate.

View File

@ -1,15 +1,35 @@
use std::path::{Path, PathBuf}; use std::{
borrow::Cow,
use super::Error; fmt::Display,
path::{Path, PathBuf},
sync::Arc,
};
/// A trait for providing file contents. /// A trait for providing file contents.
pub trait FileProvider { 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. /// Reads the contents of the file at the given path.
/// ///
/// # Errors /// # Errors
/// - If an error occurs while reading the file. /// - If an error occurs while reading the file.
/// - If the file does not exist. /// - 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. /// Provides file contents from the file system.
@ -37,28 +57,155 @@ where
} }
impl FileProvider for FsProvider { 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); 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")] #[cfg(feature = "shulkerbox")]
mod vfs { mod vfs {
use std::{borrow::Cow, sync::Arc};
use super::{Error, FileProvider, Path}; use super::{Error, FileProvider, Path};
use shulkerbox::virtual_fs::{VFile, VFolder}; use shulkerbox::virtual_fs::{VFile, VFolder};
impl FileProvider for 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( normalize_path_str(path).map_or_else(
|| Err(Error::IoError("Invalid path".to_string())), || Err(Error::from(std::io::ErrorKind::InvalidData)),
|path| { |path| {
self.get_file(&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 { .and_then(|file| match file {
VFile::Text(text) => Ok(text.to_owned()), VFile::Text(text) => Ok(Cow::Borrowed(text.as_str())),
VFile::Binary(bin) => String::from_utf8(bin.clone()) VFile::Binary(bin) => {
.map_err(|err| Error::IoError(err.to_string())), 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("foo.txt", VFile::Text("foo".to_string()));
dir.add_file("bar/baz.txt", VFile::Text("bar, baz".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!( 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() "bar, baz".to_string()
); );
assert!(matches!( assert!(dir.read_str("nonexistent.txt").is_err());
dir.read_to_string("nonexistent.txt"),
Err(Error::IoError(_))
));
} }
} }
} }

View File

@ -291,7 +291,7 @@ fn write_error_line(
(line_number == start_line && index >= start_location.column) (line_number == start_line && index >= start_location.column)
|| (line_number == end_line || (line_number == end_line
&& (index + 1) && (index + 1)
< end_location <= end_location
.map_or(usize::MAX, |end_location| end_location.column)) .map_or(usize::MAX, |end_location| end_location.column))
|| (line_number > start_line && line_number < end_line) || (line_number > start_line && line_number < end_line)
} else { } else {

View File

@ -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; pub mod source_file;
@ -10,6 +10,6 @@ mod diagnostic;
pub use diagnostic::{Handler, PrintHandler, SilentHandler, VoidHandler}; pub use diagnostic::{Handler, PrintHandler, SilentHandler, VoidHandler};
mod file_provider; mod file_provider;
pub use file_provider::{FileProvider, FsProvider}; pub use file_provider::{Error as FileProviderError, FileProvider, FsProvider};
pub mod log; pub mod log;

View File

@ -86,14 +86,18 @@ impl SourceFile {
/// Load the source file from the given file path. /// Load the source file from the given file path.
/// ///
/// # Errors /// # Errors
/// - [`Error::IoError`]: Error occurred when reading the file contents. /// - [`Error::FileProviderError`]: Error occurred when reading the file contents.
pub fn load( pub fn load(
path: &Path, path: &Path,
identifier: String, identifier: String,
provider: &impl FileProvider, provider: &impl FileProvider,
) -> Result<Arc<Self>, Error> { ) -> Result<Arc<Self>, Error> {
let source = provider.read_to_string(path)?; let source = provider.read_str(path)?;
Ok(Self::new(path.to_path_buf(), identifier, source)) Ok(Self::new(
path.to_path_buf(),
identifier,
source.into_owned(),
))
} }
/// Get the [`Location`] of a given byte index /// Get the [`Location`] of a given byte index
@ -132,11 +136,17 @@ impl SourceFile {
None 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. /// Represents a range of characters in a source file.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Getters, CopyGetters)] #[derive(Clone, Getters, CopyGetters)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Span { pub struct Span {
/// Get the start byte index of the span. /// Get the start byte index of the span.
#[get_copy = "pub"] #[get_copy = "pub"]
@ -148,6 +158,7 @@ pub struct Span {
/// Get the source file that the span is located in. /// Get the source file that the span is located in.
#[get = "pub"] #[get = "pub"]
#[cfg_attr(feature = "serde", serde(with = "crate::serde::source_file"))]
source_file: Arc<SourceFile>, 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. /// Get the string slice of the source code that the span represents.
#[must_use] #[must_use]
pub fn str(&self) -> &str { pub fn str(&self) -> &str {

View File

@ -7,16 +7,18 @@ use crate::base::{
source_file::Span, 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. /// Represents an error that occurred during the lexical analysis of the source code.
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, thiserror::Error)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, thiserror::Error)]
pub enum Error { pub enum Error {
#[error("Comment is not terminated.")] #[error(transparent)]
UnterminatedDelimitedComment(#[from] UnterminatedDelimitedComment), UnterminatedDelimitedComment(#[from] UnterminatedDelimitedComment),
#[error("Delimiter is not terminated.")] #[error(transparent)]
UndelimitedDelimiter(#[from] UndelimitedDelimiter), UndelimitedDelimiter(#[from] UndelimitedDelimiter),
#[error("Tokenize error: {0}")]
TokenizeError(#[from] token::TokenizeError),
} }
/// Source code contains an unclosed `/*` comment. /// Source code contains an unclosed `/*` comment.

View File

@ -4,13 +4,13 @@ use std::{borrow::Cow, collections::HashMap, fmt::Display, str::FromStr, sync::O
use crate::base::{ use crate::base::{
self, self,
log::SourceCodeDisplay,
source_file::{SourceElement, SourceIterator, Span}, source_file::{SourceElement, SourceIterator, Span},
Handler, Handler,
}; };
use derive_more::From; use derive_more::From;
use enum_as_inner::EnumAsInner; use enum_as_inner::EnumAsInner;
use strum::IntoEnumIterator; use strum::{EnumIter, IntoEnumIterator};
use strum_macros::EnumIter;
use super::error::{self, UnterminatedDelimitedComment}; use super::error::{self, UnterminatedDelimitedComment};
@ -41,6 +41,9 @@ pub enum KeywordKind {
Namespace, Namespace,
From, From,
Import, Import,
Tag,
Of,
Replace,
} }
impl Display for KeywordKind { impl Display for KeywordKind {
@ -101,6 +104,9 @@ impl KeywordKind {
Self::Namespace => "namespace", Self::Namespace => "namespace",
Self::From => "from", Self::From => "from",
Self::Import => "import", Self::Import => "import",
Self::Tag => "tag",
Self::Of => "of",
Self::Replace => "replace",
} }
} }
@ -140,24 +146,7 @@ pub enum Token {
DocComment(DocComment), DocComment(DocComment),
CommandLiteral(CommandLiteral), CommandLiteral(CommandLiteral),
StringLiteral(StringLiteral), StringLiteral(StringLiteral),
} MacroStringLiteral(MacroStringLiteral),
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,
}
}
} }
impl SourceElement for Token { impl SourceElement for Token {
@ -172,6 +161,7 @@ impl SourceElement for Token {
Self::DocComment(token) => token.span(), Self::DocComment(token) => token.span(),
Self::CommandLiteral(token) => token.span(), Self::CommandLiteral(token) => token.span(),
Self::StringLiteral(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. /// Is an enumeration representing the two kinds of comments in the Shulkerscript programming language.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[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. /// 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)] #[allow(missing_docs)]
pub enum TokenizeError { pub enum TokenizeError {
#[error("encountered a fatal lexical error that causes the process to stop.")] #[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.")] #[error("the iterator argument is at the end of the source code.")]
EndOfSourceCodeIteratorArgument, 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 { impl Token {
/// Increments the iterator while the predicate returns true. /// Increments the iterator while the predicate returns true.
pub fn walk_iter(iter: &mut SourceIterator, predicate: impl Fn(char) -> bool) { 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. /// 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 { fn create_span(start: usize, iter: &mut SourceIterator) -> Span {
iter.peek().map_or_else( iter.peek().map_or_else(
|| Span::to_end(iter.source_file().clone(), start).unwrap(), || 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. /// Checks if the given character is a valid first character of an identifier.
fn is_first_identifier_character(character: char) -> bool { fn is_first_identifier_character(character: char) -> bool {
character == '_' character == '_'
@ -455,17 +623,8 @@ impl Token {
Self::walk_iter(iter, |character| !(character == '\n' || character == '\r')); 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); 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 { let comment = if is_doccomment {
DocComment { span }.into() DocComment { span }.into()
} else { } else {
@ -555,6 +714,113 @@ impl Token {
.into() .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 /// Handles a command that is preceeded by a slash
fn handle_command_literal(iter: &mut SourceIterator, start: usize) -> Self { fn handle_command_literal(iter: &mut SourceIterator, start: usize) -> Self {
Self::walk_iter(iter, |c| !(c.is_whitespace() && c.is_ascii_control())); Self::walk_iter(iter, |c| !(c.is_whitespace() && c.is_ascii_control()));
@ -596,9 +862,15 @@ impl Token {
// Found comment/single slash punctuation // Found comment/single slash punctuation
else if character == '/' { else if character == '/' {
Self::handle_comment(iter, start, character, prev_token, handler) 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)) Ok(Self::handle_string_literal(iter, start))
} }
// Found macro string literal
else if character == '`' {
Self::handle_macro_string_literal(iter, start)
}
// Found numeric literal // Found numeric literal
else if character.is_ascii_digit() { else if character.is_ascii_digit() {
Ok(Self::handle_numeric_literal(iter, start)) Ok(Self::handle_numeric_literal(iter, start))

View File

@ -5,10 +5,13 @@ use std::{fmt::Debug, sync::Arc};
use derive_more::{Deref, From}; use derive_more::{Deref, From};
use enum_as_inner::EnumAsInner; use enum_as_inner::EnumAsInner;
use crate::base::{ use crate::{
self, base::{
source_file::{SourceElement, SourceFile, Span}, self,
Handler, source_file::{SourceElement, SourceFile, Span},
Handler,
},
lexical::Error,
}; };
use super::{ use super::{
@ -62,6 +65,17 @@ impl TokenStream {
Err(TokenizeError::FatalLexicalError) => { Err(TokenizeError::FatalLexicalError) => {
tracing::error!("Fatal lexical error encountered while tokenizing source code"); 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 { impl SourceElement for TokenTree {
fn span(&self) -> Span { fn span(&self) -> Span {
match self { match self {
Self::Token(token) => token.span().to_owned(), Self::Token(token) => token.span(),
Self::Delimited(delimited) => delimited Self::Delimited(delimited) => delimited
.open .open
.span() .span()

View File

@ -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( #![deny(
missing_debug_implementations, missing_debug_implementations,
@ -12,12 +12,21 @@
#![warn(missing_docs, clippy::all, clippy::pedantic)] #![warn(missing_docs, clippy::all, clippy::pedantic)]
#![allow(clippy::missing_panics_doc, clippy::missing_const_for_fn)] #![allow(clippy::missing_panics_doc, clippy::missing_const_for_fn)]
#[cfg(feature = "shulkerbox")]
pub use shulkerbox; pub use shulkerbox;
pub mod base; pub mod base;
pub mod lexical; pub mod lexical;
pub mod semantic;
pub mod syntax; pub mod syntax;
pub mod transpile; 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; use std::path::Path;
@ -29,6 +38,11 @@ use shulkerbox::{datapack::Datapack, virtual_fs::VFolder};
use crate::lexical::token_stream::TokenStream; 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. /// Converts the given source code to tokens and returns a token stream.
/// ///
/// # Errors /// # Errors
@ -78,7 +92,7 @@ pub fn parse(
let tokens = tokenize(handler, file_provider, path, identifier)?; let tokens = tokenize(handler, file_provider, path, identifier)?;
if handler.has_received() { if handler.has_received() {
return Err(Error::Other( return Err(Error::other(
"An error occurred while tokenizing the source code.", "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()); tracing::info!("Parsing the source code at path: {}", path.display());
let mut parser = Parser::new(&tokens); let mut parser = Parser::new(&tokens);
let program = parser.parse_program(handler).ok_or(Error::Other( let program = parser.parse_program(handler)?;
"An error occurred while parsing the source code.",
))?;
if handler.has_received() { if handler.has_received() {
return Err(Error::Other( return Err(Error::other(
"An error occurred while parsing the source code.", "An error occurred while parsing the source code.",
)); ));
} }
program.analyze_semantics(handler)?;
Ok(program) Ok(program)
} }
@ -165,7 +179,7 @@ where
let datapack = transpiler.into_datapack(); let datapack = transpiler.into_datapack();
if handler.has_received() { if handler.has_received() {
return Err(Error::Other( return Err(Error::other(
"An error occurred while transpiling the source code.", "An error occurred while transpiling the source code.",
)); ));
} }

286
src/semantic/error.rs Normal file
View File

@ -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 {}

574
src/semantic/mod.rs Normal file
View File

@ -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, &macro_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
}
}
}

289
src/serde.rs Normal file
View File

@ -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())
);
}
}

View File

@ -3,20 +3,39 @@
use std::fmt::Display; use std::fmt::Display;
use crate::{ use crate::{
base::log::{Message, Severity, SourceCodeDisplay}, base::{
log::{Message, Severity, SourceCodeDisplay},
source_file::{SourceElement as _, Span},
},
lexical::token::{KeywordKind, Token}, 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. /// Enumeration containing all kinds of syntax that can be failed to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs)] #[allow(missing_docs)]
pub enum SyntaxKind { pub enum SyntaxKind {
Either(&'static [SyntaxKind]),
Punctuation(char), Punctuation(char),
Keyword(KeywordKind), Keyword(KeywordKind),
Identifier, Identifier,
Declaration, Declaration,
Numeric, Numeric,
StringLiteral, StringLiteral,
MacroStringLiteral,
AnyStringLiteral,
Statement, Statement,
Expression, Expression,
Type, Type,
@ -24,6 +43,45 @@ pub enum SyntaxKind {
ExecuteBlockTail, 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. /// A syntax/token is expected but found an other invalid token.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UnexpectedSyntax { pub struct UnexpectedSyntax {
@ -36,19 +94,7 @@ pub struct UnexpectedSyntax {
impl Display for UnexpectedSyntax { impl Display for UnexpectedSyntax {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let expected_binding = match self.expected { let expected_binding = self.expected.expected_binding_str();
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 found_binding = match self.found.clone() { let found_binding = match self.found.clone() {
Some(Token::Comment(..)) => "a comment token".to_string(), Some(Token::Comment(..)) => "a comment token".to_string(),
Some(Token::DocComment(..)) => "a doc 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::Numeric(..)) => "a numeric token".to_string(),
Some(Token::CommandLiteral(..)) => "a literal command token".to_string(), Some(Token::CommandLiteral(..)) => "a literal command token".to_string(),
Some(Token::StringLiteral(..)) => "a string literal 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(), None => "EOF".to_string(),
}; };
@ -75,7 +122,7 @@ impl Display for UnexpectedSyntax {
write!( write!(
f, f,
"\n{}", "\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 {} impl std::error::Error for UnexpectedSyntax {}
/// An enumeration containing all kinds of syntactic errors that can occur while parsing the /// An error that occurred due to an invalid argument.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, thiserror::Error)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs)] pub struct InvalidArgument {
pub enum Error { /// The error message.
#[error(transparent)] pub message: String,
UnexpectedSyntax(#[from] UnexpectedSyntax), /// 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 {}

View File

@ -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 error;
pub mod parser; pub mod parser;

View File

@ -6,12 +6,18 @@ use enum_as_inner::EnumAsInner;
use crate::{ use crate::{
base::{self, Handler}, base::{self, Handler},
lexical::{ lexical::{
token::{Identifier, Keyword, KeywordKind, Numeric, Punctuation, StringLiteral, Token}, token::{
Identifier, Keyword, KeywordKind, MacroStringLiteral, Numeric, Punctuation,
StringLiteral, Token,
},
token_stream::{Delimited, Delimiter, TokenStream, TokenTree}, 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. /// Represents a parser that reads a token stream and constructs an abstract syntax tree.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deref, DerefMut)] #[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. /// Steps into the [`Delimited`] token stream and parses the content within the delimiters.
/// ///
/// The parser's position must be at the delimited token stream. /// 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>( pub fn step_into<T>(
&mut self, &mut self,
delimiter: Delimiter, delimiter: Delimiter,
f: impl FnOnce(&mut Self) -> Option<T>, f: impl FnOnce(&mut Self) -> ParseResult<T>,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> Option<DelimitedTree<T>> { ) -> ParseResult<DelimitedTree<T>> {
self.current_frame.stop_at_significant(); self.current_frame.stop_at_significant();
let raw_token_tree = self let raw_token_tree = self
.current_frame .current_frame
@ -62,7 +71,7 @@ impl<'a> Parser<'a> {
delimited_tree delimited_tree
} }
found => { found => {
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Punctuation(expected), expected: SyntaxKind::Punctuation(expected),
found: Some(match found { found: Some(match found {
TokenTree::Token(token) => token.clone(), TokenTree::Token(token) => token.clone(),
@ -70,18 +79,20 @@ impl<'a> Parser<'a> {
Token::Punctuation(delimited_tree.open.clone()) Token::Punctuation(delimited_tree.open.clone())
} }
}), }),
})); });
handler.receive(err.clone());
return None; return Err(err);
} }
} }
} else { } else {
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Punctuation(expected), expected: SyntaxKind::Punctuation(expected),
found: self.get_reading(None).into_token(), found: self.get_reading(None).into_token(),
})); });
handler.receive(err.clone());
return None; return Err(err);
}; };
// creates a new frame // creates a new frame
@ -99,7 +110,10 @@ impl<'a> Parser<'a> {
let tree = f(self); let tree = f(self);
// pops the current frame off the stack // 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 // the current frame must be at the end
if !self.current_frame.is_exhausted() { if !self.current_frame.is_exhausted() {
@ -111,10 +125,12 @@ impl<'a> Parser<'a> {
.delimiter .delimiter
.closing_char(); .closing_char();
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Punctuation(expected), expected: SyntaxKind::Punctuation(expected),
found: self.peek().into_token(), found: self.peek().into_token(),
})); });
handler.receive(err.clone());
return Err(err);
} }
let close_punctuation = self let close_punctuation = self
@ -128,7 +144,7 @@ impl<'a> Parser<'a> {
// replaces the current frame with the popped one // replaces the current frame with the popped one
self.current_frame = new_frame; self.current_frame = new_frame;
Some(DelimitedTree { Ok(DelimitedTree {
open, open,
tree, tree,
close: close_punctuation, 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 /// Tries to parse the given function, and if it fails, resets the current index to the
/// `current_index` before the function call. /// `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 current_index = self.current_frame.current_index;
let result = f(self); let result = f(self);
if result.is_none() { if result.is_err() {
self.current_frame.current_index = current_index; self.current_frame.current_index = current_index;
} }
@ -157,7 +176,7 @@ pub struct DelimitedTree<T> {
pub open: Punctuation, pub open: Punctuation,
/// The tree inside the delimiter. /// The tree inside the delimiter.
pub tree: Option<T>, pub tree: ParseResult<T>,
/// The closing delimiter. /// The closing delimiter.
pub close: Punctuation, pub close: Punctuation,
@ -363,15 +382,19 @@ impl<'a> Frame<'a> {
/// ///
/// # Errors /// # Errors
/// If the next [`Token`] is not an [`Identifier`]. /// 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() { match self.next_significant_token() {
Reading::Atomic(Token::Identifier(ident)) => Some(ident), Reading::Atomic(Token::Identifier(ident)) => Ok(ident),
found => { found => {
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Identifier, expected: SyntaxKind::Identifier,
found: found.into_token(), found: found.into_token(),
})); });
None handler.receive(err.clone());
Err(err)
} }
} }
} }
@ -380,15 +403,16 @@ impl<'a> Frame<'a> {
/// ///
/// # Errors /// # Errors
/// If the next [`Token`] is not an [`Identifier`]. /// 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() { match self.next_significant_token() {
Reading::Atomic(Token::Numeric(ident)) => Some(ident), Reading::Atomic(Token::Numeric(ident)) => Ok(ident),
found => { found => {
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Numeric, expected: SyntaxKind::Numeric,
found: found.into_token(), found: found.into_token(),
})); });
None handler.receive(err.clone());
Err(err)
} }
} }
} }
@ -400,15 +424,59 @@ impl<'a> Frame<'a> {
pub fn parse_string_literal( pub fn parse_string_literal(
&mut self, &mut self,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> Option<StringLiteral> { ) -> ParseResult<StringLiteral> {
match self.next_significant_token() { match self.next_significant_token() {
Reading::Atomic(Token::StringLiteral(literal)) => Some(literal), Reading::Atomic(Token::StringLiteral(literal)) => Ok(literal),
found => { found => {
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::StringLiteral, expected: SyntaxKind::StringLiteral,
found: found.into_token(), 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, &mut self,
expected: KeywordKind, expected: KeywordKind,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> Option<Keyword> { ) -> ParseResult<Keyword> {
match self.next_significant_token() { match self.next_significant_token() {
Reading::Atomic(Token::Keyword(keyword_token)) if keyword_token.keyword == expected => { Reading::Atomic(Token::Keyword(keyword_token)) if keyword_token.keyword == expected => {
Some(keyword_token) Ok(keyword_token)
} }
found => { found => {
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Keyword(expected), expected: SyntaxKind::Keyword(expected),
found: found.into_token(), found: found.into_token(),
})); });
None handler.receive(err.clone());
Err(err)
} }
} }
} }
@ -445,7 +514,7 @@ impl<'a> Frame<'a> {
expected: char, expected: char,
skip_insignificant: bool, skip_insignificant: bool,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> Option<Punctuation> { ) -> ParseResult<Punctuation> {
match if skip_insignificant { match if skip_insignificant {
self.next_significant_token() self.next_significant_token()
} else { } else {
@ -454,14 +523,15 @@ impl<'a> Frame<'a> {
Reading::Atomic(Token::Punctuation(punctuation_token)) Reading::Atomic(Token::Punctuation(punctuation_token))
if punctuation_token.punctuation == expected => if punctuation_token.punctuation == expected =>
{ {
Some(punctuation_token) Ok(punctuation_token)
} }
found => { found => {
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Punctuation(expected), expected: SyntaxKind::Punctuation(expected),
found: found.into_token(), found: found.into_token(),
})); });
None handler.receive(err.clone());
Err(err)
} }
} }
} }

View File

@ -1,5 +1,7 @@
//! Syntax tree nodes for conditions. //! Syntax tree nodes for conditions.
#![allow(clippy::missing_errors_doc)]
use std::{cmp::Ordering, collections::VecDeque}; use std::{cmp::Ordering, collections::VecDeque};
use enum_as_inner::EnumAsInner; use enum_as_inner::EnumAsInner;
@ -9,45 +11,51 @@ use crate::{
base::{ base::{
self, self,
source_file::{SourceElement, Span}, source_file::{SourceElement, Span},
VoidHandler, Handler, Handler, VoidHandler,
}, },
lexical::{ lexical::{
token::{Punctuation, StringLiteral, Token}, token::{Punctuation, Token},
token_stream::Delimiter, token_stream::Delimiter,
}, },
syntax::{ syntax::{
error::{Error, SyntaxKind, UnexpectedSyntax}, error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax},
parser::{Parser, Reading}, parser::{Parser, Reading},
}, },
}; };
use super::AnyStringLiteral;
/// Condition that is viewed as a single entity during precedence parsing.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
/// PrimaryCondition: /// PrimaryCondition:
/// ConditionalPrefix /// UnaryCondition
/// | ParenthesizedCondition /// | ParenthesizedCondition
/// | StringLiteral /// | AnyStringLiteral
/// ``` /// ```
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, EnumAsInner)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, EnumAsInner)]
pub enum PrimaryCondition { pub enum PrimaryCondition {
Prefix(ConditionalPrefix), Unary(UnaryCondition),
Parenthesized(ParenthesizedCondition), Parenthesized(ParenthesizedCondition),
StringLiteral(StringLiteral), StringLiteral(AnyStringLiteral),
} }
impl SourceElement for PrimaryCondition { impl SourceElement for PrimaryCondition {
fn span(&self) -> Span { fn span(&self) -> Span {
match self { match self {
Self::Prefix(prefix) => prefix.span(), Self::Unary(unary) => unary.span(),
Self::Parenthesized(parenthesized) => parenthesized.span(), Self::Parenthesized(parenthesized) => parenthesized.span(),
Self::StringLiteral(literal) => literal.span(), Self::StringLiteral(literal) => literal.span(),
} }
} }
} }
/// Condition that is composed of two conditions and a binary operator.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -86,6 +94,8 @@ impl BinaryCondition {
} }
} }
/// Operator that is used to combine two conditions.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -126,6 +136,8 @@ impl SourceElement for ConditionalBinaryOperator {
} }
} }
/// Condition that is enclosed in parentheses.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -163,6 +175,8 @@ impl SourceElement for ParenthesizedCondition {
} }
} }
/// Operator that is used to prefix a condition.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -183,16 +197,18 @@ impl SourceElement for ConditionalPrefixOperator {
} }
} }
/// Condition that is prefixed by an operator.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ```ebnf /// ```ebnf
/// ConditionalPrefix: /// UnaryCondition:
/// ConditionalPrefixOperator PrimaryCondition /// ConditionalPrefixOperator PrimaryCondition
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
pub struct ConditionalPrefix { pub struct UnaryCondition {
/// The operator of the prefix. /// The operator of the prefix.
#[get = "pub"] #[get = "pub"]
operator: ConditionalPrefixOperator, operator: ConditionalPrefixOperator,
@ -201,12 +217,12 @@ pub struct ConditionalPrefix {
operand: Box<PrimaryCondition>, operand: Box<PrimaryCondition>,
} }
impl SourceElement for ConditionalPrefix { impl SourceElement for UnaryCondition {
fn span(&self) -> Span { fn span(&self) -> Span {
self.operator.span().join(&self.operand.span()).unwrap() self.operator.span().join(&self.operand.span()).unwrap()
} }
} }
impl ConditionalPrefix { impl UnaryCondition {
/// Dissolves the conditional prefix into its components /// Dissolves the conditional prefix into its components
#[must_use] #[must_use]
pub fn dissolve(self) -> (ConditionalPrefixOperator, PrimaryCondition) { pub fn dissolve(self) -> (ConditionalPrefixOperator, PrimaryCondition) {
@ -214,6 +230,8 @@ impl ConditionalPrefix {
} }
} }
/// Represents a condition in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -241,12 +259,20 @@ impl SourceElement for Condition {
impl<'a> Parser<'a> { impl<'a> Parser<'a> {
/// Parses a [`Condition`]. /// 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 lhs = Condition::Primary(self.parse_primary_condition(handler)?);
let mut expressions = VecDeque::new(); let mut expressions = VecDeque::new();
// Parses a list of binary operators and expressions // 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(( expressions.push_back((
binary_operator, binary_operator,
Some(Condition::Primary(self.parse_primary_condition(handler)?)), Some(Condition::Primary(self.parse_primary_condition(handler)?)),
@ -300,14 +326,14 @@ impl<'a> Parser<'a> {
} }
} }
Some(lhs) Ok(lhs)
} }
/// Parses a [`PrimaryCondition`]. /// Parses a [`PrimaryCondition`].
pub fn parse_primary_condition( pub fn parse_primary_condition(
&mut self, &mut self,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> Option<PrimaryCondition> { ) -> ParseResult<PrimaryCondition> {
match self.stop_at_significant() { match self.stop_at_significant() {
// prefixed expression // prefixed expression
Reading::Atomic(Token::Punctuation(punc)) if punc.punctuation == '!' => { 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)?); let operand = Box::new(self.parse_primary_condition(handler)?);
Some(PrimaryCondition::Prefix(ConditionalPrefix { Ok(PrimaryCondition::Unary(UnaryCondition {
operator, operator,
operand, operand,
})) }))
@ -330,7 +356,13 @@ impl<'a> Parser<'a> {
// string literal // string literal
Reading::Atomic(Token::StringLiteral(literal)) => { Reading::Atomic(Token::StringLiteral(literal)) => {
self.forward(); 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 // parenthesized condition
@ -342,12 +374,17 @@ impl<'a> Parser<'a> {
// make progress // make progress
self.forward(); self.forward();
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Expression, expected: SyntaxKind::Either(&[
SyntaxKind::Punctuation('!'),
SyntaxKind::StringLiteral,
SyntaxKind::Punctuation('('),
]),
found: unexpected.into_token(), found: unexpected.into_token(),
})); });
handler.receive(err.clone());
None Err(err)
} }
} }
} }
@ -356,38 +393,59 @@ impl<'a> Parser<'a> {
pub fn parse_parenthesized_condition( pub fn parse_parenthesized_condition(
&mut self, &mut self,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> Option<ParenthesizedCondition> { ) -> ParseResult<ParenthesizedCondition> {
let token_tree = self.step_into( let token_tree = self.step_into(
Delimiter::Parenthesis, Delimiter::Parenthesis,
|parser| { |parser| {
let cond = parser.parse_condition(handler)?; let cond = parser.parse_condition(handler)?;
parser.stop_at_significant(); parser.stop_at_significant();
Some(cond) Ok(cond)
}, },
handler, handler,
)?; )?;
Some(ParenthesizedCondition { Ok(ParenthesizedCondition {
open_paren: token_tree.open, open_paren: token_tree.open,
condition: Box::new(token_tree.tree?), condition: Box::new(token_tree.tree?),
close_paren: token_tree.close, 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() { 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)) let b = parser.parse_punctuation('&', false, &VoidHandler)?;
} Ok(ConditionalBinaryOperator::LogicalAnd(punc, b))
'|' => { }
let b = parser.parse_punctuation('|', false, &VoidHandler)?; '|' => {
Some(ConditionalBinaryOperator::LogicalOr(punc, b)) let b = parser.parse_punctuation('|', false, &VoidHandler)?;
} Ok(ConditionalBinaryOperator::LogicalOr(punc, b))
_ => None, }
_ => Err(Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Either(&[
SyntaxKind::Punctuation('&'),
SyntaxKind::Punctuation('|'),
]),
found: Some(token),
})),
},
unexpected => Err(Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Either(&[
SyntaxKind::Punctuation('&'),
SyntaxKind::Punctuation('|'),
]),
found: Some(unexpected),
})),
}, },
_ => None, unexpected => Err(Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Either(&[
SyntaxKind::Punctuation('&'),
SyntaxKind::Punctuation('|'),
]),
found: unexpected.into_token(),
})),
}) })
} }
} }

View File

@ -15,13 +15,15 @@ use crate::{
token_stream::Delimiter, token_stream::Delimiter,
}, },
syntax::{ syntax::{
error::{Error, SyntaxKind, UnexpectedSyntax}, error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax},
parser::{Parser, Reading}, parser::{Parser, Reading},
}, },
}; };
use super::{statement::Block, ConnectedList}; use super::{statement::Block, ConnectedList, DelimitedList};
/// Represents a declaration in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -35,6 +37,7 @@ use super::{statement::Block, ConnectedList};
pub enum Declaration { pub enum Declaration {
Function(Function), Function(Function),
Import(Import), Import(Import),
Tag(Tag),
} }
impl SourceElement for Declaration { impl SourceElement for Declaration {
@ -42,9 +45,12 @@ impl SourceElement for Declaration {
match self { match self {
Self::Function(function) => function.span(), Self::Function(function) => function.span(),
Self::Import(import) => import.span(), Self::Import(import) => import.span(),
Self::Tag(tag) => tag.span(),
} }
} }
} }
/// Represents an Annotation with optional value.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -97,6 +103,8 @@ impl SourceElement for Annotation {
} }
} }
/// Represents a function declaration in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -174,6 +182,8 @@ impl SourceElement for Function {
} }
} }
/// Represents an import declaration in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -196,6 +206,7 @@ pub struct Import {
semicolon: Punctuation, semicolon: Punctuation,
} }
/// Items to import.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ImportItems { 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> { 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() { match self.stop_at_significant() {
Reading::Atomic(Token::Punctuation(punctuation)) if punctuation.punctuation == '#' => { Reading::Atomic(Token::Punctuation(punctuation)) if punctuation.punctuation == '#' => {
// eat the pound sign // eat the pound sign
@ -239,36 +333,29 @@ impl<'a> Parser<'a> {
|parser| { |parser| {
let identifier = parser.parse_identifier(handler)?; let identifier = parser.parse_identifier(handler)?;
let value = if let Reading::Atomic(Token::Punctuation(punctuation)) = let value = match parser.stop_at_significant() {
parser.stop_at_significant() Reading::Atomic(Token::Punctuation(punc))
{ if punc.punctuation == '=' =>
if punctuation.punctuation == '=' { {
// eat the equals sign // eat the equals sign
parser.forward(); parser.forward();
// parse the string literal // parse the string literal
let string_literal = parser let string_literal = parser.parse_string_literal(handler)?;
.next_significant_token()
.into_token()?
.into_string_literal()
.ok()?;
Some((punctuation, string_literal)) Some((punc, string_literal))
} else {
None
} }
} else { _ => None,
None
}; };
Some((identifier, value)) Ok((identifier, value))
}, },
handler, handler,
)?; )?;
let (identifier, value) = content.tree?; let (identifier, value) = content.tree?;
Some(Annotation { Ok(Annotation {
pound_sign: punctuation, pound_sign: punctuation,
open_bracket: content.open, open_bracket: content.open,
identifier, identifier,
@ -276,7 +363,14 @@ impl<'a> Parser<'a> {
close_bracket: content.close, 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( pub fn parse_declaration(
&mut self, &mut self,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> Option<Declaration> { ) -> ParseResult<Declaration> {
match self.stop_at_significant() { match self.stop_at_significant() {
Reading::Atomic(Token::Keyword(function_keyword)) Reading::Atomic(Token::Keyword(function_keyword))
if function_keyword.keyword == KeywordKind::Function => if function_keyword.keyword == KeywordKind::Function =>
@ -293,22 +387,17 @@ impl<'a> Parser<'a> {
tracing::trace!("Parsed function '{:?}'", function.identifier.span.str()); tracing::trace!("Parsed function '{:?}'", function.identifier.span.str());
Some(Declaration::Function(function)) Ok(Declaration::Function(function))
} }
Reading::Atomic(Token::Keyword(pub_keyword)) Reading::Atomic(Token::Keyword(pub_keyword))
if pub_keyword.keyword == KeywordKind::Pub => if pub_keyword.keyword == KeywordKind::Pub =>
{ {
// eat the public keyword
self.forward();
// parse the function keyword
let function = self.parse_function(handler)?; let function = self.parse_function(handler)?;
Some(Declaration::Function(Function { tracing::trace!("Parsed function '{:?}'", function.identifier.span.str());
public_keyword: Some(pub_keyword),
..function Ok(Declaration::Function(function))
}))
} }
// parse annotations // parse annotations
@ -316,23 +405,15 @@ impl<'a> Parser<'a> {
// parse the annotation // parse the annotation
let mut annotations = Vec::new(); let mut annotations = Vec::new();
while let Some(annotation) = while let Ok(annotation) =
self.try_parse(|parser| parser.parse_annotation(handler)) self.try_parse(|parser| parser.parse_annotation(&VoidHandler))
{ {
annotations.push(annotation); annotations.push(annotation);
} }
self.parse_declaration(handler).and_then(|declaration| { self.parse_function(handler).map(|mut function| {
if let Declaration::Function(mut function) = declaration { function.annotations.extend(annotations);
function.annotations.extend(annotations); Declaration::Function(function)
Some(Declaration::Function(function))
} else {
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Keyword(KeywordKind::Function),
found: None,
}));
None
}
}) })
} }
@ -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)?; let semicolon = self.parse_punctuation(';', true, handler)?;
tracing::trace!("Parsed import from '{:?}'", module.str_content()); tracing::trace!("Parsed import from '{:?}'", module.str_content());
Some(Declaration::Import(Import { Ok(Declaration::Import(Import {
from_keyword, from_keyword,
module, module,
import_keyword, import_keyword,
@ -379,62 +460,116 @@ impl<'a> Parser<'a> {
semicolon, semicolon,
})) }))
} else { } else {
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Identifier, expected: SyntaxKind::Punctuation('*'),
found: self.stop_at_significant().into_token(), 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 => { unexpected => {
// make progress // make progress
self.forward(); self.forward();
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Declaration, expected: SyntaxKind::Declaration,
found: unexpected.into_token(), found: unexpected.into_token(),
})); });
handler.receive(err.clone());
None Err(err)
} }
} }
} }
pub fn parse_function(&mut self, handler: &impl Handler<base::Error>) -> Option<Function> { /// Parses a function.
if let Reading::Atomic(Token::Keyword(function_keyword)) = self.stop_at_significant() { ///
// eat the function keyword /// # Errors
self.forward(); /// - 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));
// parse the identifier match self.stop_at_significant() {
let identifier = self.parse_identifier(handler)?; Reading::Atomic(Token::Keyword(function_keyword))
let delimited_tree = self.parse_enclosed_list( if function_keyword.keyword == KeywordKind::Function =>
Delimiter::Parenthesis, {
',', // eat the function keyword
|parser: &mut Parser<'_>| parser.parse_identifier(handler), self.forward();
handler,
)?;
// parse the block // parse the identifier
let block = self.parse_block(handler)?; let identifier = self.parse_identifier(handler)?;
let delimited_tree = self.parse_enclosed_list(
Delimiter::Parenthesis,
',',
|parser: &mut Parser<'_>| parser.parse_identifier(handler),
handler,
)?;
Some(Function { // parse the block
public_keyword: None, let block = self.parse_block(handler)?;
annotations: Vec::new(),
function_keyword, Ok(Function {
identifier, public_keyword: pub_keyword.ok(),
open_paren: delimited_tree.open, annotations: Vec::new(),
parameters: delimited_tree.list, function_keyword,
close_paren: delimited_tree.close, identifier,
block, open_paren: delimited_tree.open,
}) parameters: delimited_tree.list,
} else { close_paren: delimited_tree.close,
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { block,
expected: SyntaxKind::Keyword(KeywordKind::Function), })
found: self.peek().into_token(), }
})); unexpected => {
None let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Keyword(KeywordKind::Function),
found: unexpected.into_token(),
});
handler.receive(err.clone());
Err(err)
}
} }
} }
} }

View File

@ -10,17 +10,22 @@ use crate::{
Handler, Handler,
}, },
lexical::{ lexical::{
token::{Identifier, Keyword, KeywordKind, Punctuation, StringLiteral, Token}, token::{
Identifier, Keyword, KeywordKind, MacroStringLiteral, Punctuation, StringLiteral, Token,
},
token_stream::Delimiter, token_stream::Delimiter,
}, },
syntax::{ syntax::{
error::{Error, UnexpectedSyntax}, self,
error::{Error, ParseResult, UnexpectedSyntax},
parser::{Parser, Reading}, parser::{Parser, Reading},
}, },
}; };
use super::ConnectedList; use super::ConnectedList;
/// Represents an expression in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ```ebnf /// ```ebnf
@ -42,11 +47,16 @@ impl SourceElement for Expression {
} }
} }
/// Represents a primary expression in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
/// Primary: /// Primary:
/// FunctionCall /// FunctionCall
/// | StringLiteral
/// | MacroStringLiteral
/// | LuaCode
/// ``` /// ```
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -54,6 +64,7 @@ impl SourceElement for Expression {
pub enum Primary { pub enum Primary {
FunctionCall(FunctionCall), FunctionCall(FunctionCall),
StringLiteral(StringLiteral), StringLiteral(StringLiteral),
MacroStringLiteral(MacroStringLiteral),
Lua(Box<LuaCode>), Lua(Box<LuaCode>),
} }
@ -62,11 +73,14 @@ impl SourceElement for Primary {
match self { match self {
Self::FunctionCall(function_call) => function_call.span(), Self::FunctionCall(function_call) => function_call.span(),
Self::StringLiteral(string_literal) => string_literal.span(), Self::StringLiteral(string_literal) => string_literal.span(),
Self::MacroStringLiteral(macro_string_literal) => macro_string_literal.span(),
Self::Lua(lua_code) => lua_code.span(), Self::Lua(lua_code) => lua_code.span(),
} }
} }
} }
/// Represents a function call in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -100,6 +114,8 @@ impl SourceElement for FunctionCall {
} }
} }
/// Represents a lua code block in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ```ebnf /// ```ebnf
@ -156,12 +172,23 @@ impl LuaCode {
impl<'a> Parser<'a> { impl<'a> Parser<'a> {
/// Parses an [`Expression`] /// 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`] /// 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() { match self.stop_at_significant() {
// identifier expression // identifier expression
Reading::Atomic(Token::Identifier(identifier)) => { Reading::Atomic(Token::Identifier(identifier)) => {
@ -169,24 +196,31 @@ impl<'a> Parser<'a> {
self.forward(); self.forward();
// function call // 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( let token_tree = self.parse_enclosed_list(
Delimiter::Parenthesis, Delimiter::Parenthesis,
',', ',',
|parser| parser.parse_expression(handler).map(Box::new), |parser| parser.parse_expression(handler).map(Box::new),
handler, handler,
)?; )?;
Some(Primary::FunctionCall(FunctionCall { Ok(Primary::FunctionCall(FunctionCall {
identifier, identifier,
left_parenthesis: token_tree.open, left_parenthesis: token_tree.open,
right_parenthesis: token_tree.close, right_parenthesis: token_tree.close,
arguments: token_tree.list, arguments: token_tree.list,
})) }))
} else { }
// insert parser for regular identifier here unexpected => {
None // insert parser for regular identifier here
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 // eat the string literal
self.forward(); 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 // lua code expression
@ -212,9 +254,16 @@ impl<'a> Parser<'a> {
|parser| match parser.next_significant_token() { |parser| match parser.next_significant_token() {
Reading::Atomic(Token::Identifier(identifier)) => { Reading::Atomic(Token::Identifier(identifier)) => {
parser.forward(); 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, handler,
)?; )?;
@ -234,19 +283,20 @@ impl<'a> Parser<'a> {
let combined = first let combined = first
.into_token() .into_token()
.and_then(|first| { .and_then(|first| {
first.span().join(&last.into_token().map_or_else( first.span().join(
|| first.span().to_owned(), &last
|last| last.span().to_owned(), .into_token()
)) .map_or_else(|| first.span(), |last| last.span()),
)
}) })
.expect("Invalid lua code span"); .expect("Invalid lua code span");
Some(combined.str().trim().to_owned()) Ok(combined.str().trim().to_owned())
}, },
handler, handler,
)?; )?;
Some(Primary::Lua(Box::new(LuaCode { Ok(Primary::Lua(Box::new(LuaCode {
lua_keyword, lua_keyword,
left_parenthesis: variables.open, left_parenthesis: variables.open,
variables: variables.list, variables: variables.list,
@ -261,12 +311,13 @@ impl<'a> Parser<'a> {
// make progress // make progress
self.forward(); self.forward();
handler.receive(Error::UnexpectedSyntax(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: crate::syntax::error::SyntaxKind::Expression, expected: syntax::error::SyntaxKind::Expression,
found: unexpected.into_token(), found: unexpected.into_token(),
})); });
handler.receive(err.clone());
None Err(err)
} }
} }
} }

View File

@ -1,5 +1,6 @@
//! Contains the syntax tree nodes that represent the structure of the source code. //! Contains the syntax tree nodes that represent the structure of the source code.
use derive_more::derive::From;
use getset::Getters; use getset::Getters;
use crate::{ use crate::{
@ -9,13 +10,13 @@ use crate::{
Handler, VoidHandler, Handler, VoidHandler,
}, },
lexical::{ lexical::{
token::{Punctuation, Token}, token::{MacroStringLiteral, Punctuation, StringLiteral, Token},
token_stream::Delimiter, token_stream::Delimiter,
}, },
syntax::parser::Reading, syntax::parser::Reading,
}; };
use super::parser::Parser; use super::{error::ParseResult, parser::Parser};
pub mod condition; pub mod condition;
pub mod declaration; 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 /// Represents a syntax tree node with a pattern of having [`ConnectedList`] delimited by a pair of
/// punctuation like such `(a, b, c)`. /// punctuation like such `(a, b, c)`.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DelimitedList<T> { pub struct DelimitedList<T> {
/// The open punctuation of the list. /// The open punctuation of the list.
@ -63,6 +65,29 @@ pub struct DelimitedList<T> {
pub close: Punctuation, 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> { impl<'a> Parser<'a> {
/// Parses a list of elements enclosed by a pair of delimiters, separated by a separator. /// 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, &mut self,
delimiter: Delimiter, delimiter: Delimiter,
separator: char, separator: char,
mut f: impl FnMut(&mut Self) -> Option<T>, mut f: impl FnMut(&mut Self) -> ParseResult<T>,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> Option<DelimitedList<T>> { ) -> ParseResult<DelimitedList<T>> {
fn skip_to_next_separator(this: &mut Parser, separator: char) -> Option<Punctuation> { fn skip_to_next_separator(this: &mut Parser, separator: char) -> Option<Punctuation> {
if let Reading::Atomic(Token::Punctuation(punc)) = this.stop_at(|token| { if let Reading::Atomic(Token::Punctuation(punc)) = this.stop_at(|token| {
matches!( matches!(
@ -101,7 +126,7 @@ impl<'a> Parser<'a> {
let mut trailing_separator: Option<Punctuation> = None; let mut trailing_separator: Option<Punctuation> = None;
while !parser.is_exhausted() { while !parser.is_exhausted() {
let Some(element) = f(parser) else { let Ok(element) = f(parser) else {
skip_to_next_separator(parser, separator); skip_to_next_separator(parser, separator);
continue; continue;
}; };
@ -122,7 +147,7 @@ impl<'a> Parser<'a> {
// expect separator if not exhausted // expect separator if not exhausted
if !parser.is_exhausted() { if !parser.is_exhausted() {
let Some(separator) = parser.parse_punctuation(separator, true, handler) let Ok(separator) = parser.parse_punctuation(separator, true, handler)
else { else {
if let Some(punctuation) = skip_to_next_separator(parser, separator) { if let Some(punctuation) = skip_to_next_separator(parser, separator) {
trailing_separator = Some(punctuation); trailing_separator = Some(punctuation);
@ -135,7 +160,7 @@ impl<'a> Parser<'a> {
} }
} }
Some(first.map(|first| ConnectedList { Ok(first.map(|first| ConnectedList {
first, first,
rest, rest,
trailing_separator, trailing_separator,
@ -144,7 +169,7 @@ impl<'a> Parser<'a> {
handler, handler,
)?; )?;
Some(DelimitedList { Ok(DelimitedList {
open: delimited_tree.open, open: delimited_tree.open,
list: delimited_tree.tree.unwrap(), list: delimited_tree.tree.unwrap(),
close: delimited_tree.close, close: delimited_tree.close,
@ -162,20 +187,20 @@ impl<'a> Parser<'a> {
pub fn parse_connected_list<T>( pub fn parse_connected_list<T>(
&mut self, &mut self,
seperator: char, seperator: char,
mut f: impl FnMut(&mut Self) -> Option<T>, mut f: impl FnMut(&mut Self) -> ParseResult<T>,
_handler: &impl Handler<base::Error>, _handler: &impl Handler<base::Error>,
) -> Option<ConnectedList<T, Punctuation>> { ) -> ParseResult<ConnectedList<T, Punctuation>> {
let first = f(self)?; let first = f(self)?;
let mut rest = Vec::new(); let mut rest = Vec::new();
while let Some(sep) = while let Ok(sep) =
self.try_parse(|parser| parser.parse_punctuation(seperator, true, &VoidHandler)) 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)); rest.push((sep, element));
} else { } else {
return Some(ConnectedList { return Ok(ConnectedList {
first, first,
rest, rest,
trailing_separator: Some(sep), trailing_separator: Some(sep),
@ -183,7 +208,7 @@ impl<'a> Parser<'a> {
} }
} }
Some(ConnectedList { Ok(ConnectedList {
first, first,
rest, rest,
trailing_separator: None, trailing_separator: None,

View File

@ -1,6 +1,7 @@
//! The program node of the syntax tree. //! The program node of the syntax tree.
use getset::Getters; use getset::Getters;
use itertools::Itertools;
use crate::{ use crate::{
base::{ base::{
@ -11,7 +12,7 @@ use crate::{
lexical::token::{Keyword, KeywordKind, Punctuation, StringLiteral, Token}, lexical::token::{Keyword, KeywordKind, Punctuation, StringLiteral, Token},
syntax::{ syntax::{
self, self,
error::{SyntaxKind, UnexpectedSyntax}, error::{ParseResult, SyntaxKind, UnexpectedSyntax},
parser::{Parser, Reading}, parser::{Parser, Reading},
}, },
}; };
@ -70,18 +71,34 @@ impl Namespace {
} }
/// Validates a namespace string. /// 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_-."; 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> { impl<'a> Parser<'a> {
/// Parses a [`ProgramFile`]. /// Parses a [`ProgramFile`].
#[tracing::instrument(level = "debug", skip_all)] #[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"); tracing::debug!("Parsing program");
let namespace = match self.stop_at_significant() { let namespace = match self.stop_at_significant() {
@ -91,24 +108,23 @@ impl<'a> Parser<'a> {
// eat the keyword // eat the keyword
self.forward(); self.forward();
let namespace_name = self.parse_string_literal(handler).and_then(|name| { let namespace_name = self.parse_string_literal(handler)?;
Namespace::validate_str(name.str_content().as_ref()).then_some(name)
})?;
let semicolon = self.parse_punctuation(';', true, handler)?; let semicolon = self.parse_punctuation(';', true, handler)?;
Some(Namespace { Ok(Namespace {
namespace_keyword, namespace_keyword,
namespace_name, namespace_name,
semicolon, semicolon,
}) })
} }
unexpected => { unexpected => {
handler.receive(syntax::error::Error::from(UnexpectedSyntax { let err = syntax::error::Error::from(UnexpectedSyntax {
expected: SyntaxKind::Keyword(KeywordKind::Namespace), expected: SyntaxKind::Keyword(KeywordKind::Namespace),
found: unexpected.into_token(), 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); let result = self.parse_declaration(handler);
#[allow(clippy::option_if_let_else)] #[allow(clippy::option_if_let_else)]
if let Some(x) = result { if let Ok(x) = result {
declarations.push(x); declarations.push(x);
} else { } else {
self.stop_at(|reading| { self.stop_at(|reading| {
@ -137,7 +153,7 @@ impl<'a> Parser<'a> {
} }
} }
Some(ProgramFile { Ok(ProgramFile {
namespace, namespace,
declarations, declarations,
}) })

View File

@ -15,13 +15,18 @@ use crate::{
token::{CommandLiteral, DocComment, Keyword, KeywordKind, Punctuation, Token}, token::{CommandLiteral, DocComment, Keyword, KeywordKind, Punctuation, Token},
token_stream::Delimiter, token_stream::Delimiter,
}, },
syntax::parser::{Parser, Reading}, syntax::{
error::ParseResult,
parser::{Parser, Reading},
},
}; };
use self::execute_block::ExecuteBlock; use self::execute_block::ExecuteBlock;
use super::expression::Expression; use super::expression::Expression;
/// Represents a statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -62,6 +67,8 @@ impl SourceElement for Statement {
} }
} }
/// Represents a block in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -100,6 +107,8 @@ impl SourceElement for Block {
} }
} }
/// Represents a run statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -138,6 +147,8 @@ impl Run {
} }
} }
/// Represents a grouping statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -173,6 +184,8 @@ impl SourceElement for Grouping {
} }
} }
/// Represents a statement that ends with a semicolon in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ``` ebnf /// ``` ebnf
/// Semicolon: /// Semicolon:
@ -209,7 +222,10 @@ impl Semicolon {
impl<'a> Parser<'a> { impl<'a> Parser<'a> {
/// Parses a [`Block`]. /// 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( let token_tree = self.step_into(
Delimiter::Brace, Delimiter::Brace,
|parser| { |parser| {
@ -217,7 +233,7 @@ impl<'a> Parser<'a> {
while !parser.is_exhausted() { while !parser.is_exhausted() {
parser.parse_statement(handler).map_or_else( parser.parse_statement(handler).map_or_else(
|| { |_| {
// error recovery // error recovery
parser.stop_at(|reading| matches!( parser.stop_at(|reading| matches!(
reading, reading,
@ -234,12 +250,12 @@ impl<'a> Parser<'a> {
); );
} }
Some(statements) Ok(statements)
}, },
handler, handler,
)?; )?;
Some(Block { Ok(Block {
open_brace: token_tree.open, open_brace: token_tree.open,
statements: token_tree.tree?, statements: token_tree.tree?,
close_brace: token_tree.close, close_brace: token_tree.close,
@ -248,19 +264,22 @@ impl<'a> Parser<'a> {
/// Parses a [`Statement`]. /// Parses a [`Statement`].
#[tracing::instrument(level = "trace", skip_all)] #[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() { match self.stop_at_significant() {
// variable declaration // variable declaration
Reading::Atomic(Token::CommandLiteral(command)) => { Reading::Atomic(Token::CommandLiteral(command)) => {
self.forward(); self.forward();
tracing::trace!("Parsed literal command '{}'", command.clean_command()); tracing::trace!("Parsed literal command '{}'", command.clean_command());
Some(Statement::LiteralCommand(command)) Ok(Statement::LiteralCommand(command))
} }
// block statement // block statement
Reading::IntoDelimited(open_brace) if open_brace.punctuation == '{' => { Reading::IntoDelimited(open_brace) if open_brace.punctuation == '{' => {
let block = self.parse_block(handler)?; let block = self.parse_block(handler)?;
Some(Statement::Block(block)) Ok(Statement::Block(block))
} }
// execute block // execute block
@ -274,7 +293,7 @@ impl<'a> Parser<'a> {
// doc comment // doc comment
Reading::Atomic(Token::DocComment(doc_comment)) => { Reading::Atomic(Token::DocComment(doc_comment)) => {
self.forward(); self.forward();
Some(Statement::DocComment(doc_comment)) Ok(Statement::DocComment(doc_comment))
} }
// grouping statement // grouping statement
@ -288,7 +307,7 @@ impl<'a> Parser<'a> {
tracing::trace!("Parsed group command"); tracing::trace!("Parsed group command");
Some(Statement::Grouping(Grouping { Ok(Statement::Grouping(Grouping {
group_keyword, group_keyword,
block, block,
})) }))
@ -306,7 +325,7 @@ impl<'a> Parser<'a> {
tracing::trace!("Parsed run statement: {:?}", expression); tracing::trace!("Parsed run statement: {:?}", expression);
Some(Statement::Run(Run { Ok(Statement::Run(Run {
run_keyword, run_keyword,
expression, expression,
semicolon, semicolon,
@ -320,7 +339,7 @@ impl<'a> Parser<'a> {
tracing::trace!("Parsed semicolon statement: {:?}", expression); tracing::trace!("Parsed semicolon statement: {:?}", expression);
Some(Statement::Semicolon(Semicolon { Ok(Statement::Semicolon(Semicolon {
expression, expression,
semicolon, semicolon,
})) }))

View File

@ -1,5 +1,7 @@
//! Execute block statement syntax tree. //! Execute block statement syntax tree.
use std::collections::HashSet;
use derive_more::From; use derive_more::From;
use enum_as_inner::EnumAsInner; use enum_as_inner::EnumAsInner;
use getset::Getters; use getset::Getters;
@ -8,22 +10,23 @@ use crate::{
base::{ base::{
self, self,
source_file::{SourceElement, Span}, source_file::{SourceElement, Span},
VoidHandler, Handler, Handler, VoidHandler,
}, },
lexical::{ lexical::{
token::{Keyword, KeywordKind, Punctuation, StringLiteral, Token}, token::{Keyword, KeywordKind, Punctuation, Token},
token_stream::Delimiter, token_stream::Delimiter,
}, },
syntax::{ syntax::{
self, error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax},
error::{SyntaxKind, UnexpectedSyntax},
parser::{DelimitedTree, Parser, Reading}, parser::{DelimitedTree, Parser, Reading},
syntax_tree::condition::ParenthesizedCondition, syntax_tree::{condition::ParenthesizedCondition, AnyStringLiteral},
}, },
}; };
use super::Block; use super::Block;
/// Represents an execute block statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// ExecuteBlock: /// ExecuteBlock:
@ -52,11 +55,25 @@ impl SourceElement for ExecuteBlock {
} }
} }
/// Represents the head of an execute block statement.
///
/// Syntax Synopsis: /// Syntax Synopsis:
///
/// ```ebnf /// ```ebnf
/// ExecuteBlockHead: /// ExecuteBlockHead:
/// Conditional /// Conditional
/// | Align
/// | Anchored
/// | As /// | As
/// | AsAt
/// | At
/// | Facing
/// | In
/// | On
/// | Positioned
/// | Rotated
/// | Store
/// | Summon
/// ; /// ;
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, EnumAsInner, From)] #[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: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// ExecuteBlockTail: /// ExecuteBlockTail:
@ -123,6 +142,8 @@ impl SourceElement for ExecuteBlockTail {
} }
} }
/// Represents an conditional `if` statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -158,6 +179,8 @@ impl SourceElement for Conditional {
} }
} }
/// Represents an `else` block in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ``` ebnf /// ``` ebnf
@ -190,11 +213,13 @@ impl SourceElement for Else {
} }
} }
/// Represents an `as` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ///
/// ```ebnf /// ```ebnf
/// As: /// As:
/// 'as' '(' StringLiteral ')' /// 'as' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -208,7 +233,7 @@ pub struct As {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the as statement. /// The selector of the as statement.
#[get = "pub"] #[get = "pub"]
as_selector: StringLiteral, as_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -225,7 +250,7 @@ impl SourceElement for As {
impl As { impl As {
/// Dissolves the [`As`] into its components. /// Dissolves the [`As`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.as_keyword, self.as_keyword,
self.open_paren, self.open_paren,
@ -235,10 +260,12 @@ impl As {
} }
} }
/// Represents an `align` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// Align: /// Align:
/// 'align' '(' StringLiteral ')' /// 'align' '(' AnyStringLiteral ')'
/// ; /// ;
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
@ -251,7 +278,7 @@ pub struct Align {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the align statement. /// The selector of the align statement.
#[get = "pub"] #[get = "pub"]
align_selector: StringLiteral, align_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -269,7 +296,7 @@ impl SourceElement for Align {
impl Align { impl Align {
/// Dissolves the [`Align`] into its components. /// Dissolves the [`Align`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.align_keyword, self.align_keyword,
self.open_paren, self.open_paren,
@ -279,10 +306,12 @@ impl Align {
} }
} }
/// Represents an `anchored` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// Anchored: /// Anchored:
/// 'anchored' '(' StringLiteral ')' /// 'anchored' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -296,7 +325,7 @@ pub struct Anchored {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the anchored statement. /// The selector of the anchored statement.
#[get = "pub"] #[get = "pub"]
anchored_selector: StringLiteral, anchored_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -312,7 +341,7 @@ impl SourceElement for Anchored {
impl Anchored { impl Anchored {
/// Dissolves the [`Anchored`] into its components. /// Dissolves the [`Anchored`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.anchored_keyword, self.anchored_keyword,
self.open_paren, self.open_paren,
@ -322,10 +351,12 @@ impl Anchored {
} }
} }
/// Represents an `asat` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// AsAt: /// AsAt:
/// 'asat' '(' StringLiteral ')' /// 'asat' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -339,7 +370,7 @@ pub struct AsAt {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the asat statement. /// The selector of the asat statement.
#[get = "pub"] #[get = "pub"]
asat_selector: StringLiteral, asat_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -355,7 +386,7 @@ impl SourceElement for AsAt {
impl AsAt { impl AsAt {
/// Dissolves the [`AsAt`] into its components. /// Dissolves the [`AsAt`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.asat_keyword, self.asat_keyword,
self.open_paren, self.open_paren,
@ -365,10 +396,12 @@ impl AsAt {
} }
} }
/// Represents an `at` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// At: /// At:
/// 'at' '(' StringLiteral ')' /// 'at' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -382,7 +415,7 @@ pub struct At {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the at statement. /// The selector of the at statement.
#[get = "pub"] #[get = "pub"]
at_selector: StringLiteral, at_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -398,7 +431,7 @@ impl SourceElement for At {
impl At { impl At {
/// Dissolves the [`At`] into its components. /// Dissolves the [`At`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.at_keyword, self.at_keyword,
self.open_paren, self.open_paren,
@ -408,10 +441,12 @@ impl At {
} }
} }
/// Represents a `facing` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// Facing: /// Facing:
/// 'facing' '(' StringLiteral ')' /// 'facing' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -425,7 +460,7 @@ pub struct Facing {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the facing statement. /// The selector of the facing statement.
#[get = "pub"] #[get = "pub"]
facing_selector: StringLiteral, facing_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -441,7 +476,7 @@ impl SourceElement for Facing {
impl Facing { impl Facing {
/// Dissolves the [`Facing`] into its components. /// Dissolves the [`Facing`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.facing_keyword, self.facing_keyword,
self.open_paren, self.open_paren,
@ -451,10 +486,12 @@ impl Facing {
} }
} }
/// Represents an `in` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// In: /// In:
/// 'in' '(' StringLiteral ')' /// 'in' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -468,7 +505,7 @@ pub struct In {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the in statement. /// The selector of the in statement.
#[get = "pub"] #[get = "pub"]
in_selector: StringLiteral, in_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -484,7 +521,7 @@ impl SourceElement for In {
impl In { impl In {
/// Dissolves the [`In`] into its components. /// Dissolves the [`In`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.in_keyword, self.in_keyword,
self.open_paren, self.open_paren,
@ -494,10 +531,12 @@ impl In {
} }
} }
/// Represents an `on` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// On: /// On:
/// 'on' '(' StringLiteral ')' /// 'on' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -511,7 +550,7 @@ pub struct On {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the on statement. /// The selector of the on statement.
#[get = "pub"] #[get = "pub"]
on_selector: StringLiteral, on_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -527,7 +566,7 @@ impl SourceElement for On {
impl On { impl On {
/// Dissolves the [`On`] into its components. /// Dissolves the [`On`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.on_keyword, self.on_keyword,
self.open_paren, self.open_paren,
@ -537,10 +576,12 @@ impl On {
} }
} }
/// Represents a `positioned` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// Positioned: /// Positioned:
/// 'positioned' '(' StringLiteral ')' /// 'positioned' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -554,7 +595,7 @@ pub struct Positioned {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the positioned statement. /// The selector of the positioned statement.
#[get = "pub"] #[get = "pub"]
positioned_selector: StringLiteral, positioned_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -570,7 +611,7 @@ impl SourceElement for Positioned {
impl Positioned { impl Positioned {
/// Dissolves the [`Positioned`] into its components. /// Dissolves the [`Positioned`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.positioned_keyword, self.positioned_keyword,
self.open_paren, self.open_paren,
@ -580,10 +621,12 @@ impl Positioned {
} }
} }
/// Represents a `rotated` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// Rotated: /// Rotated:
/// 'rotated' '(' StringLiteral ')' /// 'rotated' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -597,7 +640,7 @@ pub struct Rotated {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the rotated statement. /// The selector of the rotated statement.
#[get = "pub"] #[get = "pub"]
rotated_selector: StringLiteral, rotated_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -613,7 +656,7 @@ impl SourceElement for Rotated {
impl Rotated { impl Rotated {
/// Dissolves the [`Rotated`] into its components. /// Dissolves the [`Rotated`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.rotated_keyword, self.rotated_keyword,
self.open_paren, self.open_paren,
@ -623,10 +666,12 @@ impl Rotated {
} }
} }
/// Represents a `store` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// Store: /// Store:
/// 'store' '(' StringLiteral ')' /// 'store' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -640,7 +685,7 @@ pub struct Store {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the store statement. /// The selector of the store statement.
#[get = "pub"] #[get = "pub"]
store_selector: StringLiteral, store_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -656,7 +701,7 @@ impl SourceElement for Store {
impl Store { impl Store {
/// Dissolves the [`Store`] into its components. /// Dissolves the [`Store`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.store_keyword, self.store_keyword,
self.open_paren, self.open_paren,
@ -666,10 +711,12 @@ impl Store {
} }
} }
/// Represents a `summon` execute statement in the syntax tree.
///
/// Syntax Synopsis: /// Syntax Synopsis:
/// ```ebnf /// ```ebnf
/// Summon: /// Summon:
/// 'summon' '(' StringLiteral ')' /// 'summon' '(' AnyStringLiteral ')'
/// ; /// ;
/// ``` /// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -683,7 +730,7 @@ pub struct Summon {
open_paren: Punctuation, open_paren: Punctuation,
/// The selector of the summon statement. /// The selector of the summon statement.
#[get = "pub"] #[get = "pub"]
summon_selector: StringLiteral, summon_selector: AnyStringLiteral,
/// The close parenthesis. /// The close parenthesis.
#[get = "pub"] #[get = "pub"]
close_paren: Punctuation, close_paren: Punctuation,
@ -699,7 +746,7 @@ impl SourceElement for Summon {
impl Summon { impl Summon {
/// Dissolves the [`Summon`] into its components. /// Dissolves the [`Summon`] into its components.
#[must_use] #[must_use]
pub fn dissolve(self) -> (Keyword, Punctuation, StringLiteral, Punctuation) { pub fn dissolve(self) -> (Keyword, Punctuation, AnyStringLiteral, Punctuation) {
( (
self.summon_keyword, self.summon_keyword,
self.open_paren, self.open_paren,
@ -711,10 +758,14 @@ impl Summon {
impl<'a> Parser<'a> { impl<'a> Parser<'a> {
/// Parses an [`ExecuteBlock`]. /// 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( pub fn parse_execute_block_statement(
&mut self, &mut self,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> Option<ExecuteBlock> { ) -> ParseResult<ExecuteBlock> {
match self.stop_at_significant() { match self.stop_at_significant() {
Reading::Atomic(Token::Keyword(if_keyword)) Reading::Atomic(Token::Keyword(if_keyword))
if if_keyword.keyword == KeywordKind::If => if if_keyword.keyword == KeywordKind::If =>
@ -739,14 +790,17 @@ impl<'a> Parser<'a> {
// eat the else keyword // eat the else keyword
parser.forward(); 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, block,
Else { Else {
else_keyword, else_keyword,
@ -755,11 +809,11 @@ impl<'a> Parser<'a> {
)) ))
}); });
if let Some((block, else_tail)) = else_tail { if let Ok((block, else_tail)) = else_tail {
Some(ExecuteBlock::IfElse(conditional, block, else_tail)) Ok(ExecuteBlock::IfElse(conditional, block, else_tail))
} else { } else {
let tail = self.parse_execute_block_tail(handler)?; let tail = self.parse_execute_block_tail(handler)?;
Some(ExecuteBlock::HeadTail( Ok(ExecuteBlock::HeadTail(
ExecuteBlockHead::Conditional(conditional), ExecuteBlockHead::Conditional(conditional),
tail, tail,
)) ))
@ -773,15 +827,16 @@ impl<'a> Parser<'a> {
let argument = match self.stop_at_significant() { let argument = match self.stop_at_significant() {
Reading::IntoDelimited(punc) if punc.punctuation == '(' => self.step_into( Reading::IntoDelimited(punc) if punc.punctuation == '(' => self.step_into(
Delimiter::Parenthesis, Delimiter::Parenthesis,
|parser| parser.parse_string_literal(handler), |parser| parser.parse_any_string_literal(handler),
handler, handler,
), ),
unexpected => { unexpected => {
handler.receive(syntax::error::Error::from(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::Punctuation('('), expected: SyntaxKind::Punctuation('('),
found: unexpected.into_token(), 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)?; let head = head_from_keyword(keyword, argument)?;
Some(ExecuteBlock::HeadTail(head, tail)) Ok(ExecuteBlock::HeadTail(head, tail))
} }
// unexpected // unexpected
unexpected => { unexpected => {
handler.receive(syntax::error::Error::from(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::ExecuteBlock, expected: SyntaxKind::ExecuteBlock,
found: unexpected.into_token(), found: unexpected.into_token(),
})); });
None handler.receive(err.clone());
Err(err)
} }
} }
} }
@ -806,7 +862,7 @@ impl<'a> Parser<'a> {
fn parse_execute_block_tail( fn parse_execute_block_tail(
&mut self, &mut self,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> Option<ExecuteBlockTail> { ) -> ParseResult<ExecuteBlockTail> {
match self.stop_at_significant() { match self.stop_at_significant() {
// nested execute block // nested execute block
Reading::Atomic(Token::Punctuation(punc)) if punc.punctuation == ',' => { 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)?; let execute_block = self.parse_execute_block_statement(handler)?;
Some(ExecuteBlockTail::ExecuteBlock( Ok(ExecuteBlockTail::ExecuteBlock(
punc, punc,
Box::new(execute_block), Box::new(execute_block),
)) ))
@ -825,15 +881,16 @@ impl<'a> Parser<'a> {
Reading::IntoDelimited(punc) if punc.punctuation == '{' => { Reading::IntoDelimited(punc) if punc.punctuation == '{' => {
let block = self.parse_block(handler)?; let block = self.parse_block(handler)?;
Some(ExecuteBlockTail::Block(block)) Ok(ExecuteBlockTail::Block(block))
} }
unexpected => { unexpected => {
handler.receive(syntax::error::Error::from(UnexpectedSyntax { let err = Error::UnexpectedSyntax(UnexpectedSyntax {
expected: SyntaxKind::ExecuteBlockTail, expected: SyntaxKind::ExecuteBlockTail,
found: unexpected.into_token(), found: unexpected.into_token(),
})); });
None handler.receive(err.clone());
Err(err)
} }
} }
} }
@ -841,9 +898,9 @@ impl<'a> Parser<'a> {
fn head_from_keyword( fn head_from_keyword(
keyword: Keyword, keyword: Keyword,
argument: DelimitedTree<StringLiteral>, argument: DelimitedTree<AnyStringLiteral>,
) -> Option<ExecuteBlockHead> { ) -> ParseResult<ExecuteBlockHead> {
Some(match keyword.keyword { Ok(match keyword.keyword {
KeywordKind::Align => Align { KeywordKind::Align => Align {
align_keyword: keyword, align_keyword: keyword,
open_paren: argument.open, open_paren: argument.open,
@ -931,3 +988,91 @@ fn head_from_keyword(
_ => unreachable!("The keyword is not a valid execute block head."), _ => 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
}
}

View File

@ -1,10 +1,19 @@
//! Conversion functions for converting between tokens/ast-nodes and [`shulkerbox`] types //! 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::{
BinaryCondition, Condition, ConditionalBinaryOperator, ConditionalPrefixOperator, lexical::token::{MacroStringLiteral, MacroStringLiteralPart},
PrimaryCondition, syntax::syntax_tree::{
condition::{
BinaryCondition, Condition, ConditionalBinaryOperator, ConditionalPrefixOperator,
PrimaryCondition,
},
AnyStringLiteral,
},
}; };
impl From<Condition> for DpCondition { impl From<Condition> for DpCondition {
@ -19,11 +28,9 @@ impl From<Condition> for DpCondition {
impl From<PrimaryCondition> for DpCondition { impl From<PrimaryCondition> for DpCondition {
fn from(value: PrimaryCondition) -> Self { fn from(value: PrimaryCondition) -> Self {
match value { match value {
PrimaryCondition::StringLiteral(literal) => { PrimaryCondition::StringLiteral(literal) => Self::Atom(literal.into()),
Self::Atom(literal.str_content().to_string())
}
PrimaryCondition::Parenthesized(cond) => cond.dissolve().1.into(), PrimaryCondition::Parenthesized(cond) => cond.dissolve().1.into(),
PrimaryCondition::Prefix(prefix) => match prefix.operator() { PrimaryCondition::Unary(prefix) => match prefix.operator() {
ConditionalPrefixOperator::LogicalNot(_) => { ConditionalPrefixOperator::LogicalNot(_) => {
Self::Not(Box::new(prefix.dissolve().1.into())) 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 { impl From<BinaryCondition> for DpCondition {
fn from(value: BinaryCondition) -> Self { fn from(value: BinaryCondition) -> Self {
let (lhs, op, rhs) = value.dissolve(); let (lhs, op, rhs) = value.dissolve();

View File

@ -1,36 +1,79 @@
//! Errors that can occur during transpilation. //! Errors that can occur during transpilation.
use std::fmt::Display; use std::{collections::BTreeMap, fmt::Display};
use getset::Getters;
use itertools::Itertools;
use crate::{ use crate::{
base::{ base::{
log::{Message, Severity, SourceCodeDisplay}, 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. /// Errors that can occur during transpilation.
#[allow(clippy::module_name_repetitions, missing_docs)] #[allow(clippy::module_name_repetitions, missing_docs)]
#[derive(Debug, thiserror::Error, Clone)] #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
pub enum TranspileError { pub enum TranspileError {
#[error(transparent)] #[error(transparent)]
MissingFunctionDeclaration(#[from] MissingFunctionDeclaration), MissingFunctionDeclaration(#[from] MissingFunctionDeclaration),
#[error("Unexpected expression: {}", .0.span().str())] #[error(transparent)]
UnexpectedExpression(Expression), UnexpectedExpression(#[from] UnexpectedExpression),
#[error("Lua code evaluation is disabled.")] #[error("Lua code evaluation is disabled.")]
LuaDisabled, LuaDisabled,
#[error("Lua runtime error: {}", .0)] #[error(transparent)]
LuaRuntimeError(String), LuaRuntimeError(#[from] LuaRuntimeError),
#[error(transparent)]
ConflictingFunctionNames(#[from] ConflictingFunctionNames),
#[error(transparent)]
InvalidFunctionArguments(#[from] InvalidFunctionArguments),
} }
/// The result of a transpilation operation. /// The result of a transpilation operation.
pub type TranspileResult<T> = Result<T, TranspileError>; pub type TranspileResult<T> = Result<T, TranspileError>;
/// An error that occurs when a function declaration is missing. /// 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 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 { impl Display for MissingFunctionDeclaration {
@ -41,12 +84,65 @@ impl Display for MissingFunctionDeclaration {
); );
write!(f, "{}", Message::new(Severity::Error, message))?; 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!( write!(
f, f,
"\n{}", "\n{}",
SourceCodeDisplay::new(&self.span, Option::<u8>::None) SourceCodeDisplay::new(&self.span, help_message.as_ref())
) )
} }
} }
impl std::error::Error for MissingFunctionDeclaration {} 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,
}
}
}

View File

@ -2,12 +2,12 @@
#[cfg(feature = "lua")] #[cfg(feature = "lua")]
mod enabled { mod enabled {
use mlua::Lua; use mlua::{Lua, Value};
use crate::{ use crate::{
base::{self, source_file::SourceElement, Handler}, base::{self, source_file::SourceElement, Handler},
syntax::syntax_tree::expression::LuaCode, syntax::syntax_tree::expression::LuaCode,
transpile::error::{TranspileError, TranspileResult}, transpile::error::{LuaRuntimeError, TranspileError, TranspileResult},
}; };
impl LuaCode { impl LuaCode {
@ -16,7 +16,10 @@ mod enabled {
/// # Errors /// # Errors
/// - If Lua code evaluation is disabled. /// - If Lua code evaluation is disabled.
#[tracing::instrument(level = "debug", name = "eval_lua", skip_all, ret)] #[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"); tracing::debug!("Evaluating Lua code");
let lua = Lua::new(); let lua = Lua::new();
@ -24,7 +27,7 @@ mod enabled {
let name = { let name = {
let span = self.span(); let span = self.span();
let file = span.source_file(); 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 start = span.start_location();
let end = span.end_location().unwrap_or_else(|| { let end = span.end_location().unwrap_or_else(|| {
@ -43,29 +46,60 @@ mod enabled {
) )
}; };
self.add_globals(&lua).unwrap();
let lua_result = lua let lua_result = lua
.load(self.code()) .load(self.code())
.set_name(name) .set_name(name)
.eval::<String>() .eval::<Value>()
.map_err(|err| { .map_err(|err| {
let err = TranspileError::from(err); let err =
handler.receive(err.clone()); TranspileError::from(LuaRuntimeError::from_lua_err(&err, self.span()));
handler.receive(crate::Error::from(err.clone()));
err err
})?; })?;
Ok(lua_result) self.handle_lua_result(lua_result).inspect_err(|err| {
handler.receive(err.clone());
})
} }
}
impl From<mlua::Error> for TranspileError { fn add_globals(&self, lua: &Lua) -> mlua::Result<()> {
fn from(value: mlua::Error) -> Self { let globals = lua.globals();
let string = value.to_string();
Self::LuaRuntimeError( let location = {
string let span = self.span();
.strip_prefix("runtime error: ") let file = span.source_file();
.unwrap_or(&string) file.path_relative().unwrap_or_else(|| file.path().clone())
.to_string(), };
) 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 /// # Errors
/// - If Lua code evaluation is disabled. /// - 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); handler.receive(TranspileError::LuaDisabled);
tracing::error!("Lua code evaluation is disabled"); tracing::error!("Lua code evaluation is disabled");
Err(TranspileError::LuaDisabled) Err(TranspileError::LuaDisabled)

View File

@ -1,9 +1,14 @@
//! The transpile module is responsible for transpiling the abstract syntax tree into a data pack. //! 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)] #[doc(hidden)]
#[cfg(feature = "shulkerbox")] #[cfg(feature = "shulkerbox")]
pub mod conversions; pub mod conversions;
mod error; mod error;
#[doc(inline)] #[doc(inline)]
#[allow(clippy::module_name_repetitions)] #[allow(clippy::module_name_repetitions)]
pub use error::{TranspileError, TranspileResult}; pub use error::{TranspileError, TranspileResult};
@ -11,7 +16,18 @@ pub use error::{TranspileError, TranspileResult};
pub mod lua; pub mod lua;
#[cfg(feature = "shulkerbox")] #[cfg(feature = "shulkerbox")]
mod transpiler; mod transpiler;
#[doc(inline)] #[cfg(feature = "shulkerbox")]
#[cfg_attr(feature = "shulkerbox", doc(inline))]
pub use transpiler::Transpiler; 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>>,
}

View File

@ -1,7 +1,10 @@
//! Transpiler for `ShulkerScript` //! Transpiler for `Shulkerscript`
use chksum_md5 as md5; 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}; use shulkerbox::datapack::{self, Command, Datapack, Execute};
@ -11,6 +14,7 @@ use crate::{
source_file::{SourceElement, Span}, source_file::{SourceElement, Span},
Handler, Handler,
}, },
semantic::error::{ConflictingFunctionNames, InvalidFunctionArguments, UnexpectedExpression},
syntax::syntax_tree::{ syntax::syntax_tree::{
declaration::{Declaration, ImportItems}, declaration::{Declaration, ImportItems},
expression::{Expression, FunctionCall, Primary}, expression::{Expression, FunctionCall, Primary},
@ -23,25 +27,21 @@ use crate::{
transpile::error::MissingFunctionDeclaration, transpile::error::MissingFunctionDeclaration,
}; };
use super::error::{TranspileError, TranspileResult}; use super::{
error::{TranspileError, TranspileResult},
FunctionData,
};
/// A transpiler for `ShulkerScript`. /// A transpiler for `Shulkerscript`.
#[derive(Debug)] #[derive(Debug)]
pub struct Transpiler { pub struct Transpiler {
datapack: shulkerbox::datapack::Datapack, datapack: shulkerbox::datapack::Datapack,
/// Key: (program identifier, function name) /// Key: (program identifier, function name)
functions: RwLock<HashMap<(String, String), FunctionData>>, functions: BTreeMap<(String, String), FunctionData>,
function_locations: RwLock<HashMap<(String, String), (String, bool)>>, /// Key: (program identifier, function name), Value: (function location, public)
aliases: RwLock<HashMap<(String, String), (String, String)>>, function_locations: HashMap<(String, String), (String, bool)>,
} /// Key: alias, Value: target
aliases: 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>>,
} }
impl Transpiler { impl Transpiler {
@ -50,9 +50,9 @@ impl Transpiler {
pub fn new(pack_format: u8) -> Self { pub fn new(pack_format: u8) -> Self {
Self { Self {
datapack: shulkerbox::datapack::Datapack::new(pack_format), datapack: shulkerbox::datapack::Datapack::new(pack_format),
functions: RwLock::new(HashMap::new()), functions: BTreeMap::new(),
function_locations: RwLock::new(HashMap::new()), function_locations: HashMap::new(),
aliases: RwLock::new(HashMap::new()), aliases: HashMap::new(),
} }
} }
@ -80,9 +80,8 @@ impl Transpiler {
let mut always_transpile_functions = Vec::new(); 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() { for (_, data) in functions.iter() {
let always_transpile_function = data.annotations.contains_key("tick") let always_transpile_function = data.annotations.contains_key("tick")
|| data.annotations.contains_key("load") || data.annotations.contains_key("load")
@ -99,7 +98,7 @@ impl Transpiler {
); );
for identifier_span in always_transpile_functions { 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(()) Ok(())
@ -124,7 +123,7 @@ impl Transpiler {
&mut self, &mut self,
declaration: &Declaration, declaration: &Declaration,
namespace: &Namespace, namespace: &Namespace,
_handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) { ) {
let program_identifier = declaration.span().source_file().identifier().clone(); let program_identifier = declaration.span().source_file().identifier().clone();
match declaration { match declaration {
@ -144,11 +143,21 @@ impl Transpiler {
) )
}) })
.collect(); .collect();
self.functions.write().unwrap().insert( #[allow(clippy::significant_drop_tightening)]
self.functions.insert(
(program_identifier, name), (program_identifier, name),
FunctionData { FunctionData {
namespace: namespace.namespace_name().str_content().to_string(), namespace: namespace.namespace_name().str_content().to_string(),
identifier_span: identifier_span.clone(), 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, statements,
public: function.is_public(), public: function.is_public(),
annotations, annotations,
@ -160,15 +169,16 @@ impl Transpiler {
let import_identifier = let import_identifier =
super::util::calculate_import_identifier(&program_identifier, path); super::util::calculate_import_identifier(&program_identifier, path);
let mut aliases = self.aliases.write().unwrap(); let aliases = &mut self.aliases;
match import.items() { 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) => { ImportItems::Named(list) => {
let items = iter::once(list.first()) for item in list.elements() {
.chain(list.rest().iter().map(|(_, ident)| ident));
for item in items {
let name = item.span.str(); let name = item.span.str();
aliases.insert( aliases.insert(
(program_identifier.clone(), name.to_string()), (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( fn get_or_transpile_function(
&mut self, &mut self,
identifier_span: &Span, identifier_span: &Span,
arguments: Option<&[&Expression]>,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> TranspileResult<String> { ) -> TranspileResult<(String, Option<BTreeMap<String, String>>)> {
let program_identifier = identifier_span.source_file().identifier(); let program_identifier = identifier_span.source_file().identifier();
let program_query = ( let program_query = (
program_identifier.to_string(), program_identifier.to_string(),
identifier_span.str().to_string(), identifier_span.str().to_string(),
); );
let alias_query = { let alias_query = self.aliases.get(&program_query).cloned();
let aliases = self.aliases.read().unwrap();
aliases.get(&program_query).cloned()
};
let already_transpiled = { let already_transpiled = {
let locations = self.function_locations.read().unwrap(); let locations = &self.function_locations;
locations locations
.get(&program_query) .get(&program_query)
.or_else(|| { .or_else(|| {
@ -214,7 +238,7 @@ impl Transpiler {
tracing::trace!("Function not transpiled yet, transpiling."); tracing::trace!("Function not transpiled yet, transpiling.");
let statements = { let statements = {
let functions = self.functions.read().unwrap(); let functions = &self.functions;
let function_data = functions let function_data = functions
.get(&program_query) .get(&program_query)
.or_else(|| { .or_else(|| {
@ -224,18 +248,20 @@ impl Transpiler {
}) })
.ok_or_else(|| { .ok_or_else(|| {
let error = TranspileError::MissingFunctionDeclaration( let error = TranspileError::MissingFunctionDeclaration(
MissingFunctionDeclaration { MissingFunctionDeclaration::from_context(
span: identifier_span.clone(), identifier_span.clone(),
}, functions,
),
); );
handler.receive(error.clone()); handler.receive(error.clone());
error error
})?; })?;
function_data.statements.clone() function_data.statements.clone()
}; };
let commands = self.transpile_function(&statements, program_identifier, handler)?; let commands = self.transpile_function(&statements, program_identifier, handler)?;
let functions = self.functions.read().unwrap(); let functions = &self.functions;
let function_data = functions let function_data = functions
.get(&program_query) .get(&program_query)
.or_else(|| { .or_else(|| {
@ -244,10 +270,12 @@ impl Transpiler {
.and_then(|q| functions.get(&q).filter(|f| f.public)) .and_then(|q| functions.get(&q).filter(|f| f.public))
}) })
.ok_or_else(|| { .ok_or_else(|| {
let error = let error = TranspileError::MissingFunctionDeclaration(
TranspileError::MissingFunctionDeclaration(MissingFunctionDeclaration { MissingFunctionDeclaration::from_context(
span: identifier_span.clone(), identifier_span.clone(),
}); functions,
),
);
handler.receive(error.clone()); handler.receive(error.clone());
error error
})?; })?;
@ -259,16 +287,24 @@ impl Transpiler {
|| { || {
let hash_data = let hash_data =
program_identifier.to_string() + "\0" + identifier_span.str(); 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, Clone::clone,
) )
.unwrap_or_else(|| identifier_span.str().to_string()); .unwrap_or_else(|| identifier_span.str().to_string());
let function = self let namespace = self.datapack.namespace_mut(&function_data.namespace);
.datapack
.namespace_mut(&function_data.namespace) if namespace.function(&modified_name).is_some() {
.function_mut(&modified_name); 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); function.get_commands_mut().extend(commands);
let function_location = format!( let function_location = format!(
@ -283,7 +319,7 @@ impl Transpiler {
self.datapack.add_load(&function_location); self.datapack.add_load(&function_location);
} }
self.function_locations.write().unwrap().insert( self.function_locations.insert(
( (
program_identifier.to_string(), program_identifier.to_string(),
identifier_span.str().to_string(), identifier_span.str().to_string(),
@ -292,19 +328,96 @@ impl Transpiler {
); );
} }
let locations = self.function_locations.read().unwrap(); let parameters = {
locations let function_data = self
.functions
.get(&program_query)
.or_else(|| {
alias_query
.clone()
.and_then(|q| self.functions.get(&q).filter(|f| f.public))
})
.ok_or_else(|| {
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) .get(&program_query)
.or_else(|| alias_query.and_then(|q| locations.get(&q).filter(|(_, p)| *p))) .or_else(|| {
alias_query.and_then(|q| self.function_locations.get(&q).filter(|(_, p)| *p))
})
.ok_or_else(|| { .ok_or_else(|| {
let error = let error = TranspileError::MissingFunctionDeclaration(
TranspileError::MissingFunctionDeclaration(MissingFunctionDeclaration { MissingFunctionDeclaration::from_context(
span: identifier_span.clone(), identifier_span.clone(),
}); &self.functions,
),
);
handler.receive(error.clone()); handler.receive(error.clone());
error 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( fn transpile_function(
@ -349,8 +462,11 @@ impl Transpiler {
Expression::Primary(Primary::StringLiteral(string)) => { Expression::Primary(Primary::StringLiteral(string)) => {
Ok(Some(Command::Raw(string.str_content().to_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)) => { Expression::Primary(Primary::Lua(code)) => {
Ok(Some(Command::Raw(code.eval_string(handler)?))) Ok(code.eval_string(handler)?.map(Command::Raw))
} }
}, },
Statement::Block(_) => { Statement::Block(_) => {
@ -391,7 +507,9 @@ impl Transpiler {
self.transpile_function_call(func, handler).map(Some) self.transpile_function_call(func, handler).map(Some)
} }
unexpected => { unexpected => {
let error = TranspileError::UnexpectedExpression(unexpected.clone()); let error = TranspileError::UnexpectedExpression(UnexpectedExpression(
unexpected.clone(),
));
handler.receive(error.clone()); handler.receive(error.clone());
Err(error) Err(error)
} }
@ -404,8 +522,29 @@ impl Transpiler {
func: &FunctionCall, func: &FunctionCall,
handler: &impl Handler<base::Error>, handler: &impl Handler<base::Error>,
) -> TranspileResult<Command> { ) -> TranspileResult<Command> {
let location = self.get_or_transpile_function(&func.identifier().span, handler)?; let arguments = func
Ok(Command::Raw(format!("function {location}"))) .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( fn transpile_execute_block(
@ -568,53 +707,53 @@ impl Transpiler {
None None
} }
} }
ExecuteBlockHead::As(as_) => { ExecuteBlockHead::As(r#as) => {
let selector = as_.as_selector().str_content(); let selector = r#as.as_selector();
tail.map(|tail| Execute::As(selector.to_string(), Box::new(tail))) tail.map(|tail| Execute::As(selector.into(), Box::new(tail)))
} }
ExecuteBlockHead::At(at) => { ExecuteBlockHead::At(at) => {
let selector = at.at_selector().str_content(); let selector = at.at_selector();
tail.map(|tail| Execute::At(selector.to_string(), Box::new(tail))) tail.map(|tail| Execute::At(selector.into(), Box::new(tail)))
} }
ExecuteBlockHead::Align(align) => { ExecuteBlockHead::Align(align) => {
let align = align.align_selector().str_content(); let align = align.align_selector();
tail.map(|tail| Execute::Align(align.to_string(), Box::new(tail))) tail.map(|tail| Execute::Align(align.into(), Box::new(tail)))
} }
ExecuteBlockHead::Anchored(anchored) => { ExecuteBlockHead::Anchored(anchored) => {
let anchor = anchored.anchored_selector().str_content(); let anchor = anchored.anchored_selector();
tail.map(|tail| Execute::Anchored(anchor.to_string(), Box::new(tail))) tail.map(|tail| Execute::Anchored(anchor.into(), Box::new(tail)))
} }
ExecuteBlockHead::In(in_) => { ExecuteBlockHead::In(r#in) => {
let dimension = in_.in_selector().str_content(); let dimension = r#in.in_selector();
tail.map(|tail| Execute::In(dimension.to_string(), Box::new(tail))) tail.map(|tail| Execute::In(dimension.into(), Box::new(tail)))
} }
ExecuteBlockHead::Positioned(positioned) => { ExecuteBlockHead::Positioned(positioned) => {
let position = positioned.positioned_selector().str_content(); let position = positioned.positioned_selector();
tail.map(|tail| Execute::Positioned(position.to_string(), Box::new(tail))) tail.map(|tail| Execute::Positioned(position.into(), Box::new(tail)))
} }
ExecuteBlockHead::Rotated(rotated) => { ExecuteBlockHead::Rotated(rotated) => {
let rotation = rotated.rotated_selector().str_content(); let rotation = rotated.rotated_selector();
tail.map(|tail| Execute::Rotated(rotation.to_string(), Box::new(tail))) tail.map(|tail| Execute::Rotated(rotation.into(), Box::new(tail)))
} }
ExecuteBlockHead::Facing(facing) => { ExecuteBlockHead::Facing(facing) => {
let facing = facing.facing_selector().str_content(); let facing = facing.facing_selector();
tail.map(|tail| Execute::Facing(facing.to_string(), Box::new(tail))) tail.map(|tail| Execute::Facing(facing.into(), Box::new(tail)))
} }
ExecuteBlockHead::AsAt(as_at) => { ExecuteBlockHead::AsAt(as_at) => {
let selector = as_at.asat_selector().str_content(); let selector = as_at.asat_selector();
tail.map(|tail| Execute::AsAt(selector.to_string(), Box::new(tail))) tail.map(|tail| Execute::AsAt(selector.into(), Box::new(tail)))
} }
ExecuteBlockHead::On(on) => { ExecuteBlockHead::On(on) => {
let dimension = on.on_selector().str_content(); let dimension = on.on_selector();
tail.map(|tail| Execute::On(dimension.to_string(), Box::new(tail))) tail.map(|tail| Execute::On(dimension.into(), Box::new(tail)))
} }
ExecuteBlockHead::Store(store) => { ExecuteBlockHead::Store(store) => {
let store = store.store_selector().str_content(); let store = store.store_selector();
tail.map(|tail| Execute::Store(store.to_string(), Box::new(tail))) tail.map(|tail| Execute::Store(store.into(), Box::new(tail)))
} }
ExecuteBlockHead::Summon(summon) => { ExecuteBlockHead::Summon(summon) => {
let entity = summon.summon_selector().str_content(); let entity = summon.summon_selector();
tail.map(|tail| Execute::Summon(entity.to_string(), Box::new(tail))) tail.map(|tail| Execute::Summon(entity.into(), Box::new(tail)))
} }
}) })
} }

View File

@ -1,3 +1,8 @@
//! Utility methods for transpiling
#[cfg(feature = "shulkerbox")]
use chksum_md5 as md5;
fn normalize_program_identifier<S>(identifier: S) -> String fn normalize_program_identifier<S>(identifier: S) -> String
where where
S: AsRef<str>, S: AsRef<str>,
@ -19,6 +24,8 @@ where
.join("/") .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 pub fn calculate_import_identifier<S, T>(current_identifier: S, import_path: T) -> String
where where
S: AsRef<str>, S: AsRef<str>,
@ -32,3 +39,25 @@ where
normalize_program_identifier(identifier_elements.join("/") + "/" + import_path.as_ref()) 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)
}
}

82
src/util.rs Normal file
View File

@ -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\!"
);
}
}

View File

@ -28,9 +28,9 @@ fn transpile_test1() {
main_fn.add_command(Command::Raw("say Hello, World!".to_string())); main_fn.add_command(Command::Raw("say Hello, World!".to_string()));
let exec_cmd = Command::Execute(Execute::As( let exec_cmd = Command::Execute(Execute::As(
"@a".to_string(), "@a".to_string().into(),
Box::new(Execute::If( 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( Box::new(Execute::Run(Box::new(Command::Raw(
"say You are close to me!".to_string(), "say You are close to me!".to_string(),
)))), )))),