Skip to content

Commit

Permalink
fix: Search for grammar file from CARGO_MANIFEST_DIR (#702)
Browse files Browse the repository at this point in the history
closes  #325.

The new logic looks for the [grammar = "$path"] path in CARGO_MANIFEST_DIR/ before using the fallback of CARGO_MANIFEST_DIR/src.

This allows projects that don't have a src folder to use a grammar file, while staying backward compatible.
  • Loading branch information
Nukesor committed Aug 23, 2022
1 parent ebee1fc commit 4fde90e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
2 changes: 1 addition & 1 deletion derive/tests/grammar.rs
Expand Up @@ -16,7 +16,7 @@ extern crate pest;
extern crate pest_derive;

#[derive(Parser)]
#[grammar = "../tests/grammar.pest"]
#[grammar = "tests/grammar.pest"]
struct GrammarParser;

#[test]
Expand Down
16 changes: 15 additions & 1 deletion generator/src/lib.rs
Expand Up @@ -41,7 +41,21 @@ pub fn derive_parser(input: TokenStream, include_grammar: bool) -> TokenStream {
let (data, path) = match content {
GrammarSource::File(ref path) => {
let root = env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into());
let path = Path::new(&root).join("src/").join(&path);

// 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"),
Expand Down

0 comments on commit 4fde90e

Please sign in to comment.