Write tree_sitter/parser.h file in generate command

This commit is contained in:
Max Brunsfeld 2019-01-28 14:23:41 -08:00
parent 8e198016d8
commit f6d014f3f4

View file

@ -40,7 +40,9 @@ pub fn generate_parser_in_directory(
let (language_name, c_code) =
generate_parser_for_grammar_with_opts(&grammar_json, minimize, state_ids_to_log)?;
let repo_src_path = repo_path.join("src");
let repo_header_path = repo_src_path.join("tree_sitter");
fs::create_dir_all(&repo_src_path)?;
fs::create_dir_all(&repo_header_path)?;
fs::write(&repo_src_path.join("parser.c"), c_code)
.map_err(|e| format!("Failed to write parser.c: {}", e))?;
ensure_file(&repo_src_path.join("binding.cc"), || {
@ -52,6 +54,9 @@ pub fn generate_parser_in_directory(
ensure_file(&repo_path.join("index.js"), || {
npm_files::index_js(&language_name)
})?;
ensure_file(&repo_header_path.join("parser.h"), || {
include_str!("../../../lib/include/tree_sitter/parser.h")
})?;
}
properties::generate_property_sheets(repo_path)?;
Ok(())
@ -96,7 +101,10 @@ fn load_grammar_file(grammar_path: &PathBuf) -> Result<String> {
match grammar_path.extension().and_then(|e| e.to_str()) {
Some("js") => Ok(load_js_grammar_file(grammar_path)?),
Some("json") => Ok(fs::read_to_string(grammar_path)?),
_ => Err(Error(format!("Unknown grammar file extension: {:?}", grammar_path))),
_ => Err(Error(format!(
"Unknown grammar file extension: {:?}",
grammar_path
))),
}
}
@ -129,10 +137,10 @@ fn load_js_grammar_file(grammar_path: &PathBuf) -> Result<String> {
Ok(String::from_utf8(output.stdout).expect("Got invalid UTF8 from node"))
}
fn ensure_file(path: &PathBuf, f: impl Fn() -> String) -> Result<()> {
fn ensure_file<T: AsRef<[u8]>>(path: &PathBuf, f: impl Fn() -> T) -> Result<()> {
if path.exists() {
Ok(())
} else {
fs::write(path, f()).map_err(|e| Error(format!("Failed to write file {:?}: {}", path, e)))
fs::write(path, f().as_ref()).map_err(|e| Error(format!("Failed to write file {:?}: {}", path, e)))
}
}