SplitRS π¦βοΈ
A production-ready Rust refactoring tool that intelligently splits large files into maintainable modules
SplitRS uses AST-based analysis to automatically refactor large Rust source files (>1000 lines) into well-organized, compilable modules. It handles complex generics, async functions, Arc/Mutex patterns, and automatically generates correct imports and visibility modifiers.
β¨ Features
Core Refactoring
- π― AST-Based Refactoring: Uses
synfor accurate Rust parsing - π§ Intelligent Method Clustering: Groups related methods using call graph analysis
- π¦ Auto-Generated Imports: Context-aware
usestatements with proper paths - π Visibility Inference: Automatically applies
pub(super),pub(crate), orpub - π Complex Type Support: Handles generics, async, Arc/Mutex, nested types
- β‘ Fast: Processes 1600+ line files in <1 second
- β Production-Tested: Successfully refactored 10,000+ lines of real code
Advanced Features (v0.2.0+)
- βοΈ Configuration Files:
.splitrs.tomlsupport for project-specific settings - π Trait Implementation Support: Automatic separation of trait impls into dedicated modules
- π Type Alias Resolution: Intelligent handling of type aliases in import generation
- π Circular Dependency Detection: DFS-based cycle detection with Graphviz export
- π Enhanced Preview Mode: Beautiful formatted preview with statistics before refactoring
- π¬ Interactive Mode: Confirmation prompts before file generation
- π Automatic Rollback Support: Backup creation for safe refactoring
- π Smart Documentation: Auto-generated module docs with trait listings
v0.3.x Features
- π¬ Macro Analyzer: Detects
macro_rules!definitions and#[derive]usage with placement suggestions - π Metrics Dashboard: Cyclomatic complexity analysis with HTML/JSON/text reports (
--metrics) - ποΈ Field Access Tracker: Detects field access patterns to prevent broken visibility during splits
- π Trait Method Tracker: Ensures trait method implementations stay coherent after splitting
- π₯οΈ LSP Integration (
splitrs-lsp): Language server for real-time refactoring guidance- Diagnostics for oversized files and impl blocks
- Code action
Refactor with splitrs(applies aWorkspaceEdit) - Hover showing file metrics (LoC, methods, complexity)
.splitrs.tomlconfig watch with hot reload
v0.3.3 Features
- πΊοΈ Domain-Mapping for
--target-modules: seeded assignment pulls unlisted items into the module with the strongest reference affinity, unknown-name validation with near-miss suggestions, dry-run attribution, and an extended schema (parent,pull_dependencies,doc,max_lines) plus infix/multi-segment glob patterns - π² Nested Inline-Mod Descent (
--split-nested-mods,--max-mod-depth): recursively splits over-budget inlinemod x { ... }blocks through the same analyze β group β generate pipeline - π Facade Style Control (
--facade <glob|named|none>): choose glob re-exports, explicit named re-exports, or declarations-only for generatedmod.rsfacades - βοΈ Verbatim Method Extraction:
SourceMapnow covers individual extracted impl methods, preserving original formatting byte-for-byte - π§ͺ New Integration Test Suites:
acceptance_e2e_tests,domain_mapping_tests,nested_mod_tests
π¦ Installation
Or build from source:
π Quick Start
Basic Usage
# Split a large file into modules
# Preview what will be created (no files written)
# Interactive mode with confirmation
Recommended Usage (with impl block splitting)
Using Configuration Files
Create a .splitrs.toml in your project root:
[]
= 1000
= 500
= true
[]
= "_type"
= "_impl"
[]
= true
= true
Then simply run:
Nested Inline-Mod Descent (v0.3.3)
By default, an over-budget inline mod x { ... } block travels as one opaque
item. With --split-nested-mods true, SplitRS descends into it and re-runs the
full analyze β group β generate pipeline on the module body, recursively:
# Recursively split over-budget inline `mod x { ... }` blocks
# Guard the recursion depth (modules nested deeper stay opaque; default: 8)
# Control the re-export style of every generated mod.rs
Each descended module becomes an x/ directory (x/mod.rs plus per-topic
files) and is declared in the parent mod.rs with its original visibility,
attributes, and doc comments β never re-exported, so historical
crate::x::Item paths keep resolving. super:: paths inside moved items are
deepened by one level per descent (including pub(super) β
pub(in super::super)), and the original file-scope use bindings are
recreated in the generated mod.rs. Composes with --extract-tests
(a per-level tests.rs).
--facade <STYLE> accepts:
glob(default) βpub use module::*;re-exportsnamedβ explicitpub use module::{Foo, bar};lists (better rustdoc, no glob shadowing)noneβ declarations only, for hand-curated re-exports
Domain Mapping with --target-modules (v0.3.3)
Instead of the default types.rs/functions.rs heuristic, a TOML spec can
route items into named domain modules β and, combined with
--split-nested-mods, route them inside a descended module:
# domains.toml
# How items not matched by any rule are assigned:
# "heuristic" (default) β classic types.rs/functions.rs buckets
# "seeded" β pulled into the named module with the strongest
# reference affinity (deterministic fixpoint)
= "seeded"
[[]]
= "hash"
= "core" # route inside the core/ module descended by --split-nested-mods
= ["*hash*", "Sha*"] # exact, prefix Foo*, suffix *Foo, infix *foo*, multi a*b*c, catch-all *
= true # matched items drag their private helpers along
= "Hashing and digest helpers."
[[]]
= "compare"
= "core"
= ["compare_*", "Diff*"]
[[]]
= "config"
= ["Config", "SortBy"] # exact names matching nothing = hard error (with near-miss suggestions)
= 400 # this module overflows into config_2.rs, config_3.rs, ...
Resulting layout (impls and trait impls travel with their self type):
lib_split/
βββ mod.rs # facade: `pub mod core;` β crate::core::Item paths preserved
βββ config.rs # routed by exact name
βββ core/
βββ mod.rs
βββ hash.rs
βββ compare.rs
Specs are validated up front: duplicate module names within the same parent
scope, rules with an empty items list, catch-all * rules that are not last
in their scope, and parent = "..." rules without --split-nested-mods true
are all hard errors.
LSP Integration (Editor Support)
splitrs-lsp is included when you cargo install splitrs (LSP is a default feature). It speaks the Language Server Protocol over stdio and provides:
- π΄ Diagnostics when files exceed your
.splitrs.tomlmax_lineslimit (source: "splitrs", severity: Information) - β‘ Code action
Refactor with splitrsto split large files directly from your editor - βΉοΈ Hover at the top of any Rust file showing metrics (lines of code, method count, avg complexity)
Zero-config quickstart
Neovim (via vim.lsp.start):
require..
-- Or manually:
vim..
Helix (languages.toml):
[[]]
= "rust"
= ["rust-analyzer", "splitrs-lsp"]
[]
= "splitrs-lsp"
Rich editor plugins (in editors/)
For a full-featured experience (config-watch, :SplitrsRefactor command, settings UI), use the plugins in the editors/ directory:
Neovim β editors/nvim/
Full Lua plugin with setup{} API, .splitrs.toml watcher, and :SplitrsRefactor command:
-- With lazy.nvim (from a local checkout):
-- Manual setup:
vim..:
require.
-- Custom options:
require.
VSCode β editors/vscode/
TypeScript extension activating on onLanguage:rust. Sideload:
Configure via settings.json:
Use the Command Palette (Ctrl+Shift+P) β splitrs: Refactor current file.
Emacs β editors/emacs/
Supports both built-in eglot (Emacs 29.1+) and lsp-mode:
;; With use-package:
(use-package splitrs
:load-path "path/to/splitrs/editors/emacs"
:hook ((rust-mode . splitrs-mode)
(rust-ts-mode . splitrs-mode)))
;; Manual:
(add-to-list 'load-path "path/to/splitrs/editors/emacs")
(require 'splitrs)
(splitrs-setup) ; registers with eglot and lsp-mode
;; Refactor from a Rust buffer:
;; M-x splitrs-refactor-current-file
splitrs-lsp runs alongside rust-analyzer β it uses :add-on? t in lsp-mode and appends to eglot-server-programs so neither server displaces the other.
IntelliJ IDEA β editors/intellij/
Kotlin/Gradle plugin using IntelliJ 2024.2+'s built-in LSP API. Build:
# Install: Settings β Plugins β Install Plugin from Disk β build/distributions/*.zip
Requires: IntelliJ IDEA 2024.2 or later, JDK 21, splitrs-lsp on $PATH.
Configuration (all editors)
Create .splitrs.toml in your project root to customise the server:
[]
= 1000 # warn when a file exceeds this many lines
= 300 # warn on oversized impl blocks (if split_impl_blocks = true)
= true
The server hot-reloads .splitrs.toml whenever the file changes.
To use LSP-only (without the full splitrs CLI):
π Examples
Example 1: Trait Implementations
SplitRS automatically detects and separates trait implementations:
Input: user.rs
Command:
Output:
user/
βββ types.rs # struct User definition + inherent impl
βββ user_traits.rs # All trait implementations (Debug, Display, Clone, Default)
βββ mod.rs # Module organization
Generated user_traits.rs:
//! # User - Trait Implementations
//!
//! This module contains trait implementations for `User`.
//!
//! ## Implemented Traits
//!
//! - `Debug`
//! - `Display`
//! - `Clone`
//! - `Default`
//!
//! π€ Generated with [SplitRS](https://github.com/cool-japan/splitrs)
use User;
Example 2: Basic Refactoring
Input: connection_pool.rs (1660 lines)
Command:
Output: 25 well-organized modules
connection_pool/
βββ mod.rs # Module organization & re-exports
βββ connectionpool_type.rs # Type definition with proper visibility
βββ connectionpool_new_group.rs # Constructor methods
βββ connectionpool_acquire_group.rs # Connection acquisition
βββ connectionpool_release_group.rs # Connection release
βββ ... (20 more focused modules)
Example 3: Preview Mode
Get detailed information before refactoring:
Output:
============================================================
DRY RUN - Preview Mode
============================================================
π Statistics:
Original file: 82 lines
Total modules to create: 4
π Module Structure:
π product_traits.rs (2 trait impls)
π user_traits.rs (4 trait impls)
π types.rs (2 types)
π functions.rs (1 items)
πΎ Files that would be created:
π /tmp/preview/
π product_traits.rs
π user_traits.rs
π types.rs
π functions.rs
π mod.rs
============================================================
β Preview complete - no files were created
============================================================
Example 4: Complex Types
SplitRS correctly handles complex Rust patterns:
// Input
// Output (auto-generated)
// cache_type.rs
use HashMap;
use ;
// cache_insert_group.rs
use Cache;
use HashMap;
ποΈ Command-Line Options
| Option | Short | Description | Default |
|---|---|---|---|
--input <FILE> |
-i |
Input Rust source file (required) | - |
--output <DIR> |
-o |
Output directory for modules (required) | - |
--max-lines <N> |
-m |
Maximum lines per module | 1000 |
--split-impl-blocks |
Split large impl blocks into method groups | false | |
--max-impl-lines <N> |
Maximum lines per impl block before splitting | 500 | |
--dry-run |
-n |
Preview without creating files | false |
--interactive |
-I |
Prompt for confirmation before creating files | false |
--config <FILE> |
-c |
Path to configuration file | .splitrs.toml |
--target-modules <TOML-FILE> |
TOML file with [[target_modules]] routing rules for named splits |
- | |
--split-nested-mods <BOOL> |
Descend into over-budget inline mod x { ... } blocks recursively |
false | |
--max-mod-depth <N> |
Recursion depth guard for --split-nested-mods |
8 | |
--facade <STYLE> |
Re-export style in each generated mod.rs: glob, named, none |
glob |
Configuration File Options
When using a .splitrs.toml file, you can configure:
[splitrs] section:
max_lines- Maximum lines per modulemax_impl_lines- Maximum lines per impl blocksplit_impl_blocks- Enable impl block splittingsplit_nested_mods- Descend into over-budget inlinemod x { ... }blocks (default:false)max_mod_depth- Recursion depth guard forsplit_nested_mods(default:8)
[naming] section:
type_module_suffix- Suffix for type modules (default:"_type")impl_module_suffix- Suffix for impl modules (default:"_impl")use_snake_case- Use snake_case for module names (default:true)
[output] section:
module_doc_template- Template for module documentationpreserve_comments- Preserve original comments (default:true)format_output- Format with prettyplease (default:true)facade-mod.rsre-export style:"glob","named", or"none"(default:"glob")
Command-line arguments always override configuration file settings.
π¬ SMT-verified refactoring (experimental β --features smt)
SplitRS can prove certain refactorings preserve semantics before applying them, using OxiZ β a Pure-Rust SMT solver β as the verification backend. This is off by default; build it in with:
Three capabilities are exposed:
--verify-equiv --left FILE::FN --right FILE::FN β prove two pure
fixed-width-integer functions compute the same result for all inputs, or get a
concrete counterexample:
# Proves `a` and `b` are equivalent (QF_BV, all inputs)
--extract-pure β an SMT-verified pre-pass that runs before the split. It
scans every over-budget free function for a pure-integer sub-run, factors it
into a helper, and commits the rewrite only when the solver proves it
equivalent to the original. Committed helpers are ordinary functions that then
flow through the normal split/write pipeline. Non-equivalent or out-of-fragment
candidates are skipped (with a reason) and the original is left untouched.
--verify β emit an honest Semantic verification report that separates
what was proven from what is merely assumed:
- Each
--extract-purebody rewrite that committed β SMT-Verified equivalent (QF_BV, all inputs). - The default whole-item module moves β structural identity: a byte-identical
relocation. SplitRS does not claim to SMT-prove move safety;
name-resolution and visibility correctness is the Rust compiler's job β verify
with
cargo check.
Soundness boundary. The proven fragment is pure, fixed-width integers only:
+ - * & | ^ << >>, comparisons, if/else, let, and integer casts.
Anything outside it β division/remainder, function calls, references, loops,
floats β is reported as Unsupported and never committed (the gate refuses to
rubber-stamp it). Whole-item relocations remain structural identity, not
SMT-proven.
ποΈ How It Works
SplitRS uses a multi-stage analysis pipeline:
- AST Parsing: Parse input file with
syn - Scope Analysis: Determine organization strategy and visibility
- Method Clustering: Build call graph and cluster related methods
- Type Extraction: Extract types from fields for import generation
- Module Generation: Generate well-organized modules with correct imports
- Code Formatting: Format output with
prettyplease
Organization Strategies
Inline - Keep impl blocks with type definition:
typename_module.rs
βββ struct TypeName { ... }
βββ impl TypeName { ... }
Submodule - Split type and impl blocks (recommended for large files):
typename_type.rs # Type definition
typename_new_group.rs # Constructor methods
typename_getters.rs # Getter methods
mod.rs # Module organization
Wrapper - Wrap in parent module:
typename/
βββ type.rs
βββ methods.rs
βββ mod.rs
π Performance
Tested on real-world codebases:
| File Size | Lines | Time | Modules Generated |
|---|---|---|---|
| Small | 500-1000 | <100ms | 3-5 |
| Medium | 1000-1500 | <500ms | 5-12 |
| Large | 1500-2000 | <1s | 10-25 |
| Very Large | 2000+ | <2s | 25-40 |
π§ͺ Testing
SplitRS includes 450 comprehensive tests covering all analysis components:
# Run all tests (recommended)
# Or with the built-in test runner
# Test on example files
π Documentation
API Documentation (docs.rs)
Full API documentation is available at docs.rs/splitrs.
Generate documentation locally:
# Generate and open documentation
# Generate documentation for all features
Module Structure
The codebase is organized into these main modules:
main.rs- CLI interface, file analysis, and module generationconfig.rs- Configuration file parsing and management (.splitrs.toml)method_analyzer.rs- Method dependency analysis and groupingimport_analyzer.rs- Type usage tracking and import generationscope_analyzer.rs- Module scope analysis and visibility inferencedependency_analyzer.rs- Circular dependency detection and graph visualization
Key Types and Traits
Core Types:
FileAnalyzer- Main analyzer for processing Rust filesTypeInfo- Information about a Rust type and its implementationsModule- Represents a generated moduleConfig- Configuration loaded from.splitrs.toml
Analysis Types:
ImplBlockAnalyzer- Analyzes impl blocks for splittingMethodGroup- Groups related methods togetherImportAnalyzer- Tracks type usage and generates importsDependencyGraph- Detects circular dependencies
π Use Cases
When to Use SplitRS
β Perfect for:
- Files >1000 lines with large impl blocks
- Monolithic modules that need organization
- Legacy code refactoring
- Improving code maintainability
β οΈ Consider Carefully:
- Files with circular dependencies (will generate modules but may need manual fixes)
- Files with heavy macro usage (basic support, may need manual review)
β Not Recommended:
- Files <500 lines (probably already well-organized)
- Files with complex conditional compilation (
#[cfg])
π§ Integration
CI/CD Pipeline
# .github/workflows/refactor.yml
name: Auto-refactor
on:
workflow_dispatch:
inputs:
file:
description: 'File to refactor'
required: true
jobs:
refactor:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
- run: cargo install splitrs
- run: |
splitrs --input ${{ github.event.inputs.file }} \
--output $(dirname ${{ github.event.inputs.file }})/refactored \
--split-impl-blocks
- uses: peter-evans/create-pull-request@v5
with:
title: "Refactor: Split ${{ github.event.inputs.file }}"
π€ Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
Development Setup
Implemented Features (v0.3.4 β Latest Release)
v0.3.4 Highlights (2026-07-06):
- β
Nested-mod descent correctness review: relocated private inline
moditems are widened topub(super)(newItem::Modarm inupgrade_type_visibility), fixingE0603against theuse self::<bucket>::<mod>;re-binding in generatedmod.rs - β
Parent-scope binding recreation no longer drops the forwarded
use super::*;glob when an unresolved bare fn call or method belongs to an item the parent scope provides (compute_parent_scope_items/ParentScopeItems); fixesE0425/E0599in descended module bodies - β
macro_rules!names excluded from the type-to-module import map, eliminating bogususe super::macros::<name>;imports (E0432) and the resultingE0659ambiguity with#[macro_use]-expanded macros - β
collect_use_bound_nameswidenedpub(super)βpub(crate)sonested_mod_splittercan enumerate the bindings a generatedmod.rsrecreates for its descended children - β
Parent-scope import pruning also subtracts names the nested body binds through its own non-
superuse trees, removing duplicatedunused_importswarnings from emittedmod.rs - β
Test suite: 570 tests passing with
--all-features(499 with default features, 1 skipped), was 565 in v0.3.3 β five new regression tests, one per review finding
v0.3.3 Highlights (2026-07-06):
- β
Domain-mapping for
--target-modules(seeded assignment, unknown-name validation, dry-run attribution, extended schema:parent/pull_dependencies/doc/max_lines, infix/multi-segment glob patterns,validate_target_modules()) - β
Nested inline-mod descent (
--split-nested-mods,--max-mod-depth): recursively splits over-budget inlinemod x { ... }blocks - β
--facade <glob|named|none>flag /[output] facadeconfig option for controlling generatedmod.rsre-export style - β
Verbatim source slicing (
src/source_map.rs) extended to cover individual extracted impl methods - β
New integration test suites:
acceptance_e2e_tests,domain_mapping_tests,nested_mod_tests - β
run_workspace_modeextracted into its own module,src/workspace_mode.rs - β
Dependency bumps:
syngainedvisit-mutfeature,proc-macro2added (span-locations), tokio 1.52.1β1.52.3, dashmap 6.1.0β6.2.1 - β
Test suite: 565 tests passing with
--all-features(494 with default features), was 450 in v0.3.2
v0.3.2 Highlights (2026-06-09):
- β
SMT-verified function extraction (
--features smt --extract-pure): extracts pure integer sub-blocks from over-budget free functions, committing only when OxiZ proves semantic equivalence - β
SMT equivalence oracle (
splitrs smt-verify-equiv): standalone equivalence checker between two Rust functions using QF_BV theory - β
Array-splitting mode (
--split-arrays): splits oversizedstatic/constarray literals across chunk files withconst fncompile-time reconstruction - β
Test-module splitter (
--split-test-modules): splits multiple#[cfg(test)]blocks into per-moduletests_NAME.rsfiles - β
Editor integrations shipped in
editors/: Emacs, IntelliJ, Neovim, VSCode - β
module_generatorrefactored intosrc/module_generator/(3 modules, all under 2000 lines) - β Test suite: 450 tests passing (was 269 in v0.3.1)
v0.3.1 Highlights:
- β
LSP Integration (
splitrs-lspbinary, tower-lsp, diagnostics, code actions, hover, config watch) - β Batched trait implementations into shared modules to reduce file clutter
- β
Accurate line count estimation via
prettypleaseformatting - β
Conditional
lib.rspreservation (writesmod.rsinstead of overwriting the crate root) - β
Deduplicated
std::collectionsimport handling across split modules
v0.3.0 Highlights:
- β
Macro Analyzer (
macro_rules!detection,#[derive]tracking, placement suggestions) - β Metrics Dashboard (cyclomatic complexity, HTML/JSON/text reports)
- β Field access tracking for smarter module splitting
- β Trait method tracking for coherent trait splitting
- β No-unwrap policy compliance (production code)
- β Refactored main.rs into file_analyzer.rs + module_generator.rs
- β Dependencies upgraded (toml 1.0, rayon 1.11)
v0.2.x Features:
- β
Configuration file support (
.splitrs.toml) - β Trait implementation separation & trait bound tracking
- β Type alias resolution & circular dependency detection
- β Incremental refactoring with merge strategies
- β Custom naming strategies (snake_case, domain-specific, kebab-case)
- β Workspace-level refactoring with parallel processing (rayon)
- β Enhanced error recovery, rollback support
- β CI/CD templates (GitHub Actions, GitLab CI)
- β Private helper dependency tracking & glob import analysis
- β Comprehensive benchmarking suite (Criterion)
Roadmap to v1.0
Current status: 95% production-ready
Next features (v0.4.0+):
- Macro expansion support (full
cargo expandintegration) - Extended SMT fragment: division, loops, references
Future enhancements (v0.5.0+):
- Cross-language support exploration
- AI-assisted refactoring
π License
Licensed under the Apache License, Version 2.0 (LICENSE or http://www.apache.org/licenses/LICENSE-2.0).
π Acknowledgments
- Built with syn for Rust parsing
- Formatted with prettyplease
- Developed during the OxiRS refactoring project (32,398 lines refactored)
π Resources & Support
- π API Documentation: docs.rs/splitrs
- π¦ Crate: crates.io/crates/splitrs
- π» Source Code: github.com/cool-japan/splitrs
- π Issue Tracker: github.com/cool-japan/splitrs/issues
- π¬ Discussions: github.com/cool-japan/splitrs/discussions
Getting Help
- Check the docs: Read the API documentation and examples
- Search issues: Check if your question is already answered in issues
- Ask questions: Start a discussion
- Report bugs: Open an issue with a reproducible example
Made with β€οΈ by the OxiRS team | Star β us on GitHub!
Sponsorship
SplitRS is developed and maintained by COOLJAPAN OU (Team Kitasan).
If you find SplitRS useful, please consider sponsoring the project to support continued development of the Pure Rust ecosystem.
https://github.com/sponsors/cool-japan
Your sponsorship helps us:
- Maintain and improve the COOLJAPAN ecosystem
- Keep the entire ecosystem (OxiBLAS, OxiFFT, SciRS2, etc.) 100% Pure Rust
- Provide long-term support and security updates