Skip to content

Commit

Permalink
Add name option.
Browse files Browse the repository at this point in the history
  • Loading branch information
timothee-haudebourg committed Aug 23, 2023
1 parent e8881f9 commit dc5b323
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 11 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "static-regular-grammar"
version = "1.0.0"
version = "1.1.0"
edition = "2021"
authors = ["Timothée Haudebourg <author@haudebourg.net>"]
categories = ["parsing"]
Expand Down
5 changes: 4 additions & 1 deletion examples/test.rs
Expand Up @@ -8,7 +8,10 @@ use static_regular_grammar::RegularGrammar;
/// test = "%" / "$"
/// ```
#[derive(RegularGrammar, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[grammar(sized(TestBuf, derive(Debug, Display, PartialEq, Eq, PartialOrd, Ord, Hash)))]
#[grammar(
name = "Test",
sized(TestBuf, derive(Debug, Display, PartialEq, Eq, PartialOrd, Ord, Hash))
)]
pub struct Test(str);

fn main() {
Expand Down
8 changes: 8 additions & 0 deletions src/attribute.rs
Expand Up @@ -27,6 +27,7 @@ pub enum Error {
pub struct Attribute {
pub file: Option<PathBuf>,
pub entry_point: Option<String>,
pub name: Option<String>,
pub sized: Option<SizedTypeAttributes>,
pub cache_path: Option<PathBuf>,
pub no_deref: bool,
Expand All @@ -40,6 +41,7 @@ impl Attribute {
pub fn append(&mut self, other: Self) {
self.file = other.file.or(self.file.take());
self.entry_point = other.entry_point.or(self.entry_point.take());
self.name = other.name.or(self.name.take());

if let Some(a) = other.sized {
self.sized.get_or_insert_with(Default::default).append(a);
Expand All @@ -57,6 +59,7 @@ impl Attribute {
enum AttributeItem {
File,
EntryPoint,
Name,
SizedType,
CachePath,
NoDeref,
Expand All @@ -72,6 +75,7 @@ impl AttributeItem {
match token {
TokenTree::Ident(id) if id == "file" => Ok(Self::File),
TokenTree::Ident(id) if id == "entry_point" => Ok(Self::EntryPoint),
TokenTree::Ident(id) if id == "name" => Ok(Self::Name),
TokenTree::Ident(id) if id == "sized" => Ok(Self::SizedType),
TokenTree::Ident(id) if id == "cache" => Ok(Self::CachePath),
TokenTree::Ident(id) if id == "no_deref" => Ok(Self::NoDeref),
Expand Down Expand Up @@ -164,6 +168,10 @@ impl Attribute {
expect_eq(&mut tokens, span)?;
result.entry_point = Some(expect_str_literal(&mut tokens, span)?)
}
AttributeItem::Name => {
expect_eq(&mut tokens, span)?;
result.name = Some(expect_str_literal(&mut tokens, span)?)
}
AttributeItem::CachePath => {
expect_eq(&mut tokens, span)?;
let path: PathBuf = expect_str_literal(&mut tokens, span)?.into();
Expand Down
31 changes: 22 additions & 9 deletions src/lib.rs
Expand Up @@ -382,6 +382,11 @@ fn generate_typed<T: Token>(
let vis = data.vis;
let ident = data.ident;
let ascii = data.options.ascii && T::is_ascii(&automaton);
let name = data

Check failure on line 385 in src/lib.rs

View workflow job for this annotation

GitHub Actions / Warnings

unnecessary closure used to substitute value for `Option::None`
.options
.name
.or_else(|| data.options.entry_point)
.unwrap_or_else(|| ident.to_string());

if data.options.ascii && !ascii {
return Err((Error::NotAscii, Span::call_site()));
Expand All @@ -396,18 +401,19 @@ fn generate_typed<T: Token>(
let as_inner = T::rust_as_inner_method();

let error = format_ident!("Invalid{}", ident);
let error_msg = format!("Invalid {name} `{{0}}`");

let new_doc = format!("Creates a new [`{ident}`] by parsing the `input` value");
let new_doc = format!("Creates a new {name} by parsing the `input` value");
let new_unchecked_doc = formatdoc!(
r#"
Creates a new [`{ident}`] from the `input` value without validation.
Creates a new {name} from the `input` value without validation.
# Safety
The input data *must* be a valid [`{ident}`]."#
The input data *must* be a valid {name}."#
);

let validate_doc = format!("Checks that the input iterator produces a valid [`{ident}`]");
let validate_doc = format!("Checks that the input iterator produces a valid {name}");
let validate_body = if data.options.disable {
quote! {
panic!("automaton not generated")
Expand All @@ -420,6 +426,14 @@ fn generate_typed<T: Token>(
#[derive(Debug)]
#vis struct #error<T>(pub T);

impl<T: ::core::fmt::Display> ::core::fmt::Display for #error<T> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, #error_msg, self.0)
}
}

impl<T: ::core::fmt::Debug + ::core::fmt::Display> ::std::error::Error for #error<T> {}

impl #ident {
#[doc = #new_doc]
pub fn new<T: ?Sized + AsRef<#string_type>>(input: &T) -> Result<&Self, #error<&T>> {
Expand Down Expand Up @@ -679,16 +693,15 @@ fn generate_typed<T: Token>(
let buffer_ident = buffer.ident;
let owned_string_type = T::rust_owned_string_type();

let owned_doc = format!("Owned [`{ident}`].");
let owned_new_doc =
format!("Creates a new [`{buffer_ident}`] by parsing the `input` value");
let owned_doc = format!("Owned {name}.");
let owned_new_doc = format!("Creates a new owned {name} by parsing the `input` value");
let owned_new_unchecked_doc = formatdoc!(
r#"
Creates a new [`{buffer_ident}`] from the `input` value without validation.
Creates a new owned {name} from the `input` value without validation.
# Safety
The input data *must* be a valid [`{ident}`]."#
The input data *must* be a valid {name}."#
);

tokens.extend(quote! {
Expand Down
2 changes: 2 additions & 0 deletions src/options.rs
Expand Up @@ -7,6 +7,7 @@ use crate::{attribute::SizedTypeAttributes, Attribute, Error};
pub struct Options {
pub file: Option<PathBuf>,
pub entry_point: Option<String>,
pub name: Option<String>,
pub sized: Option<SizedTypeOptions>,
pub cache_path: PathBuf,
pub no_deref: bool,
Expand All @@ -21,6 +22,7 @@ impl Options {
Ok(Self {
file: attr.file,
entry_point: attr.entry_point,
name: attr.name,
sized: match attr.sized {
Some(attr) => Some(SizedTypeOptions::from_attribute(attr, ident.span())?),
None => None,
Expand Down

0 comments on commit dc5b323

Please sign in to comment.