splitrs 0.2.3

AST-based Rust refactoring tool with trait separation, config files, and intelligent module generation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# SplitRS TODO & Feature Roadmap

This document outlines planned features, improvements, and known issues for SplitRS.

## Priority 1: Core Functionality Improvements

### 1. Configuration File Support
**Status:** ✅ IMPLEMENTED (v0.2.0)

Add support for `.splitrs.toml` configuration file to store project-specific settings:

```toml
[splitrs]
max_lines = 1000
max_impl_lines = 500
split_impl_blocks = true

[naming]
type_module_suffix = "_type"
impl_module_suffix = "_impl"

[output]
module_doc_template = "//! Auto-generated module for {type_name}\n"
preserve_comments = true
```

**Benefits:**
- Consistent refactoring across team
- Version-controlled refactoring settings
- Project-specific customization

---

### 2. Trait Implementation Support
**Status:** ✅ IMPLEMENTED (v0.2.0)

Currently, SplitRS handles inherent `impl` blocks well, but trait implementations need special handling:

- Detect `impl Trait for Type` blocks
- Group trait impls separately from inherent impls
- Generate appropriate module structure for trait impls
- Handle associated types and constants

**Example:**
```rust
// Input
impl Display for User { ... }
impl Debug for User { ... }
impl Serialize for User { ... }

// Output
user_type.rs          // Type definition
user_impl.rs          // Inherent impls
user_traits.rs        // All trait impls
```

---

### 3. Type Alias Resolution
**Status:** ✅ IMPLEMENTED (v0.2.0)

Improve handling of type aliases in import generation:

```rust
type UserId = u64;
type Result<T> = std::result::Result<T, Error>;

// Should correctly resolve and import these when used in methods
```

---

### 4. Circular Dependency Detection
**Status:** ✅ IMPLEMENTED (v0.2.0)

Add analysis to detect and warn about circular dependencies:

- Build full dependency graph before splitting
- Detect cycles in type relationships
- Provide warnings with suggestions for breaking cycles
- Generate dependency visualization (DOT format)

**Output:**
```
⚠️  Warning: Circular dependency detected
   TypeA (module_a.rs) -> TypeB (module_b.rs) -> TypeC (module_c.rs) -> TypeA

   Suggestions:
   - Consider introducing a trait to break the cycle
   - Move common dependencies to a separate module
```

---

## Priority 2: Developer Experience

### 5. Preview Mode (Dry Run Enhancement)
**Status:** ✅ IMPLEMENTED (v0.2.0)

Enhance the current `--dry-run` flag with detailed preview:

```bash
splitrs --input file.rs --output out/ --preview
```

**Features:**
- Show unified diff of changes
- Display module structure as tree
- Estimate compilation time impact
- Show before/after metrics (LOC, cyclomatic complexity)

---

### 6. Interactive Mode
**Status:** ✅ IMPLEMENTED (v0.2.0)

Add interactive CLI for guided refactoring:

```bash
splitrs --interactive --input file.rs
```

**Workflow:**
1. Show analysis results
2. Let user approve/modify module names
3. Preview each module before generation
4. Allow custom method grouping

---

### 7. Rollback/Undo Support
**Status:** ✅ IMPLEMENTED (v0.2.0)

Add ability to undo refactoring:

```bash
splitrs --rollback out/
```

**Implementation:**
- Create `.splitrs.backup/` with original files
- Store metadata about the refactoring operation
- Provide rollback command to restore original state

---

### 8. Module Documentation Generation
**Status:** ✅ IMPLEMENTED (v0.2.0)

Auto-generate meaningful documentation for split modules:

```rust
//! # User Implementation - Constructor Methods
//!
//! This module contains constructor and factory methods for the `User` type.
//!
//! ## Methods
//! - `new()` - Create a new user
//! - `from_json()` - Deserialize from JSON
//! - `with_defaults()` - Create with default values
```

**Features:**
- Extract method summaries from doc comments
- Group by functionality
- Generate cross-references

---

## Priority 3: Advanced Features

### 9. Incremental Refactoring
**Status:** ✅ IMPLEMENTED (v0.2.2)

Support refactoring files that have already been partially split:

- Detect existing module structure
- Only refactor new or modified code
- Preserve manual customizations
- Merge with existing modules intelligently

**Usage:**
```bash
splitrs -i file.rs -o out/ --incremental --merge-strategy smart
```

