Agent skill

Rust Expert

by afnanenayet in afnanenayet/diffsitter

Expert Rust guidance for diffsitter: tree-sitter FFI patterns, lifetime management, unsafe optimization, edition 2024 idioms.

MITAuto-check: notes

Install Rust Expert

skills CLI
$ npx skills add afnanenayet/diffsitter --skill rust-expert -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install afnanenayet/diffsitter rust-expert --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/afnanenayet/diffsitter.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.claude/skills/rust-expert .claude/skills/rust-expert && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
rust-expert
GitHub stars
2.4k
Token cost
~2.4k tokens
SKILL.md length
894 words
Files
1
Skills in repo
4
Repo updated
First seen
Licence
MIT

At a glance

Expert Rust guidance for diffsitter: tree-sitter FFI patterns, lifetime management, unsafe optimization, edition 2024 idioms.

  • Works in 10 steps: Tree-sitter Rust API Patterns → FFI Safety with Box::leak → Interior Mutability with RefCell → …
  • The user needs help with Rust patterns
  • SKILL.md covers Project Context, 1. Tree-sitter Rust API Patterns, 2. FFI Safety with Box::leak and 3. Interior Mutability with…, plus 8 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Rust Expert is an agent skill from afnanenayet/diffsitter. Expert Rust guidance for diffsitter: tree-sitter FFI patterns, lifetime management, unsafe optimization, edition 2024 idioms. Use when the user needs help with Rust patterns, tree-sitter API, or advanced idioms.

Its SKILL.md is about 2.4k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It works with Rust. The repository describes itself as: A tree-sitter based AST difftool to get meaningful semantic diffs. The licence is MIT.

When your agent uses it

  • The user needs help with Rust patterns
  • Tree-sitter API
  • Advanced idioms

Example prompts

  • “/rust-expert”

Requirements

  • Pre-approved tools (allowed-tools): Read, Grep, Glob, Bash

Workflow steps

10 steps, taken from the step headings in SKILL.md.

  1. Tree-sitter Rust API Patterns
  2. FFI Safety with Box::leak
  3. Interior Mutability with RefCell
  4. Unsafe Optimization in Hot Loops
  5. Type-Level Distinctions with DocumentType
  6. Compile-Time Maps with phf
  7. Zero-Cost Polymorphism with enum_dispatch
  8. Cow for Optional Text Transformations
  9. Cached FFI Values
  10. Edition 2024 Specifics

What it can do on your machine

Read from SKILL.md and the folder at commit a5a6681. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Grep
    • Glob
    • Bash

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are rust).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Rust Expert loads about 2.4k tokens when it runs. Until then it costs about 56 tokens; SKILL.md has 894 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~56
When it runs · the whole SKILL.md, loaded when a task matches
~2.4k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check: notes

The automated check noted patterns worth knowing about, such as sudo or a known installer.

  • NotePre-approves every shell command (allowed-tools: Bash)SKILL.md
    allowed-tools: Read, Grep, Glob, Bash

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from afnanenayet/diffsitter at commit a5a6681, republished under its MIT licence (© afnanenayet). 894 words, ~2,395 tokens.

Download SKILL.mdSave it as .claude/skills/rust-expert/SKILL.md (or your agent's skills folder).
name
rust-expert
description
Expert Rust guidance for diffsitter: tree-sitter FFI patterns, lifetime management, unsafe optimization, edition 2024 idioms. Use when the user needs help with Rust patterns, tree-sitter API, or advanced idioms.
allowed-tools
Read, Grep, Glob, Bash
user-invocable
true
argument-hint
[topic] Describe what you need help with

Rust Expert Guidance for diffsitter

You are an expert Rust consultant for the diffsitter codebase. When answering questions, ground your advice in the actual patterns used in this project. Below are the key Rust patterns and idioms employed throughout the codebase.

Project Context

  • MSRV: !grep 'rust-version' Cargo.toml
  • Tree-sitter version: !grep '^tree-sitter' Cargo.toml
  • Edition: 2024 (Rust edition, set in Cargo.toml)

1. Tree-sitter Rust API Patterns

File: src/parse.rs

Parser creation follows this sequence: create a Parser, generate a Language from the grammar, set it on the parser, then parse text into a Tree:

rust
let mut parser = Parser::new();
let ts_lang = generate_language(resolved_language, config)?;
parser.set_language(&ts_lang)?;
let tree = parser.parse(&text, None);

Node traversal uses TreeCursor via node.walk() and node.children(&mut cursor). See src/input_processing.rs function build() which walks the tree recursively:

rust
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
    build(vector, child, text, pseudo_leaf_types);
}

