chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

View File

@@ -0,0 +1 @@
{"files":{".cargo_vcs_info.json":"ccf56d58a229b7f9fe8b3353212dc314432b228c05d5ddee5241e180899fe5bb","Cargo.lock":"c618b8ceddc852fde9d6b6deb476dcf29fda5cf47e9d4cacfad5aef3dcbb7b47","Cargo.toml":"363d8183e01daf8edc6412251a239903a57432774bd5465cdd8f1149e78ef9fb","Cargo.toml.orig":"57ba4ba0bbe5374aa08697b9d42ecb61e102826250352e2b7633001a1db16433","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","_README.md":"214e60d12802a3c5990520ff21e6e8a788b800cb49b16663e45ebdc417202ac4","src/docs.rs":"9f91acd72f5f620e388c728a6caf565de536cd472e41b4f8448aaadd70e9aefc","src/generator.rs":"e68d1dc73ab02dd994e1c3646a7d69a8470de37ab4e2b3650a6ce2aaf3f97156","src/lib.rs":"c515d9b83cd11ca3b7d9aecc3493adeb0e4eb370c0b274c4bcd1be20a48ff482","src/macros.rs":"897d9004449b1c219f17c079630a790f3de1a27f61bc6a03cd777a163a6a1fba","src/parse_derive.rs":"44fd33409a368c740d98e4eafba49db2da584dff9cda33b3de640b532a974f12","tests/base.pest":"30f6965031bc52937114f60233a327e41ccc43429ae41a8e40c7b7c8006c466f","tests/test.pest":"f3fea8154a9a26c773ab8392685039d0d84bd845587bb2d42b970946f7967ee8"},"package":"8040c4647b13b210a963c1ed407c1ff4fdfa01c31d6d2a098218702e6664f94f"}

View File

@@ -0,0 +1,6 @@
{
"git": {
"sha1": "79dd30d11aab6f0fba3cd79bd48f456209b966b3"
},
"path_in_vcs": "generator"
}

3970
vendor/pest_generator/Cargo.lock generated vendored Normal file

File diff suppressed because it is too large Load Diff