**Merge Strategies:**
- `smart` (default): Preserve manual edits, update auto-generated
- `add-only`: Only add new types/impls, never update existing
- `replace`: Replace all content
- `skip-customized`: Skip modules with manual edits

---

### 10. Custom Naming Strategies
**Status:** ✅ IMPLEMENTED (v0.2.2)

Allow users to customize module naming:

```rust
// Plugin-based naming strategy
trait NamingStrategy {
    fn module_name(&self, type_name: &str, purpose: ModulePurpose) -> String;
    fn suggest_group_name(&self, type_name: &str, methods: &MethodNamingInfo) -> String;
}
```

**Built-in strategies:**
- `snake_case` (default): Standard Rust naming (user_type, user_impl)
- `domain-specific`: Smart naming for patterns (UserRepository → user_repository_repo)
- `kebab-case`: Hyphenated module names

**Usage:**
```bash
splitrs -i file.rs -o out/ --naming-strategy domain-specific
```
- `kebab-case`
- Domain-specific (e.g., `user_repository`, `user_service`)

---

### 11. Macro Expansion Support
**Estimated effort:** 12-15 hours
**Status:** Research

Improve handling of declarative and procedural macros:

- Optionally expand macros before analysis
- Preserve macro invocations in output
- Handle `#[derive]` macros correctly
- Support custom derive macros

**Challenges:**
- Requires macro expansion (potentially via `cargo expand`)
- Need to preserve original macro invocations
- Complex for procedural macros

---

### 12. Workspace-Level Refactoring
**Status:** ✅ IMPLEMENTED (v0.2.3)

Support refactoring across entire Cargo workspaces:

```bash
splitrs --workspace --target 1000  # Split all files >1000 lines
```

**Features:**
- Process multiple crates
- Update cross-crate imports
- Maintain workspace consistency
- Parallel processing
- Process multiple crates
- Update cross-crate imports
- Maintain workspace consistency
- Parallel processing

---

### 13. Integration Test Generation
**Status:** ✅ IMPLEMENTED (v0.2.2)

Generate integration tests to verify refactoring correctness:

```rust
// refactoring_tests.rs (auto-generated)
#[test]
fn verify_all_types_exported() {
    // Compile-time checks that all types are accessible
    let _: Option<User> = None;
    let _: Option<Product> = None;
}

#[test]
fn verify_trait_implementations() {
    // Verify traits are still implemented
    fn _assert_debug<T: std::fmt::Debug>() {}
    _assert_debug::<User>();
}
```

**Usage:**
```bash
splitrs -i file.rs -o out/ --generate-tests
```

---

### 14. LSP Integration
**Estimated effort:** 15-20 hours
**Status:** Research

Provide Language Server Protocol integration:

- Real-time refactoring suggestions in editor
- Quick-fix actions for large files
- Preview refactoring in editor
- Integration with rust-analyzer

---

## Priority 4: Code Quality & Performance

### 15. Benchmarking Suite
**Status:** ✅ IMPLEMENTED (v0.2.1)

Add comprehensive benchmarks using `criterion`:

```rust
criterion_group!(benches,
    bench_small_file,
    bench_large_file,
    bench_complex_generics,
    bench_method_clustering
);
```

**Metrics:**
- Parsing time
- Analysis time
- Code generation time
- Memory usage

---

### 16. Parallel Module Generation
**Status:** ✅ IMPLEMENTED (v0.2.3)

Use `rayon` for parallel processing:

- Parse multiple files concurrently
- Generate modules in parallel
- Speed up large workspace refactoring

**Expected improvement:** 3-5x faster on multi-core systems

**Usage:**
```bash
splitrs --parallel --threads 4  # Use 4 threads
splitrs --parallel              # Use all available cores
```

---

### 17. Error Recovery
**Status:** ✅ IMPLEMENTED (v0.2.3)

Improve error handling and recovery:

- Continue processing after non-critical errors
- Provide detailed error messages with code snippets
- Suggest fixes for common issues
- Partial output generation when possible
- Rollback support for failed operations

**Usage:**
```bash
splitrs --continue-on-error  # Continue processing on failures
splitrs --rollback           # Enable rollback on failure
```

---

## Priority 5: Ecosystem Integration

### 18. CI/CD Templates
**Status:** ✅ IMPLEMENTED (v0.2.3)

Provide ready-to-use CI/CD configurations:

- GitHub Actions workflow (`templates/github-actions.yml`)
- GitLab CI template (`templates/gitlab-ci.yml`)
- Automated file size checks
- Refactoring suggestions on PRs
- Code quality reports