Key lifetime constraint: Node<'a> borrows from the Tree. The Tree must outlive all Node references. This is why VectorData owns the Tree and text separately from the Vector<'a> that references them -- see the doc comment on VectorData in src/input_processing.rs.

2. FFI Safety with Box::leak

File: src/parse.rs, function construct_ts_lang_from_shared_lib

When loading dynamic grammars, the shared library must remain in memory for the entire program lifetime. The code intentionally leaks it:

rust
let shared_library = Box::new(libloading::Library::new(parser_path.as_os_str())?);
let static_shared_library = Box::leak(shared_library);
let constructor = static_shared_library.get::<libloading::Symbol<
    unsafe extern "C" fn() -> Language,
>>(constructor_symbol_name.as_bytes())?;
constructor()

Why: The Language object returned by the constructor references function pointers inside the shared library. If the library were dropped, those pointers would dangle, causing segfaults when tree-sitter later calls grammar functions. Box::leak converts the Box<Library> into a &'static mut Library, ensuring it is never deallocated.

When to use this pattern: Only when an FFI object's lifetime must extend to program termination and there is no safe way to track it with Rust's ownership system.

3. Interior Mutability with RefCell

File: src/input_processing.rs, function from_ts_tree

A RefCell<Vec<VectorLeaf>> is used to accumulate leaves during recursive tree traversal, then consumed with into_inner():

rust
let leaves = RefCell::new(Vec::new());
build(&leaves, tree.root_node(), text, pseudo_leaf_types);
Vector {
    leaves: leaves.into_inner(),
    source_text: text,
}

Inside build(), the vector is mutated via vector.borrow_mut().push(...). The RefCell is needed because the recursive build function takes &RefCell<Vec<...>> rather than &mut Vec<...>, avoiding mutable borrow conflicts during recursion. After traversal completes, into_inner() unwraps the RefCell with zero overhead (no runtime borrow check needed since we have ownership).

4. Unsafe Optimization in Hot Loops

File: src/diff.rs, functions common_prefix_len and common_suffix_len

The Myers diff algorithm's inner loops use get_unchecked for performance:

rust
unsafe {
    while a_range.start + l < a_range.end
        && b_range.start + l < b_range.end
        && a.get_unchecked(a_range.start + l) == b.get_unchecked(b_range.start + l)
    {
        l += 1;
    }
}

Safety argument: The loop conditions (a_range.start + l < a_range.end and b_range.start + l < b_range.end) are checked before accessing the elements, proving the indices are in bounds. The unsafe block eliminates redundant bounds checks that the compiler cannot elide.

Convention: Always pair get_unchecked with debug_assert! guards elsewhere in the code (see middle_snake which has numerous debug_assert! calls verifying coordinate ranges). Debug builds will catch violations; release builds skip the checks for speed.

5. Type-Level Distinctions with DocumentType<T>

File: src/diff.rs, around line 235

The DocumentType<T> enum encodes whether data comes from the old or new document at the type level:

rust
pub enum DocumentType<T: Debug + PartialEq + Serialize + Clone> {
    Old(T),
    New(T),
}

It implements AsRef<T>, AsMut<T>, and a consume(self) -> T method for ergonomic access without matching. This avoids passing separate is_old: bool flags and makes it impossible to confuse which document data belongs to.

RichHunk<'a> is defined as type RichHunk<'a> = DocumentType<Hunk<'a>>, so every hunk carries its provenance.

6. Compile-Time Maps with phf

File: build.rs (codegen) and src/parse.rs (usage)

The FILE_EXTS map is a phf::Map providing O(1) perfect hash lookup from file extensions to language names:

rust
static FILE_EXTS: phf::Map<&'static str, &'static str> = phf_map! {
    "rs" => "rust",
    "py" => "python",
    // ...
};

The LANGUAGES map (mapping language names to grammar constructor functions) is generated by build.rs using codegen_language_map(), which emits:

rust
static LANGUAGES: phf::Map<&'static str, unsafe extern "C" fn() -> Language> = phf_map! {
    "rust" => tree_sitter_rust,
    // ...
};

This is included at compile time via include!(concat!(env!("OUT_DIR"), "/generated_grammar.rs")) in src/parse.rs.

Show full SKILL.md (349 more words)Show less

7. Zero-Cost Polymorphism with enum_dispatch

File: src/render/mod.rs

