Skip to content
v0.1.1latest release34 skills2 categories4 sub-categories79 tested scripts157 reference docsContact us

async_ctx.rs

Helper script for rust-tokio-async-service-builder · 137 lines

Programming / Rustv1.0.0Updated OCT 21 20267 references8 scripts
scripts/async_ctx.rs
//! Where is code async, and which fns are axum handlers? Shared by the tokio scripts;
//! pulled in with `mod async_ctx;` (needs `mod rsparse;`).
//!
//! Async context = `async fn` bodies, `async {}` / `async move {}` blocks and async closures,
//! minus the arguments of spawn_blocking, block_in_place, thread::spawn and rayon::spawn
//! (code there runs on a blocking thread, where blocking is the point).
#![allow(dead_code)]

use crate::rsparse::{close_of, word_positions, FnSig, Src};

pub struct AsyncCtx {
    spans: Vec<(usize, usize)>,
    excluded: Vec<(usize, usize)>,
}

/// `{ .. }` body span of a fn, if it has one.
pub fn body_span(src: &Src, f: &FnSig) -> Option<(usize, usize)> {
    let open = f.off + src.code[f.off..].find(['{', ';'])?;
    (src.code.as_bytes()[open] == b'{').then(|| (open, close_of(&src.code, open)))
}

pub fn is_async_fn(src: &Src, f: &FnSig) -> bool {
    let before = src.code[..f.off].trim_end();
    before.ends_with("async") || before.ends_with("async unsafe")
}

/// Argument spans of every call to one of `names` (e.g. `spawn_blocking(`).
pub fn call_arg_spans(code: &str, names: &[&str]) -> Vec<(usize, usize)> {
    let mut out = Vec::new();
    for name in names {
        for (i, _) in code.match_indices(name) {
            let open = i + name.len() - 1; // names end with '('
            out.push((open, close_of(code, open)));
        }
    }
    out
}

/// Spans of `name! { .. }` / `name!( .. )` macro bodies, e.g. `select!`.
pub fn macro_spans(code: &str, name: &str) -> Vec<(usize, usize)> {
    code.match_indices(name)
        .filter_map(|(i, _)| {
            let rest = &code[i + name.len()..];
            let open = i + name.len() + rest.find(['{', '('])?;
            (rest[..open - i - name.len()].trim().is_empty()).then(|| (open, close_of(code, open)))
        })
        .collect()
}

impl AsyncCtx {
    pub fn new(src: &Src, fns: &[FnSig]) -> AsyncCtx {
        let code = &src.code;
        let mut spans: Vec<(usize, usize)> = fns.iter().filter(|f| is_async_fn(src, f)).filter_map(|f| body_span(src, f)).collect();
        for i in word_positions(code, "async") {
            let mut rest = code[i + 5..].trim_start();
            if let Some(r) = rest.strip_prefix("move") {
                rest = r.trim_start();
            }
            let at = code.len() - rest.len();
            if rest.starts_with('{') {
                spans.push((at, close_of(code, at)));
            } else if rest.starts_with('|') {
                // async closure: |args| { body }  or  |args| expr
                if let Some(end_args) = rest[1..].find('|') {
                    let body = rest[end_args + 2..].trim_start();
                    let b = code.len() - body.len();
                    if body.starts_with('{') {
                        spans.push((b, close_of(code, b)));
                    }
                }
            }
        }
        let excluded = call_arg_spans(code, &["spawn_blocking(", "block_in_place(", "thread::spawn(", "rayon::spawn(", "thread::scope("]);
        AsyncCtx { spans, excluded }
    }

    /// Is `off` in async code (and not inside a blocking-thread closure)?
    pub fn contains(&self, off: usize) -> bool {
        self.spans.iter().any(|&(a, b)| a < off && off < b) && !self.excluded.iter().any(|&(a, b)| a < off && off < b)
    }

    /// Innermost async span containing `off`.
    pub fn innermost(&self, off: usize) -> Option<(usize, usize)> {
        self.spans.iter().filter(|&&(a, b)| a < off && off < b).min_by_key(|&&(a, b)| b - a).copied()
    }
}

/// Names of fns routed with get(..)/post(..)/... or taking axum extractors.
pub fn handlers(src: &Src, fns: &[FnSig]) -> Vec<String> {
    let code = &src.code;
    let mut out: Vec<String> = Vec::new();
    for verb in ["get(", "post(", "put(", "delete(", "patch(", "head(", "options(", "any("] {
        for (i, _) in code.match_indices(verb) {
            let before_ok = i == 0 || !code.as_bytes()[i - 1].is_ascii_alphanumeric() && code.as_bytes()[i - 1] != b'_';
            if !before_ok {
                continue;
            }
            let open = i + verb.len() - 1;
            let arg = code[open + 1..close_of(code, open) - 1].trim();
            let name = arg.rsplit("::").next().unwrap_or("");
            if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
                out.push(name.to_string());
            }
        }
    }
    for f in fns {
        let extractor = ["State(", "Json(", "Path(", "Query(", "Extension(", "Form("].iter().any(|e| f.params.contains(e));
        if extractor && is_async_fn(src, f) {
            out.push(f.name.clone());
        }
    }
    out.sort();
    out.dedup();
    out
}

/// Innermost fn whose body contains `off`.
pub fn fn_at<'a>(src: &Src, fns: &'a [FnSig], off: usize) -> Option<&'a FnSig> {
    fns.iter()
        .filter(|f| body_span(src, f).is_some_and(|(a, b)| a < off && off < b))
        .min_by_key(|f| f.body.len())
}

