# Rustfmt Configuration Guide
## Overview
This document defines the code formatting standards for the CallTrace project using rustfmt.
## rustfmt.toml Configuration
Create a `rustfmt.toml` file in the project root with the following configuration:
```toml
# Rust code formatting configuration for CallTrace
# https://rust-lang.github.io/rustfmt/
# Basic formatting
edition = "2021"
hard_tabs = false
tab_spaces = 4
newline_style = "Unix"
use_small_heuristics = "Default"
# Line width
max_width = 100
comment_width = 80
wrap_comments = true
# Imports
imports_granularity = "Crate"
imports_layout = "Mixed"
group_imports = "StdExternalCrate"
reorder_imports = true
reorder_modules = true
# Functions & impl blocks
fn_params_layout = "Tall"
fn_single_line = false
where_single_line = false
brace_style = "SameLineWhere"
# Structs & enums
struct_field_align_threshold = 20
enum_discrim_align_threshold = 20
use_field_init_shorthand = true
# Chains
chain_width = 60
use_try_shorthand = true
# Formatting
format_strings = false
format_macro_matchers = true
format_macro_bodies = true
hex_literal_case = "Lower"
# Comments
normalize_comments = true
normalize_doc_attributes = true
# Misc
inline_attribute_width = 0
blank_lines_upper_bound = 2
blank_lines_lower_bound = 0
remove_nested_parens = true
combine_control_expr = true
spaces_around_ranges = false
binop_separator = "Front"
# Skip formatting for specific items
skip_children = false
hide_parse_errors = false
error_on_line_overflow = false
error_on_unformatted = false
# Unstable features (comment out if using stable rustfmt)
# unstable_features = true
# format_code_in_doc_comments = true
# overflow_delimited_expr = true
# trailing_comma = "Vertical"
# condense_wildcard_suffixes = true
```
## Usage
### Manual Formatting
Run rustfmt on the entire project:
```bash
cargo fmt
```
Check formatting without making changes:
```bash
cargo fmt -- --check
```
Format a specific file:
```bash
rustfmt src/lib.rs
```
### CI Integration
Add to GitHub Actions workflow:
```yaml
- name: Check formatting
run: cargo fmt -- --check
```
### Pre-commit Hook
Create `.git/hooks/pre-commit`:
```bash
#!/bin/sh
# Check Rust formatting before commit
cargo fmt -- --check
if [ $? -ne 0 ]; then
echo "Please run 'cargo fmt' before committing"
exit 1
fi
```
## Style Guidelines
### 1. Import Organization
Imports are automatically grouped in this order:
1. Standard library imports
2. External crate imports
3. Local/crate imports
Example:
```rust
use std::collections::HashMap;
use std::sync::Arc;
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use crate::error::CallTraceError;
use crate::json_output::TraceSession;
```
### 2. Function Parameters
Long parameter lists are formatted vertically:
```rust
pub fn complex_function(
first_param: String,
second_param: u64,
third_param: Option<String>,
fourth_param: &[u8],
) -> Result<(), CallTraceError> {
// Implementation
}
```
### 3. Method Chains
Long chains are broken into multiple lines:
```rust
let result = some_collection
.iter()
.filter(|x| x.is_valid())
.map(|x| x.transform())
.collect::<Vec<_>>();
```
### 4. Struct Formatting
Fields are aligned when similar:
```rust
pub struct CallNode {
pub id: NodeId,
pub thread_id: ThreadId,
pub function: String,
pub address: u64,
pub call_site: u64,
pub start_time: u64,
pub end_time: Option<u64>,
}
```
### 5. Match Expressions
Consistent formatting for match arms:
```rust
match error {
CallTraceError::InitFailed => {
eprintln!("Initialization failed");
-1
}
CallTraceError::IOError(e) => {
eprintln!("IO Error: {}", e);
-2
}
_ => -99,
}
```
## Editor Integration
### VS Code
Add to `.vscode/settings.json`:
```json
{
"rust-analyzer.rustfmt.extraArgs": [
"+nightly"
],
"[rust]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "rust-lang.rust-analyzer"
}
}
```
### Vim/Neovim
Add to your config:
```vim
let g:rustfmt_autosave = 1
let g:rustfmt_command = "rustfmt"
```
### IntelliJ/CLion
1. Go to Settings → Languages & Frameworks → Rust → Rustfmt
2. Check "Run rustfmt on Save"
3. Set "Use rustfmt instead of built-in formatter"
## Exceptions
Files or sections that should not be formatted:
- Generated code
- Inline assembly blocks
- Certain macro definitions
Use attributes to skip formatting:
```rust
#[rustfmt::skip]
fn special_formatting() {
// Code with custom formatting
}
```
## Enforcement
1. **Local Development**: Developers should run `cargo fmt` before committing
2. **CI/CD**: GitHub Actions will check formatting on all PRs
3. **Pre-commit Hooks**: Optional but recommended for automatic checking
4. **Code Review**: Formatting issues should be addressed before merge
## Benefits
- **Consistency**: Uniform code style across the entire project
- **Reduced Bikeshedding**: No debates about formatting in code reviews
- **Better Diffs**: Consistent formatting leads to cleaner diffs
- **Focus on Logic**: Developers focus on code logic, not formatting
- **Tool Integration**: Works seamlessly with IDE and CI tools
## Troubleshooting
### Common Issues
1. **Different rustfmt versions**:
```bash
rustup component add rustfmt
rustup update
```
2. **Conflicts with save actions**:
- Disable other formatters for Rust files
- Ensure only rustfmt is active
3. **Parsing errors**:
- Check for syntax errors first
- Run `cargo check` before `cargo fmt`
## References
- [Rustfmt Configuration](https://rust-lang.github.io/rustfmt/)
- [Rust Style Guide](https://doc.rust-lang.org/1.0.0/style/)
- [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/)