The Renderer trait uses enum_dispatch for static dispatch instead of Box<dyn Renderer>:

rust
#[enum_dispatch(Renderers)]
pub trait Renderer {
    fn render(
        &self,
        writer: &mut dyn Write,
        data: &DisplayData,
        term_info: Option<&Term>,
    ) -> anyhow::Result<()>;
}

#[enum_dispatch]
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize, Display, EnumIter, EnumString)]
#[strum(serialize_all = "snake_case")]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Renderers {
    Unified,
    Json,
}

enum_dispatch auto-generates match-based dispatch, eliminating vtable indirection. Each variant is a concrete type (Unified, Json) that implements Renderer. Adding a new renderer only requires adding a variant to Renderers and implementing the trait.

8. Cow<str> for Optional Text Transformations

File: src/input_processing.rs, Entry struct

rust
pub struct Entry<'node> {
    pub text: Cow<'node, str>,
    // ...
}

Cow<'node, str> avoids allocation when text does not need transformation. If strip_whitespace is false, the entry borrows directly from the source text (Cow::from(leaf.text) which is Cow::Borrowed). If whitespace stripping is needed, Cow::from(leaf.text.trim()) may allocate only if the trimmed result differs. This is a zero-cost abstraction when no transformation is needed.

9. Cached FFI Values

File: src/input_processing.rs, Entry struct

rust
pub struct Entry<'node> {
    pub reference: TSNode<'node>,
    pub kind_id: u16,
    // ...
}

The kind_id is cached from TSNode::kind_id() at construction time. This avoids crossing the FFI boundary on every comparison during diffing, where kind_id is checked via the PartialEq implementation:

rust
impl PartialEq for Entry<'_> {
    fn eq(&self, other: &Entry) -> bool {
        self.kind_id == other.kind_id && self.text == other.text
    }
}

The comment notes: "Caching it here saves some time because it is queried repeatedly later. If we don't store it inline then we have to cross the FFI boundary which incurs some overhead." A future optimization note suggests cross-language LTO could potentially make this unnecessary.

10. Edition 2024 Specifics

File: build.rs, function compile_static_grammars

The codegen emits unsafe extern "C" blocks, which is the edition 2024 syntax for declaring foreign functions:

rust
writeln!(
    codegen,
    "unsafe extern \"C\" {{ pub fn tree_sitter_{language}() -> Language; }}"
)?;

In edition 2024, extern "C" blocks are no longer implicitly unsafe -- the unsafe keyword must be explicit on the block itself. This is a breaking change from edition 2021 where extern "C" { ... } was implicitly unsafe. If you are writing new FFI declarations, always use unsafe extern "C" { ... }.

Guidelines for Answering Questions

  1. Always reference the specific file and function when discussing a pattern.
  2. When suggesting new code, follow the existing conventions (e.g., use Cow<str> for optional transforms, cache FFI values, prefer enum_dispatch over trait objects).
  3. For unsafe code, always articulate the safety argument and add debug_assert! guards.
  4. Remember that Node<'a> borrows from Tree -- any API that returns nodes must keep the tree alive.
  5. When working with tree-sitter grammars, be aware of the ABI compatibility check in ts_language_abi_checked.

© afnanenayet, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .claude/skills/rust-expert of afnanenayet/diffsitter.

Open the folder on GitHubat commit a5a6681

Compare with similar skills

Rust Expert next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Rust Expert compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Rust Expert this skillafnanenayet/diffsitter2.4k—~2.4kAutomated safety check: NotesMIT
Update V8 Versionopeninterpreter/openinterpreter69k2 repos~845Automated safety check: PassApache-2.0
Firecrawl Page Scrape Integrationfirecrawl/firecrawl190k1 repos~944Automated safety check: PassISC
Migrate Core Code to Submodulestinyhumansai/openhuman42k—~2.6kAutomated safety check: PassGPL-3.0
Rust TDD Workflowrtk-ai/rtk83k—~753Automated safety check: NotesApache-2.0
OpenLogi macOS Permissions TriageAprilNEA/OpenLogi23k—~2.5kAutomated safety check: NotesApache-2.0