/// End of the scope (block) that contains `off`: the first unmatched `}` after it.
pub fn scope_end(code: &str, off: usize) -> usize {
    let mut depth = 0i32;
    for (j, c) in code[off..].char_indices() {
        match c {
            '{' => depth += 1,
            '}' if depth == 0 => return off + j,
            '}' => depth -= 1,
            _ => {}
        }
    }
    code.len()
}
More in Rust

rust-borrow-checker-error-explainer

Explain and fix Rust borrow-checker, ownership, move and lifetime compiler errors: E0382 use of moved value, E0499 cannot borrow as mutable more than once, E0502 also borrowed as immutable, E0505, E0506, E0503, E0507 cannot move out of index/Rc/reference, E0515 return reference to local, E0597 does not live long enough, E0716 temporary value dropped while borrowed, E0373 closure may outlive (spawn needs move), E0521 borrowed data escapes, E0384, E0596, E0594, E0381, E0713, 'lifetime may not live long enough', RefCell 'already borrowed: BorrowMutError' panics. Ranks fixes from restructuring (split borrows, entry API, split_at_mut, get_disjoint_mut, mem::take, Option::take, indices, thread::scope) down to clone and Rc<RefCell>/Arc<Mutex>; never unsafe. Covers NLL limits (get-or-insert), iterator invalidation, closure captures, self-referential structs. Ships std-only Rust triage tools.

rust-cargo-workspace-designer

Design, review and fix Cargo workspaces: when to split a crate (compile time, boundaries, publishing, proc-macros), crates/* vs apps/ + crates/ layouts, virtual manifest vs root package, members/exclude/default-members, resolver 2 vs 3 (MSRV-aware, edition 2024), [workspace.package] and [workspace.dependencies] inheritance, [workspace.lints], root-only profiles (lto, codegen-units), additive features with dep: and weak ?/ syntax, feature unification pitfalls, internal path + version deps, publish = false, Cargo.lock and MSRV policy, xtask, CI with --locked, nextest, rust-cache, sccache, cargo-hack/deny/machete/udeps/semver-checks, and cargo build --timings. Ships a workspace auditor and crate-graph tool.

rust-error-handling-thiserror-anyhow-designer

Design and review Rust error handling with thiserror 2 and anyhow 1: library vs application split, typed error enums with #[from], #[source], #[error(transparent)] and #[non_exhaustive], ErrorKind patterns, context via .context()/.with_context(), bail!/ensure!, source() chains, {:#} and {:?} reports, RUST_BACKTRACE/RUST_LIB_BACKTRACE, Box<dyn Error + Send + Sync>, main -> anyhow::Result or ExitCode, unwrap/expect/panic policy, Option to Result, collecting iterators of Results, axum IntoResponse mapping, retryable errors, tracing, async Send bounds, testing with matches! and downcast_ref, no_std core::error::Error, and snafu, eyre/color-eyre, miette, error-stack.

rust-lifetime-annotation-advisor

Decide when Rust lifetime annotations are needed and which ones: the three elision rules, structs holding references (struct Parser<'a>), owned vs borrowed (String, &str, Cow<'a, str>, Arc<str>), one vs several lifetimes, 'a: 'b bounds, T: 'static misconceptions, Box<dyn Trait + 'a> default object lifetimes, impl Trait + '_ and edition 2024 capture rules with use<..>, variance and PhantomData, HRTB for<'a> Fn(&'a T), GATs and lending iterators, async fn and tokio::spawn 'static, self-referential structs (ouroboros, self_cell, indices, arenas), Rc/Arc to escape lifetime soup. Ships std-only Rust checkers for redundant, missing, unused and over-restrictive lifetimes.

rust-trait-design-reviewer

Review and design Rust traits and generic APIs: generics vs impl Trait vs dyn Trait (static vs dynamic dispatch), dyn compatibility / object safety (generic methods, Self returns, where Self: Sized, error[E0038] not dyn compatible / cannot be made into an object), associated types vs generic parameters, blanket impls, coherence and orphan rule (E0117, E0119, E0210), newtype, extension, sealed and marker traits, supertraits and trait upcasting (1.86), async fn in traits (1.75) and the Send bound problem (trait_variant, async-trait), RPITIT, GATs, From/Into/TryFrom/AsRef/Borrow, std trait checklist (Debug, Clone, PartialEq, Hash, Default, Display, Error, Send/Sync, serde feature), #[must_use], #[non_exhaustive], semver hazards, Deref abuse, builders, typestate, PhantomData, Box<dyn Error + Send + Sync>, Fn traits, mockall.

rust-unsafe-block-auditor

Audit unsafe Rust for soundness: inventory every unsafe block, unsafe fn, unsafe impl/trait, extern block and unsafe attribute, check // SAFETY: comments and # Safety docs, and classify each as sound, needs-justification or likely UB, proposing safe alternatives first. Covers the five unsafe superpowers, aliasing (Stacked/Tree Borrows), invalid values, MaybeUninit vs mem::zeroed/uninitialized, transmute, slice::from_raw_parts, Vec::set_len/from_raw_parts, get_unchecked, CString::as_ptr dangling, unsafe impl Send/Sync, Pin projection, FFI (extern "C", repr(C), C-unwind, Box::into_raw/from_raw), strict provenance, static mut and &raw, edition 2024 (unsafe extern, #[unsafe(no_mangle)], unsafe_op_in_unsafe_fn, env::set_var), Miri, sanitizers, cargo-fuzz, loom, cargo-geiger and clippy safety lints.