---

### 19. Editor Plugins
**Estimated effort:** 20-30 hours per editor
**Status:** Research

- VS Code extension
- IntelliJ IDEA plugin
- Vim/Neovim plugin
- Emacs package

---

### 20. Metrics Dashboard
**Estimated effort:** 8-10 hours
**Status:** Planned

Generate HTML report with metrics:

- Complexity reduction
- Module organization visualization
- Dependency graph
- Refactoring impact analysis

---

## Known Issues & Bugs

### Critical
- None currently identified

### High Priority
- [x] Generic type parameters not always correctly preserved in split impl blocks (FIXED v0.2.1)
- [x] `#[cfg]` conditional compilation attributes may cause incorrect splitting (FIXED v0.2.1)
- [x] Lifetime parameters in associated types need better handling (FIXED v0.2.1)

### Medium Priority
- [x] Doc comments on impl blocks are sometimes lost (FIXED v0.2.1)
- [x] Very long method names (>100 chars) break module naming (FIXED v0.2.1)
- [x] Unicode in identifiers not fully tested (FIXED v0.2.1 - comprehensive tests added)

### Low Priority
- [x] Generated code could be more idiomatic in some cases (FIXED v0.2.1 - enhanced error messages)
- [x] Module naming could be smarter for domain-specific patterns (FIXED v0.2.1 - domain-specific naming)
- [x] Performance optimization for files >5000 lines (FIXED v0.2.1 - benchmarking suite added)

---

## Research & Exploration

### Future Possibilities

1. **AI-Assisted Refactoring**
   - Use LLM to suggest optimal module organization
   - Semantic grouping based on code understanding
   - Auto-generate module documentation

2. **Cross-Language Support**
   - Adapt approach for other languages (TypeScript, Go, etc.)
   - Common refactoring framework

3. **Refactoring Patterns Library**
   - Common patterns database
   - Suggested refactorings based on codebase analysis
   - Anti-pattern detection

4. **Distributed Analysis**
   - Cloud-based analysis for very large codebases
   - Team collaboration on refactoring plans
   - Centralized refactoring history

---

## Contributing

Want to implement any of these features? See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

**Good First Issues:**
- Editor plugins (VS Code, IntelliJ, Vim)
- Enhanced dry-run mode with diff output
- Metrics dashboard implementation
- Pre-commit hook templates

**Advanced Issues:**
- Macro expansion support
- LSP integration
- Workspace-level refactoring
- Editor plugins

---

## Version Planning

### v0.2.0 (Released)
- ✅ Configuration file support
- ✅ Trait implementation support
- ✅ Preview mode enhancement
- ✅ Circular dependency detection

### v0.2.1 (Released)
- ✅ Generic type parameters preservation
- ✅ Lifetime parameters handling
- ✅ #[cfg] and attribute preservation
- ✅ Doc comments preservation
- ✅ Long method name handling
- ✅ Unicode identifier support
- ✅ Benchmarking suite with criterion
- ✅ Integration test suite (9 tests)
- ✅ Enhanced error messages with context
- ✅ Input validation and error recovery
- ✅ Domain-specific module naming (serialization, CRUD, predicates, builders, etc.)
- ✅ Generated code validation

### v0.2.2 (Released)
- ✅ Incremental refactoring mode with merge strategies
- ✅ Custom naming strategies (snake_case, domain-specific, kebab-case)
- ✅ Integration test generation (--generate-tests)
- ✅ NamingStrategy trait for extensibility
- ✅ Enhanced configuration with naming and incremental options
- ✅ Test suite expanded to 62 tests (53 unit + 9 integration)

### v0.2.3 (Released)
- ✅ Workspace-level refactoring (--workspace)
- ✅ Parallel module generation with rayon (--parallel)
- ✅ Enhanced error recovery (--continue-on-error, --rollback)
- ✅ CI/CD templates (GitHub Actions, GitLab CI)
- ✅ Test suite expanded to 73 tests (64 unit + 9 integration)

### v0.3.0 (Next Release)
- Macro expansion support
- LSP integration exploration
- Metrics dashboard

### v1.0.0 (Production Ready)
- All critical features implemented
- Comprehensive documentation
- Production-tested on 100k+ LOC
- LSP integration
- Editor plugins

---

**Last Updated:** 2025-12-27
**Maintainers:** COOLJAPAN OU (Team KitaSan)