Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add to support /// and //! syntax for add doc comment for rules. #765

Merged
merged 5 commits into from Jan 18, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
82 changes: 75 additions & 7 deletions generator/src/generator.rs
Expand Up @@ -7,6 +7,7 @@
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

use std::collections::HashMap;
use std::path::PathBuf;

use proc_macro2::TokenStream;
Expand All @@ -17,12 +18,42 @@ use pest::unicode::unicode_property_names;
use pest_meta::ast::*;
use pest_meta::optimizer::*;

pub fn generate(
#[derive(Debug)]
pub(crate) struct DocComment {
/// Multi-line grammar doc, (joined with `\n`)
///
/// e.g.
///
/// ```ignore
/// "grammar doc 1\ngrammar doc 2"
/// ```
grammar_doc: String,
/// HashMap rule name and doc comments (joined with `\n`)
///
/// e.g.
///
/// ```ignore
/// { "foo": "line doc 1\nline doc 2", "bar": "line doc 3" }
/// ```
line_docs: HashMap<String, String>,
}

impl DocComment {
pub fn new(grammar_doc: String, line_docs: HashMap<String, String>) -> Self {
tomtau marked this conversation as resolved.
Show resolved Hide resolved
Self {
grammar_doc,
line_docs,
}
}
}

pub(crate) fn generate(
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This because of themod generator is not public.

So I changed it to pub(crate).

name: Ident,
generics: &Generics,
path: Option<PathBuf>,
rules: Vec<OptimizedRule>,
defaults: Vec<&str>,
doc_comment: &DocComment,
include_grammar: bool,
) -> TokenStream {
let uses_eoi = defaults.iter().any(|name| *name == "EOI");
Expand All @@ -36,7 +67,7 @@ pub fn generate(
} else {
quote!()
};
let rule_enum = generate_enum(&rules, uses_eoi);
let rule_enum = generate_enum(&rules, doc_comment, uses_eoi);
let patterns = generate_patterns(&rules, uses_eoi);
let skip = generate_skip(&rules);

Expand Down Expand Up @@ -181,10 +212,25 @@ fn generate_include(name: &Ident, path: &str) -> TokenStream {
}
}

fn generate_enum(rules: &[OptimizedRule], uses_eoi: bool) -> TokenStream {
let rules = rules.iter().map(|rule| format_ident!("r#{}", rule.name));
fn generate_enum(rules: &[OptimizedRule], doc_comment: &DocComment, uses_eoi: bool) -> TokenStream {
let rules = rules.iter().map(|rule| {
let rule_name = format_ident!("r#{}", rule.name);

match doc_comment.line_docs.get(&rule.name) {
Some(doc) => quote! {
#[doc = #doc]
#rule_name
},
None => quote! {
#rule_name
},
}
});

let grammar_doc = &doc_comment.grammar_doc;
if uses_eoi {
quote! {
#[doc = #grammar_doc]
#[allow(dead_code, non_camel_case_types, clippy::upper_case_acronyms)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Rule {
Expand All @@ -194,6 +240,7 @@ fn generate_enum(rules: &[OptimizedRule], uses_eoi: bool) -> TokenStream {
}
} else {
quote! {
#[doc = #grammar_doc]
#[allow(dead_code, non_camel_case_types, clippy::upper_case_acronyms)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Rule {
Expand All @@ -208,6 +255,7 @@ fn generate_patterns(rules: &[OptimizedRule], uses_eoi: bool) -> TokenStream {
.iter()
.map(|rule| {
let rule = format_ident!("r#{}", rule.name);

quote! {
Rule::#rule => rules::#rule(state)
}
Expand Down Expand Up @@ -669,12 +717,22 @@ mod tests {
expr: OptimizedExpr::Ident("g".to_owned()),
}];

let mut line_docs = HashMap::new();
line_docs.insert("f".to_owned(), "This is rule comment".to_owned());

let doc_comment = &DocComment {
grammar_doc: "Rule doc\nhello".to_owned(),
line_docs,
};

assert_eq!(
generate_enum(&rules, false).to_string(),
generate_enum(&rules, doc_comment, false).to_string(),
quote! {
#[doc = "Rule doc\nhello"]
#[allow(dead_code, non_camel_case_types, clippy::upper_case_acronyms)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Rule {
#[doc = "This is rule comment"]
r#f
}
}
Expand Down Expand Up @@ -957,7 +1015,7 @@ mod tests {
}

#[test]
fn generate_complete() {
fn test_generate_complete() {
let name = Ident::new("MyParser", Span::call_site());
let generics = Generics::default();

Expand All @@ -974,22 +1032,32 @@ mod tests {
},
];

let mut line_docs = HashMap::new();
line_docs.insert("if".to_owned(), "If statement".to_owned());

let doc_comment = &DocComment {
line_docs,
grammar_doc: "This is Rule doc\nThis is second line".to_owned(),
};

let defaults = vec!["ANY"];
let result = result_type();
let box_ty = box_type();
let mut current_dir = std::env::current_dir().expect("Unable to get current directory");
current_dir.push("test.pest");
let test_path = current_dir.to_str().expect("path contains invalid unicode");
assert_eq!(
generate(name, &generics, Some(PathBuf::from("test.pest")), rules, defaults, true).to_string(),
generate(name, &generics, Some(PathBuf::from("test.pest")), rules, defaults, doc_comment, true).to_string(),
quote! {
#[allow(non_upper_case_globals)]
const _PEST_GRAMMAR_MyParser: &'static str = include_str!(#test_path);

#[doc = "This is Rule doc\nThis is second line"]
#[allow(dead_code, non_camel_case_types, clippy::upper_case_acronyms)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Rule {
r#a,
#[doc = "If statement"]
r#if
}

Expand Down
139 changes: 138 additions & 1 deletion generator/src/lib.rs
Expand Up @@ -21,11 +21,13 @@
#[macro_use]
extern crate quote;

use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;

use pest::iterators::Pairs;
use proc_macro2::TokenStream;
use syn::{Attribute, DeriveInput, Generics, Ident, Lit, Meta};

Expand All @@ -36,6 +38,8 @@ mod generator;
use pest_meta::parser::{self, rename_meta_rule, Rule};
use pest_meta::{optimizer, unwrap_or_report, validator};

use generator::DocComment;

/// 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).
Expand Down Expand Up @@ -90,11 +94,83 @@ pub fn derive_parser(input: TokenStream, include_grammar: bool) -> TokenStream {
Err(error) => panic!("error parsing \n{}", error.renamed_rules(rename_meta_rule)),
};

let grammar_doc = consume_grammar_doc(pairs.clone());
let line_docs = consume_line_docs(pairs.clone());

let defaults = unwrap_or_report(validator::validate_pairs(pairs.clone()));
let ast = unwrap_or_report(parser::consume_rules(pairs));
let optimized = optimizer::optimize(ast);

generator::generate(name, &generics, path, optimized, defaults, include_grammar)
let doc_comment = &DocComment::new(grammar_doc, line_docs);

generator::generate(
name,
&generics,
path,
optimized,
defaults,
doc_comment,
include_grammar,
)
}

/// Consume grammar doc into String, multi-line joined with `\n`
fn consume_grammar_doc(pairs: Pairs<'_, Rule>) -> String {
let mut docs = vec![];
for pair in pairs {
if pair.as_rule() == Rule::grammar_doc {
let inner_doc = pair.into_inner().next().unwrap();
docs.push(inner_doc.as_str());
}
}

docs.join("\n")
huacnlee marked this conversation as resolved.
Show resolved Hide resolved
}

/// Consume line docs into HashMap<rule_name, doc>
///
/// Example a `test.pest`:
///
/// ```ignore
/// /// Line doc 1
/// foo = {}
///
/// /// Line doc 2
/// /// Line doc 3
/// bar = {}
/// ```
///
/// Will returns `{ "foo": "This is line comment", "bar": "Line doc 2\n/// Line doc 3" }`
fn consume_line_docs(pairs: Pairs<'_, Rule>) -> HashMap<String, String> {
let mut docs: HashMap<String, String> = HashMap::new();
let mut comments = vec![];
huacnlee marked this conversation as resolved.
Show resolved Hide resolved

for pair in pairs {
let rule = pair.as_rule();

if rule == 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() {
comments.push(inner_doc.as_str())
}
}
Rule::identifier => {
if !comments.is_empty() {
let rule_name = inner.as_str().to_owned();
docs.insert(rule_name, comments.join("\n"));
comments = vec![];
}
}
_ => (),
}
}
}
}

docs
}

fn read_file<P: AsRef<Path>>(path: P) -> io::Result<String> {
Expand Down Expand Up @@ -155,9 +231,14 @@ fn get_attribute(attr: &Attribute) -> GrammarSource {

#[cfg(test)]
mod tests {
use std::collections::HashMap;

use super::consume_line_docs;
use super::parse_derive;
use super::GrammarSource;

use pest_meta::parser::{self, Rule};

#[test]
fn derive_inline_file() {
let definition = "
Expand Down Expand Up @@ -225,4 +306,60 @@ mod tests {
let ast = syn::parse_str(definition).unwrap();
parse_derive(ast);
}

#[test]
fn test_consume_line_docs() {
let pairs = match parser::parse(Rule::grammar_rules, include_str!("../tests/test.pest")) {
Ok(pairs) => pairs,
Err(_) => panic!("error parsing tests/test.pest"),
};

let line_docs = consume_line_docs(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 Indent 2, e.g: `bar` or `foobar`".to_owned(),
);
expected.insert(
"dar".to_owned(),
"Matches dar\nMatch dar description".to_owned(),
);
assert_eq!(expected, line_docs);
}

#[test]
fn test_generate_doc() {
let input = quote! {
#[derive(Parser)]
#[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"]
#[allow(dead_code, non_camel_case_types, clippy::upper_case_acronyms)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]

pub enum Rule {
#[doc = "Matches foo str, e.g.: `foo`"]
r#foo,
#[doc = "Matches bar str,\n Indent 2, e.g: `bar` or `foobar`"]
r#bar,
r#bar1,
#[doc = "Matches dar\nMatch dar description"]
r#dar
}
};

assert!(
token.to_string().contains(expected.to_string().as_str()),
"{}\n\nExpected to contains:\n{}",
token,
expected
);
}
}
20 changes: 20 additions & 0 deletions generator/tests/test.pest
@@ -0,0 +1,20 @@
//! 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" }
5 changes: 5 additions & 0 deletions grammars/src/grammars/json.pest
Expand Up @@ -7,8 +7,13 @@
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! A parser for JSON file.
//!
//! And this is a example for JSON parser.
json = { SOI ~ (object | array) ~ EOI }

/// Matches object, e.g.: `{ "foo": "bar" }`
/// Foobar
object = { "{" ~ pair ~ ("," ~ pair)* ~ "}" | "{" ~ "}" }
pair = { string ~ ":" ~ value }

Expand Down