61
vendor/pest_generator/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,61 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.83"
name = "pest_generator"
version = "2.8.6"
authors = ["Dragoș Tiselice <dragostiselice@gmail.com>"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "pest code generator"
homepage = "https://pest.rs/"
documentation = "https://docs.rs/pest"
readme = "_README.md"
keywords = [
"pest",
"generator",
]
categories = ["parsing"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/pest-parser/pest"
[features]
default = ["std"]
export-internal = []
grammar-extras = ["pest_meta/grammar-extras"]
not-bootstrap-in-src = ["pest_meta/not-bootstrap-in-src"]
std = ["pest/std"]
[lib]
name = "pest_generator"
path = "src/lib.rs"
[dependencies.pest]
version = "2.8.6"
default-features = false
[dependencies.pest_meta]
version = "2.8.6"
[dependencies.proc-macro2]
version = "1.0"
[dependencies.quote]
version = "1.0"
[dependencies.syn]
version = "2.0"

201
vendor/pest_generator/LICENSE-APACHE vendored 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 [yyyy] [name of copyright owner]
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.

23
vendor/pest_generator/LICENSE-MIT vendored Normal file
View File

@@ -0,0 +1,23 @@
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

233
vendor/pest_generator/_README.md vendored Normal file
View File

@@ -0,0 +1,233 @@
<p align="center">
<img src="https://raw.github.com/pest-parser/pest/master/pest-logo.svg?sanitize=true" width="80%"/>
</p>
# pest. The Elegant Parser
[![Join the chat at https://gitter.im/pest-parser/pest](https://badges.gitter.im/dragostis/pest.svg)](https://gitter.im/pest-parser/pest?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Book](https://img.shields.io/badge/book-WIP-4d76ae.svg)](https://pest.rs/book)
[![Docs](https://docs.rs/pest/badge.svg)](https://docs.rs/pest)
[![pest Continuous Integration](https://github.com/pest-parser/pest/actions/workflows/ci.yml/badge.svg)](https://github.com/pest-parser/pest/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/pest-parser/pest/branch/master/graph/badge.svg)](https://codecov.io/gh/pest-parser/pest)
<a href="https://blog.rust-lang.org/2024/11/28/Rust-1.83.0/"><img alt="Rustc Version 1.83.0+" src="https://img.shields.io/badge/rustc-1.83.0%2B-lightgrey.svg"/></a>
[![Crates.io](https://img.shields.io/crates/d/pest.svg)](https://crates.io/crates/pest)
[![Crates.io](https://img.shields.io/crates/v/pest.svg)](https://crates.io/crates/pest)
pest is a general purpose parser written in Rust with a focus on accessibility,
correctness, and performance. It uses parsing expression grammars
(or [PEG]) as input, which are similar in spirit to regular expressions, but
which offer the enhanced expressivity needed to parse complex languages.
[PEG]: https://en.wikipedia.org/wiki/Parsing_expression_grammar
## Getting started
The recommended way to start parsing with pest is to read the official [book].
Other helpful resources:
* API reference on [docs.rs]
* play with grammars and share them on our [fiddle]
* find previous common questions answered or ask questions on [GitHub Discussions]
* leave feedback, ask questions, or greet us on [Gitter] or [Discord]
[book]: https://pest.rs/book
[docs.rs]: https://docs.rs/pest
[fiddle]: https://pest.rs/#editor
[Gitter]: https://gitter.im/pest-parser/pest
[Discord]: https://discord.gg/XEGACtWpT2
[GitHub Discussions]: https://github.com/pest-parser/pest/discussions
## Example
The following is an example of a grammar for a list of alphanumeric identifiers
where all identifiers don't start with a digit:
```rust
alpha = { 'a'..'z' | 'A'..'Z' }
digit = { '0'..'9' }
ident = { !digit ~ (alpha | digit)+ }
ident_list = _{ ident ~ (" " ~ ident)* }
// ^
// ident_list rule is silent which means it produces no tokens
```
Grammars are saved in separate .pest files which are never mixed with procedural
code. This results in an always up-to-date formalization of a language that is
easy to read and maintain.
## Meaningful error reporting
Based on the grammar definition, the parser also includes automatic error
reporting. For the example above, the input `"123"` will result in:
```
thread 'main' panicked at ' --> 1:1
|
1 | 123
| ^---
|
= unexpected digit', src/main.rs:12
```
while `"ab *"` will result in:
```
thread 'main' panicked at ' --> 1:1
|
1 | ab *
| ^---
|
= expected ident', src/main.rs:12
```
These error messages can be obtained from their default `Display` implementation,
e.g. `panic!("{}", parser_result.unwrap_err())` or `println!("{}", e)`.
## Pairs API
The grammar can be used to derive a `Parser` implementation automatically.
Parsing returns an iterator of nested token pairs:
```rust
use pest_derive::Parser;
use pest::Parser;
#[derive(Parser)]
#[grammar = "ident.pest"]
struct IdentParser;
fn main() {
let pairs = IdentParser::parse(Rule::ident_list, "a1 b2").unwrap_or_else(|e| panic!("{}", e));
// Because ident_list is silent, the iterator will contain idents
for pair in pairs {
// A pair is a combination of the rule which matched and a span of input
println!("Rule: {:?}", pair.as_rule());
println!("Span: {:?}", pair.as_span());
println!("Text: {}", pair.as_str());
// A pair can be converted to an iterator of the tokens which make it up:
for inner_pair in pair.into_inner() {
match inner_pair.as_rule() {
Rule::alpha => println!("Letter: {}", inner_pair.as_str()),
Rule::digit => println!("Digit: {}", inner_pair.as_str()),
_ => unreachable!()
};
}
}
}
```
This produces the following output:
```
Rule: ident
Span: Span { start: 0, end: 2 }
Text: a1
Letter: a
Digit: 1
Rule: ident
Span: Span { start: 3, end: 5 }
Text: b2
Letter: b
Digit: 2
```
### Defining multiple parsers in a single file
The current automatic `Parser` derivation will produce the `Rule` enum
which would have name conflicts if one tried to define multiple such structs
that automatically derive `Parser`. One possible way around it is to put each
parser struct in a separate namespace:
```rust
mod a {
#[derive(Parser)]
#[grammar = "a.pest"]
pub struct ParserA;
}
mod b {
#[derive(Parser)]
#[grammar = "b.pest"]
pub struct ParserB;
}
```
## Other features
* Precedence climbing
* Input handling
* Custom errors
* Runs on stable Rust
## Projects using pest
You can find more projects and ecosystem tools in the [awesome-pest](https://github.com/pest-parser/awesome-pest) repo.
* [pest_meta](https://github.com/pest-parser/pest/blob/master/meta/src/grammar.pest) (bootstrapped)
* [AshPaper](https://github.com/shnewto/ashpaper)
* [brain](https://github.com/brain-lang/brain)
* [cicada](https://github.com/mitnk/cicada)
* [comrak](https://github.com/kivikakk/comrak)
* [elastic-rs](https://github.com/cch123/elastic-rs)
* [graphql-parser](https://github.com/Keats/graphql-parser)
* [handlebars-rust](https://github.com/sunng87/handlebars-rust)
* [hexdino](https://github.com/Luz/hexdino)
* [Huia](https://gitlab.com/jimsy/huia/)
* [insta](https://github.com/mitsuhiko/insta)
* [jql](https://github.com/yamafaktory/jql)
* [json5-rs](https://github.com/callum-oakley/json5-rs)
* [mt940](https://github.com/svenstaro/mt940-rs)
* [Myoxine](https://github.com/d3bate/myoxine)
* [py_literal](https://github.com/jturner314/py_literal)
* [rouler](https://github.com/jarcane/rouler)
* [RuSh](https://github.com/lwandrebeck/RuSh)
* [rs_pbrt](https://github.com/wahn/rs_pbrt)
* [stache](https://github.com/dgraham/stache)
* [tera](https://github.com/Keats/tera)
* [ui_gen](https://github.com/emoon/ui_gen)
* [ukhasnet-parser](https://github.com/adamgreig/ukhasnet-parser)
* [ZoKrates](https://github.com/ZoKrates/ZoKrates)
* [Vector](https://github.com/timberio/vector)
* [AutoCorrect](https://github.com/huacnlee/autocorrect)
* [yaml-peg](https://github.com/aofdev/yaml-peg)
* [qubit](https://github.com/abhimanyu003/qubit)
* [caith](https://github.com/Geobert/caith) (a dice roller crate)
* [Melody](https://github.com/yoav-lavi/melody)
* [json5-nodes](https://github.com/jlyonsmith/json5-nodes)
* [prisma](https://github.com/prisma/prisma)
* [ws2markdown](https://code.rosaelefanten.org/ws2markdown) (a WordStar to Markdown converter)
## Minimum Supported Rust Version (MSRV)
This library should always compile with default features on **Rust 1.83.0**.
## no_std support
The `pest` and `pest_derive` crates can be built without the Rust standard
library and target embedded environments. To do so, you need to disable
their default features. In your `Cargo.toml`, you can specify it as follows:
```toml
[dependencies]
# ...
pest = { version = "2", default-features = false }
pest_derive = { version = "2", default-features = false }
```
If you want to build these crates in the pest repository's workspace, you can
pass the `--no-default-features` flag to `cargo` and specify these crates using
the `--package` (`-p`) flag. For example:
```bash
$ cargo build --target thumbv7em-none-eabihf --no-default-features -p pest
$ cargo bootstrap
$ cargo build --target thumbv7em-none-eabihf --no-default-features -p pest_derive
```
## Special thanks
A special round of applause goes to prof. Marius Minea for his guidance and all
pest contributors, some of which being none other than my friends.

136
vendor/pest_generator/src/docs.rs vendored Normal file
View File

@@ -0,0 +1,136 @@
//! Type and helper to collect the gramamr and rule documentation.
use pest::iterators::Pairs;
use pest_meta::parser::Rule;
use std::collections::HashMap;
/// Abstraction for the grammar and rule doc.
#[derive(Debug)]
pub struct DocComment {
/// The grammar documentation is defined at the beginning of a file with //!.
pub grammar_doc: String,
/// HashMap for store all doc_comments for rules.
/// key is rule name, value is doc_comment.
pub line_docs: HashMap<String, String>,
}
/// Consume pairs to matches `Rule::grammar_doc`, `Rule::line_doc` into `DocComment`
///
/// e.g.
///
/// a pest file:
///
/// ```ignore
/// //! This is a grammar doc
/// /// line doc 1
/// /// line doc 2
/// foo = {}
///
/// /// line doc 3
/// bar = {}
/// ```
///
/// Then will get:
///
/// ```ignore
/// grammar_doc = "This is a grammar doc"
/// line_docs = { "foo": "line doc 1\nline doc 2", "bar": "line doc 3" }
/// ```
pub fn consume(pairs: Pairs<'_, Rule>) -> DocComment {
let mut grammar_doc = String::new();
let mut line_docs: HashMap<String, String> = HashMap::new();
let mut line_doc = String::new();
for pair in pairs {
match pair.as_rule() {
Rule::grammar_doc => {
// grammar_doc > inner_doc
let inner_doc = pair.into_inner().next().unwrap();
grammar_doc.push_str(inner_doc.as_str());
grammar_doc.push('\n');
}
Rule::grammar_rule => {
if let Some(inner) = pair.into_inner().next() {
// grammar_rule > line_doc | identifier
match inner.as_rule() {
Rule::line_doc => {
if let Some(inner_doc) = inner.into_inner().next() {
line_doc.push_str(inner_doc.as_str());
line_doc.push('\n');
}
}
Rule::identifier => {
if !line_doc.is_empty() {
let rule_name = inner.as_str().to_owned();
// Remove last \n
line_doc.pop();
line_docs.insert(rule_name, line_doc.clone());
line_doc.clear();
}
}
_ => (),
}
}
}
_ => (),
}
}
if !grammar_doc.is_empty() {
// Remove last \n
grammar_doc.pop();
}
DocComment {
grammar_doc,
line_docs,
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use pest_meta::parser;
use pest_meta::parser::Rule;
#[test]
fn test_doc_comment() {
let pairs = match parser::parse(Rule::grammar_rules, include_str!("../tests/test.pest")) {
Ok(pairs) => pairs,
Err(_) => panic!("error parsing tests/test.pest"),
};
let doc_comment = super::consume(pairs);
let mut expected = HashMap::new();
expected.insert("foo".to_owned(), "Matches foo str, e.g.: `foo`".to_owned());
expected.insert(
"bar".to_owned(),
"Matches bar str\n\n Indent 2, e.g: `bar` or `foobar`".to_owned(),
);
expected.insert(
"dar".to_owned(),
"Matches dar\n\nMatch dar description\n".to_owned(),
);
assert_eq!(expected, doc_comment.line_docs);
assert_eq!(
"A parser for JSON file.\nAnd this is a example for JSON parser.\n\n indent-4-space\n",
doc_comment.grammar_doc
);
}
#[test]
fn test_empty_grammar_doc() {
assert!(parser::parse(Rule::grammar_rules, "//!").is_ok());
assert!(parser::parse(Rule::grammar_rules, "///").is_ok());
assert!(parser::parse(Rule::grammar_rules, "//").is_ok());
assert!(parser::parse(Rule::grammar_rules, "/// Line Doc").is_ok());
assert!(parser::parse(Rule::grammar_rules, "//! Grammar Doc").is_ok());
assert!(parser::parse(Rule::grammar_rules, "// Comment").is_ok());
}
}

1324
vendor/pest_generator/src/generator.rs vendored Normal file

File diff suppressed because it is too large Load Diff

171
vendor/pest_generator/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,171 @@
// pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
#![doc(
html_root_url = "https://docs.rs/pest_derive",
html_logo_url = "https://raw.githubusercontent.com/pest-parser/pest/master/pest-logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/pest-parser/pest/master/pest-logo.svg"
)]
#![warn(missing_docs, rust_2018_idioms, unused_qualifications)]
#![recursion_limit = "256"]
//! # pest generator
//!
//! This crate generates code from ASTs (which is used in the `pest_derive` crate).
#[macro_use]
extern crate quote;
use std::env;
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use generator::generate;
use proc_macro2::TokenStream;
use syn::DeriveInput;
#[macro_use]
mod macros;
#[cfg(feature = "export-internal")]
pub mod docs;
#[cfg(not(feature = "export-internal"))]
mod docs;
#[cfg(feature = "export-internal")]
pub mod generator;
#[cfg(not(feature = "export-internal"))]
mod generator;
#[cfg(feature = "export-internal")]
pub mod parse_derive;
#[cfg(not(feature = "export-internal"))]
mod parse_derive;
use crate::parse_derive::{parse_derive, GrammarSource};
use pest_meta::parser::{self, rename_meta_rule, Rule};
use pest_meta::{optimizer, unwrap_or_report, validator};
/// Processes the derive/proc macro input and generates the corresponding parser based
/// on the parsed grammar. If `include_grammar` is set to true, it'll generate an explicit
/// "include_str" statement (done in pest_derive, but turned off in the local bootstrap).
pub fn derive_parser(input: TokenStream, include_grammar: bool) -> TokenStream {
let ast: DeriveInput = syn::parse2(input).unwrap();
let (parsed_derive, contents) = parse_derive(ast);
// Grammar presented in a view of a string.
let mut data = String::new();
let mut paths = vec![];
for content in contents {
let (_data, _path) = match content {
GrammarSource::File(ref path) => {
let root = env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into());
// Check whether we can find a file at the path relative to the CARGO_MANIFEST_DIR
// first.
//
// If we cannot find the expected file over there, fallback to the
// `CARGO_MANIFEST_DIR/src`, which is the old default and kept for convenience
// reasons.
// TODO: This could be refactored once `std::path::absolute()` get's stabilized.
// https://doc.rust-lang.org/std/path/fn.absolute.html
let path = if Path::new(&root).join(path).exists() {
Path::new(&root).join(path)
} else {
Path::new(&root).join("src/").join(path)
};
let file_name = match path.file_name() {
Some(file_name) => file_name,
None => panic!("grammar attribute should point to a file"),
};
let data = match read_file(&path) {
Ok(data) => data,
Err(error) => panic!("error opening {:?}: {}", file_name, error),
};
(data, Some(path.clone()))
}
GrammarSource::Inline(content) => (content, None),
};
data.push_str(&_data);
if let Some(path) = _path {
paths.push(path);
}
}
// `Rule::grammar_rules` is taken from meta/srd/parser.rs.
let pairs = match parser::parse(Rule::grammar_rules, &data) {
Ok(pairs) => pairs,
Err(error) => panic!("error parsing \n{}", error.renamed_rules(rename_meta_rule)),
};
let defaults = unwrap_or_report(validator::validate_pairs(pairs.clone()));
let doc_comment = docs::consume(pairs.clone());
let ast = unwrap_or_report(parser::consume_rules(pairs));
let optimized = optimizer::optimize(ast);
generate(
parsed_derive,
paths,
optimized,
defaults,
&doc_comment,
include_grammar,
)
}
fn read_file<P: AsRef<Path>>(path: P) -> io::Result<String> {
let mut file = File::open(path.as_ref())?;
let mut string = String::new();
file.read_to_string(&mut string)?;
Ok(string)
}
#[cfg(test)]
mod tests {
#[doc = "Matches dar\n\nMatch dar description\n"]
#[test]
fn test_generate_doc() {
let input = quote! {
#[derive(Parser)]
#[non_exhaustive]
#[grammar = "../tests/test.pest"]
pub struct TestParser;
};
let token = super::derive_parser(input, true);
let expected = quote! {
#[doc = "A parser for JSON file.\nAnd this is a example for JSON parser.\n\n indent-4-space\n"]
#[allow(dead_code, non_camel_case_types, clippy::upper_case_acronyms)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum Rule {
#[doc = "Matches foo str, e.g.: `foo`"]
r#foo,
#[doc = "Matches bar str\n\n Indent 2, e.g: `bar` or `foobar`"]
r#bar,
r#bar1,
#[doc = "Matches dar\n\nMatch dar description\n"]
r#dar
}
};
assert!(
token.to_string().contains(expected.to_string().as_str()),
"{}\n\nExpected to contains:\n{}",
token,
expected
);
}
}

40
vendor/pest_generator/src/macros.rs vendored Normal file
View File

@@ -0,0 +1,40 @@
// pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
macro_rules! insert_builtin {
($builtin: expr, $name: ident, $pattern: expr) => {
$builtin.push((stringify!($name), generate_rule!($name, $pattern)));
};
}
#[cfg(feature = "std")]
macro_rules! generate_rule {
($name: ident, $pattern: expr) => {
quote! {
#[inline]
#[allow(dead_code, non_snake_case, unused_variables)]
pub fn $name(state: ::std::boxed::Box<::pest::ParserState<'_, Rule>>) -> ::pest::ParseResult<::std::boxed::Box<::pest::ParserState<'_, Rule>>> {
$pattern
}
}
}
}
#[cfg(not(feature = "std"))]
macro_rules! generate_rule {
($name: ident, $pattern: expr) => {
quote! {
#[inline]
#[allow(dead_code, non_snake_case, unused_variables)]
pub fn $name(state: ::alloc::boxed::Box<::pest::ParserState<'_, Rule>>) -> ::pest::ParseResult<::alloc::boxed::Box<::pest::ParserState<'_, Rule>>> {
$pattern
}
}
}
}

View File

@@ -0,0 +1,172 @@
// pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
//! Types and helpers to parse the input of the derive macro.
use syn::{Attribute, DeriveInput, Expr, ExprLit, Generics, Ident, Lit, Meta};
#[derive(Debug, PartialEq)]
pub(crate) enum GrammarSource {
File(String),
Inline(String),
}
/// Parsed information of the derive and the attributes.
pub struct ParsedDerive {
/// The identifier of the deriving struct, union, or enum.
pub name: Ident,
/// The generics of the deriving struct, union, or enum.
pub generics: Generics,
/// Indicates whether the 'non_exhaustive' attribute is added to the 'Rule' enum.
pub non_exhaustive: bool,
}
pub(crate) fn parse_derive(ast: DeriveInput) -> (ParsedDerive, Vec<GrammarSource>) {
let name = ast.ident;
let generics = ast.generics;
let grammar: Vec<&Attribute> = ast
.attrs
.iter()
.filter(|attr| {
let path = attr.meta.path();
path.is_ident("grammar") || path.is_ident("grammar_inline")
})
.collect();
if grammar.is_empty() {
panic!("a grammar file needs to be provided with the #[grammar = \"PATH\"] or #[grammar_inline = \"GRAMMAR CONTENTS\"] attribute");
}
let mut grammar_sources = Vec::with_capacity(grammar.len());
for attr in grammar {
grammar_sources.push(get_attribute(attr))
}
let non_exhaustive = ast
.attrs
.iter()
.any(|attr| attr.meta.path().is_ident("non_exhaustive"));
(
ParsedDerive {
name,
generics,
non_exhaustive,
},
grammar_sources,
)
}
fn get_attribute(attr: &Attribute) -> GrammarSource {
match &attr.meta {
Meta::NameValue(name_value) => match &name_value.value {
Expr::Lit(ExprLit {
lit: Lit::Str(string),
..
}) => {
if name_value.path.is_ident("grammar") {
GrammarSource::File(string.value())
} else {
GrammarSource::Inline(string.value())
}
}
_ => panic!("grammar attribute must be a string"),
},
_ => panic!("grammar attribute must be of the form `grammar = \"...\"`"),
}
}
#[cfg(test)]
mod tests {
use super::parse_derive;
use super::GrammarSource;
#[test]
fn derive_inline_file() {
let definition = "
#[other_attr]
#[grammar_inline = \"GRAMMAR\"]
pub struct MyParser<'a, T>;
";
let ast = syn::parse_str(definition).unwrap();
let (_, filenames) = parse_derive(ast);
assert_eq!(filenames, [GrammarSource::Inline("GRAMMAR".to_string())]);
}
#[test]
fn derive_ok() {
let definition = "
#[other_attr]
#[grammar = \"myfile.pest\"]
pub struct MyParser<'a, T>;
";
let ast = syn::parse_str(definition).unwrap();
let (parsed_derive, filenames) = parse_derive(ast);
assert_eq!(filenames, [GrammarSource::File("myfile.pest".to_string())]);
assert!(!parsed_derive.non_exhaustive);
}
#[test]
fn derive_multiple_grammars() {
let definition = "
#[other_attr]
#[grammar = \"myfile1.pest\"]
#[grammar = \"myfile2.pest\"]
pub struct MyParser<'a, T>;
";
let ast = syn::parse_str(definition).unwrap();
let (_, filenames) = parse_derive(ast);
assert_eq!(
filenames,
[
GrammarSource::File("myfile1.pest".to_string()),
GrammarSource::File("myfile2.pest".to_string())
]
);
}
#[test]
fn derive_nonexhaustive() {
let definition = "
#[non_exhaustive]
#[grammar = \"myfile.pest\"]
pub struct MyParser<'a, T>;
";
let ast = syn::parse_str(definition).unwrap();
let (parsed_derive, filenames) = parse_derive(ast);
assert_eq!(filenames, [GrammarSource::File("myfile.pest".to_string())]);
assert!(parsed_derive.non_exhaustive);
}
#[test]
#[should_panic(expected = "grammar attribute must be a string")]
fn derive_wrong_arg() {
let definition = "
#[other_attr]
#[grammar = 1]
pub struct MyParser<'a, T>;
";
let ast = syn::parse_str(definition).unwrap();
parse_derive(ast);
}
#[test]
#[should_panic(
expected = "a grammar file needs to be provided with the #[grammar = \"PATH\"] or #[grammar_inline = \"GRAMMAR CONTENTS\"] attribute"
)]
fn derive_no_grammar() {
let definition = "
#[other_attr]
pub struct MyParser<'a, T>;
";
let ast = syn::parse_str(definition).unwrap();
parse_derive(ast);
}
}

Binary file not shown.

View File

@@ -0,0 +1 @@
{"name":"pest_generator","vers":"2.8.6","deps":[{"name":"pest","req":"^2.8.6","features":[],"optional":false,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"pest_meta","req":"^2.8.6","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"proc-macro2","req":"^1.0","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"quote","req":"^1.0","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"syn","req":"^2.0","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false}],"features":{"default":["std"],"export-internal":[],"grammar-extras":["pest_meta/grammar-extras"],"not-bootstrap-in-src":["pest_meta/not-bootstrap-in-src"],"std":["pest/std"]},"features2":null,"cksum":"927ee0a6d2dbf21e51c6d74e186f36db9651e42167681a1a45cd55c793c41446","yanked":null,"links":null,"rust_version":null,"v":2}

1
vendor/pest_generator/tests/base.pest vendored Normal file
View File

@@ -0,0 +1 @@
base = { "base" }

23
vendor/pest_generator/tests/test.pest vendored Normal file
View File

@@ -0,0 +1,23 @@
//! A parser for JSON file.
//! And this is a example for JSON parser.
//!
//! indent-4-space
//!
/// Matches foo str, e.g.: `foo`
foo = { "foo" }
/// Matches bar str
///
/// Indent 2, e.g: `bar` or `foobar`
bar = { "bar" | "foobar" }
bar1 = { "bar1" }
/// Matches dar
///
/// Match dar description
///
dar = { "da" }