Skip to content

Commit

Permalink
codegen: Favor assert/panic over error
Browse files Browse the repository at this point in the history
  • Loading branch information
taiki-e committed Sep 8, 2024
1 parent 6981c97 commit 3a98f0f
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 32 deletions.
1 change: 0 additions & 1 deletion tools/codegen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ name = "futures-async-stream-internal-codegen"
edition = "2021"

[dependencies]
anyhow = "1"
fs-err = "2"
globset = { version = "0.4", default-features = false }
prettyplease = "0.2"
Expand Down
41 changes: 22 additions & 19 deletions tools/codegen/src/file.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT

use std::{
io,
path::{Path, PathBuf},
process::Command,
str,
sync::LazyLock,
};

use anyhow::{bail, format_err, Context as _, Result};
use fs_err as fs;
use proc_macro2::TokenStream;

Expand Down Expand Up @@ -53,17 +53,18 @@ pub(crate) fn write(
function_name: &str,
path: impl AsRef<Path>,
contents: TokenStream,
) -> Result<()> {
write_raw(function_name, path.as_ref(), format_tokens(contents)?)
) -> io::Result<()> {
write_raw(function_name, path.as_ref(), format_tokens(contents))
}

fn format_tokens(contents: TokenStream) -> Result<Vec<u8>> {
#[track_caller]
fn format_tokens(contents: TokenStream) -> Vec<u8> {
let mut out = prettyplease::unparse(
&syn::parse2(contents.clone()).map_err(|e| format_err!("{e} in:\n---\n{contents}\n---"))?,
&syn::parse2(contents.clone()).unwrap_or_else(|e| panic!("{e} in:\n---\n{contents}\n---")),
)
.into_bytes();
format_macros(&mut out);
Ok(out)
out
}

// Roughly format the code inside macro calls.
Expand Down Expand Up @@ -129,7 +130,7 @@ pub(crate) fn write_raw(
function_name: &str,
path: &Path,
contents: impl AsRef<[u8]>,
) -> Result<()> {
) -> io::Result<()> {
static LINGUIST_GENERATED: LazyLock<Vec<globset::GlobMatcher>> = LazyLock::new(|| {
let gitattributes = fs::read_to_string(workspace_root().join(".gitattributes")).unwrap();
let mut linguist_generated = vec![];
Expand Down Expand Up @@ -157,19 +158,21 @@ pub(crate) fn write_raw(
Ok(())
}

pub(crate) fn git_ls_files(dir: &Path, filters: &[&str]) -> Result<Vec<(String, PathBuf)>> {
#[track_caller]
pub(crate) fn git_ls_files(dir: &Path, filters: &[&str]) -> Vec<(String, PathBuf)> {
let mut cmd = Command::new("git");
cmd.arg("ls-files").args(filters).current_dir(dir);
let output = cmd.output().with_context(|| format!("could not execute process `{cmd:?}`"))?;
if !output.status.success() {
bail!(
"process didn't exit successfully: `{cmd:?}`:\n\nSTDOUT:\n{0}\n{1}\n{0}\n\nSTDERR:\n{0}\n{2}\n{0}\n",
"-".repeat(60),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
}
Ok(str::from_utf8(&output.stdout)?
let output =
cmd.output().unwrap_or_else(|e| panic!("could not execute process `{cmd:?}`: {e}"));
assert!(
output.status.success(),
"process didn't exit successfully: `{cmd:?}`:\n\nSTDOUT:\n{0}\n{1}\n{0}\n\nSTDERR:\n{0}\n{2}\n{0}\n",
"-".repeat(60),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
str::from_utf8(&output.stdout)
.unwrap()
.lines()
.map(str::trim)
.filter_map(|f| {
Expand All @@ -182,5 +185,5 @@ pub(crate) fn git_ls_files(dir: &Path, filters: &[&str]) -> Result<Vec<(String,
}
Some((f.to_owned(), p))
})
.collect())
.collect()
}
20 changes: 8 additions & 12 deletions tools/codegen/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,17 @@ use std::{
path::Path,
};

use anyhow::Result;
use fs_err as fs;
use quote::{format_ident, quote, ToTokens};
use syn::visit_mut::{self, VisitMut};

use crate::file::*;

fn main() -> Result<()> {
gen_assert_impl()?;
Ok(())
fn main() {
gen_assert_impl();
}

fn gen_assert_impl() -> Result<()> {
fn gen_assert_impl() {
const NOT_SEND: &[&str] = &[];
const NOT_SYNC: &[&str] = &[];
const NOT_UNPIN: &[&str] = &[];
Expand All @@ -31,9 +29,9 @@ fn gen_assert_impl() -> Result<()> {

let workspace_root = &workspace_root();
let out_dir = &workspace_root.join("src/gen");
fs::create_dir_all(out_dir)?;
fs::create_dir_all(out_dir).unwrap();

let files: BTreeSet<String> = git_ls_files(&workspace_root.join("src"), &["*.rs"])?
let files: BTreeSet<String> = git_ls_files(&workspace_root.join("src"), &["*.rs"])
.into_iter()
.filter_map(|(file_name, path)| {
// Assertions are only needed for the library's public APIs.
Expand All @@ -48,8 +46,8 @@ fn gen_assert_impl() -> Result<()> {
let mut visited_types = HashSet::new();
let mut use_generics_helpers = false;
for f in &files {
let s = fs::read_to_string(f)?;
let mut ast = syn::parse_file(&s)?;
let s = fs::read_to_string(f).unwrap();
let mut ast = syn::parse_file(&s).unwrap();

let module = if f.ends_with("lib.rs") {
vec![]
Expand Down Expand Up @@ -293,9 +291,7 @@ fn gen_assert_impl() -> Result<()> {
#tokens
};
});
write(function_name!(), out_dir.join("assert_impl.rs"), out)?;

Ok(())
write(function_name!(), out_dir.join("assert_impl.rs"), out).unwrap();
}

#[must_use]
Expand Down

0 comments on commit 3a98f0f

Please sign in to comment.