Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ jobs:
- name: Test error_set
run: cd error_set && cargo test --verbose --tests
- name: Test no_std
run: rustup target add x86_64-unknown-linux-gnu && cd test_no_std && cargo run
run: rustup target add x86_64-unknown-linux-gnu && cd examples/test_no_std && cargo run
- name: Test combine_parts feature flag
run: cd examples/error_set_part && cargo run
91 changes: 91 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
resolver = "3"
members = ["error_set", "error_set_impl"]
members = ["error_set", "error_set_impl", "examples/error_set_part"]

exclude = ["test_no_std"]
exclude = ["examples/test_no_std"]
2 changes: 2 additions & 0 deletions error_set/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ rust-version = "1.86"

[dependencies]
error_set_impl = { version = "=0.9.1", path = "../error_set_impl" }
ignore = { version = "0.4", optional = true }

[dev-dependencies]
trybuild = "=1.0.111"
Expand All @@ -22,6 +23,7 @@ jsonwebtoken = { version = "10", features = ["rust_crypto"] }

[features]
default = []
combine_parts = ["dep:ignore"]

[package.metadata.docs.rs]
all-features = false
Expand Down
131 changes: 131 additions & 0 deletions error_set/src/combine_parts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
use std::fs;
use std::path::{Path, PathBuf};

use ignore::WalkBuilder;

/// Combines all uses of the `error_set_part!` macro in `src/` (respecting `.gitignore`) into one
/// `error_set!` macro at the generated file `src/error_set.rs`
pub fn combine_error_set_parts() {
let mut parts = String::with_capacity(1024);
for file_path in find_rust_files("src") {
if let Ok(content) = fs::read_to_string(&file_path) {
extract_error_set_parts(&content, &mut parts, &file_path);
}
}
if parts.is_empty() {
return;
}
let output_path = "src/error_set.rs";
if let Err(e) = fs::write(
output_path,
format!(
"// This file is auto-generated\n\nerror_set::error_set! {{\n{parts}\n}}"
),
) {
panic!("Failed to write to {}: {}", output_path, e);
}
// if let Err(e) = std::process::Command::new("rustfmt")
// .arg(output_path)
// .status()
// {
// println!("cargo:warning=Failed to format {:?}: {}", output_path, e);
// }
}

#[inline]
fn find_rust_files<P: AsRef<Path>>(dir: P) -> impl Iterator<Item = PathBuf> {
WalkBuilder::new(dir)
.build()
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("rs"))
.map(|e| e.path().to_path_buf())
}

#[inline]
fn extract_error_set_parts(content: &str, error_set_body: &mut String, current_file: &Path) {
let needle = "error_set_part!";
let mut pos = 0;

while let Some(relative_idx) = content[pos..].find(needle) {
let statement_start = pos + relative_idx;
let mut brace_pos = statement_start + needle.len();

// Skip whitespace
let skip = content[brace_pos..].chars()
.take_while(|c| c.is_whitespace())
.map(|c| c.len_utf8())
.sum::<usize>();
brace_pos += skip;

if brace_pos < content.len() {
let end = extract_balanced_braces(content, brace_pos, error_set_body, current_file);
pos = end;
} else {
break;
}
}
}

#[inline]
fn extract_balanced_braces(content: &str, brace_start_pos: usize, error_set_body: &mut String, current_file: &Path) -> usize {
let mut chars = content[brace_start_pos..].chars();

let next = chars.next();
if let Some(next) = next {
if next != '{' {
panic!("Expected '{{' after error_set_part! macro in {}", current_file.display());
}
} else {
panic!("Unexpected end of input after error_set_part! macro in {}", current_file.display());
}

let mut depth = 1;
let mut end = brace_start_pos + 1;

for (i, ch) in chars.enumerate() {
match ch {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
end = brace_start_pos + i + 2; // +1 for opening brace, +1 for current closing brace
break;
}
}
_ => {}
}
}

if depth == 0 {
let line_number = content[..brace_start_pos].chars().filter(|&c| c == '\n').count() + 1;
error_set_body.push_str(&format!("\t// From `{}:{line_number}`\n", current_file.display()));
error_set_body.push_str(&content[brace_start_pos + 1..end - 1].trim_start_matches('\n'));
error_set_body.push_str("\n");
end
} else {
panic!("Unmatched braces in error_set_part! macro in {}", current_file.display());
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_extract_error_set_parts() {
let code = r#"
error_set_part! {
MyError1,
MyError2,
}

fn some_function() {}

error_set_part! { AnotherError }
"#;
let mut parts = String::new();
extract_error_set_parts(code, &mut parts, &PathBuf::from("test"));
assert!(parts.contains("MyError1"));
assert!(parts.contains("AnotherError"));
}
}
7 changes: 6 additions & 1 deletion error_set/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
#![cfg_attr(not(test), no_std)]
#![cfg_attr(not(any(test, feature = "combine_parts")), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc = include_str!("../README.md")]

#[cfg(feature = "combine_parts")]
mod combine_parts;
#[cfg(feature = "combine_parts")]
pub use combine_parts::combine_error_set_parts;

pub use error_set_impl::*;

pub trait CoerceResult<T, E1> {
Expand Down
24 changes: 21 additions & 3 deletions error_set_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@ mod validate;

use ast::AstErrorSet;
use expand::expand;
use quote::TokenStreamExt;
use resolve::resolve;
use validate::validate;

use crate::ast::AstErrorKind;

#[proc_macro]
pub fn error_set(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
// Dev Note: If the macro is not updating when macro changes, uncomment below, rust-analyzer may be stuck and you need to restart: https://github.com/rust-lang/rust-analyzer/issues/10027
// let token_stream: proc_macro2::TokenStream = syn::parse_str("const int: i32 = 1;").unwrap();
// return proc_macro::TokenStream::from(token_stream);
let error_set = syn::parse_macro_input!(tokens as AstErrorSet);
let mut error_enum_decls = Vec::new();
let mut error_struct_decls = Vec::new();
Expand All @@ -39,3 +37,23 @@ pub fn error_set(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
}
expand(error_enums, error_struct_decls).into()
}

#[proc_macro]
pub fn error_set_part(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
let error_set = syn::parse_macro_input!(tokens as AstErrorSet);
let mut token_stream = proc_macro2::TokenStream::new();
for item in error_set.set_items.into_iter() {
let name = match item {
AstErrorKind::Enum(error_enum_decl) => {
error_enum_decl.error_name
}
AstErrorKind::Struct(struct_decl) => {
struct_decl.r#struct.ident
}
};
token_stream.append_all(quote::quote! {
use crate::error_set::#name;
});
}
token_stream.into()
}
1 change: 1 addition & 0 deletions examples/error_set_part/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ignored.rs
10 changes: 10 additions & 0 deletions examples/error_set_part/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "error_set_part"
version = "0.1.0"
edition = "2024"

[dependencies]
error_set = { path = "../../error_set" }

[build-dependencies]
error_set = { path = "../../error_set", features = ["combine_parts"] }
3 changes: 3 additions & 0 deletions examples/error_set_part/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fn main() {
error_set::combine_error_set_parts();
}
Loading
Loading