Similar skills

  • Update V8 Version

    openinterpreter/openinterpreter

    Bumps the pinned v8 and rusty_v8 versions in Codex, validates the release-candidate path with the v8-canary check, and traces failures to upstream build changes.

    69k GitHub starsUsed in 2 repos~845 tokens
    DevOps & CloudAuto-check passed
  • Adds Firecrawl's /scrape endpoint to application code to pull markdown, HTML, links, screenshots or structured data from a single known URL.

    190k GitHub starsUsed in 1 repo~944 tokens
    Data & AnalyticsAuto-check passed
  • Migrate Core Code to Submodules

    tinyhumansai/openhuman

    Plans and carries out moving non-host-specific code and its tests from the OpenHuman core into vendored tiny submodule libraries, then releases the submodule and re-pins the host.

    42k GitHub stars~2.6k tokensUpdated today
    DevelopmentAuto-check passed
  • Enforces red-green-refactor for Rust work, with idiomatic test patterns, a naming convention and a pre-commit gate of cargo fmt, clippy and test.

    83k GitHub stars~753 tokensUpdated today
    Testing & QAAuto-check: notes
  • Decides whether an OpenLogi device problem on macOS is a privacy-permission (TCC) problem, using agent log lines, and says which identity needs which grant.

    23k GitHub stars~2.5k tokensUpdated today
    DevelopmentAuto-check: notes
  • Guide for writing idiomatic Rust code based on Apollo GraphQL's best practices handbook.

    5.6k GitHub starsUsed in 3 repos~1.1k tokens
    DevelopmentAuto-check passed

More from afnanenayet/diffsitter

  • Add Grammar

    afnanenayet/diffsitter

    Step-by-step guide for adding a new tree-sitter language grammar to diffsitter.

    2.4k GitHub stars~1.9k tokensUpdated yesterday
    Auto-check: notes
  • Add Renderer

    afnanenayet/diffsitter

    Step-by-step guide for adding a new diff output renderer to diffsitter.

    2.4k GitHub stars~1.4k tokensUpdated yesterday
    Auto-check: notes
  • Debug Diff

    afnanenayet/diffsitter

    Diagnose unexpected diff output by tracing the pipeline from parsing through AST processing to hunk generation.

    2.4k GitHub stars~2.4k tokensUpdated yesterday
    Auto-check: notes

Works with

Questions about Rust Expert

What does Rust Expert do?

Expert Rust guidance for diffsitter: tree-sitter FFI patterns, lifetime management, unsafe optimization, edition 2024 idioms. Rust Expert is an agent skill from afnanenayet/diffsitter. Expert Rust guidance for diffsitter: tree-sitter FFI patterns, lifetime management, unsafe optimization, edition 2024 idioms.

When should I use Rust Expert?

Rust Expert fits situations like: the user needs help with Rust patterns; tree-sitter API; advanced idioms.

How do I install Rust Expert in Claude Code?

Run `npx skills add afnanenayet/diffsitter --skill rust-expert -a claude-code`. Or copy the skill folder (.claude/skills/rust-expert in afnanenayet/diffsitter) into .claude/skills/rust-expert in your project. Claude Code loads it when a task matches its description.

How do I install Rust Expert in Codex?

Run `npx skills add afnanenayet/diffsitter --skill rust-expert -a codex`. Or copy the skill folder (.claude/skills/rust-expert in afnanenayet/diffsitter) into .agents/skills/rust-expert in your project. Codex loads it when a task matches its description.

Can I use Rust Expert in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add afnanenayet/diffsitter --skill rust-expert -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/rust-expert, .gemini/skills/rust-expert, .github/skills/rust-expert and .opencode/skills/rust-expert in your project.

What does Rust Expert need to run?

SKILL.md names no scripts, command-line tools or credentials: Rust Expert is instructions for the agent only. Its frontmatter pre-approves these tools: Read, Grep, Glob, Bash.

Does Rust Expert access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Rust Expert safe to install?

Our automated static check of SKILL.md found notes only (pre-approves every shell command (allowed-tools: bash)), nothing it rates as a warning. It is not a guarantee. Review the folder before installing.

What licence does Rust Expert use?

Rust Expert is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Rust Expert use?

About 2.4k tokens (SKILL.md is roughly 9.6k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Rust Expert?

Skills that share tags, products or a category with Rust Expert: Update V8 Version (openinterpreter/openinterpreter, 69k stars), Firecrawl Page Scrape Integration (firecrawl/firecrawl, 190k stars), Migrate Core Code to Submodules (tinyhumansai/openhuman, 42k stars) and Rust TDD Workflow (rtk-ai/rtk, 83k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Rust Expert?

afnanenayet (a GitHub user) maintains it in afnanenayet/diffsitter, which has 2,405 GitHub stars. The repository holds 4 skills in this directory. The repository was last updated on October 8, 2026.

Source: afnanenayet/diffsitter on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.