### Render alignment guide with #rw:aligned examples Source: https://docs.rs/rulewright/latest/src/rulewright/llm.rs.html?search=u32+-%3E+bool Builds a documentation section explaining the `#rw:aligned` directive. Includes two code examples: one for aligning `=>` in a table-like block, and one for aligning tuple rows in an array. The second example uses `#[rustfmt::skip]` to preserve manual padding. ```rust // #rw:aligned Parser => "parser"; Formatter => "formatter"; Writer => "writer"; ``` ```rust #[rustfmt::skip] let cases = [ // #rw:aligned (SHORT, "first"), (LONG_NAME, "second"), ]; ``` -------------------------------- ### Render alignment guide with Doc builder chain Source: https://docs.rs/rulewright/latest/src/rulewright/llm.rs.html Builds a markdown guide section for alignment rules using a Doc builder. Includes code blocks for aligned table-like syntax and array/slice tuple examples, with notes on rustfmt interaction. ```rust fn render_alignment_guide(doc: Doc) -> Doc { doc.h2("Alignment guide") .blank() .line("`// #rw:aligned` is not a suppression. It opts the immediately following table-like block into `rust_aligned`:") .blank() .code_block( "rust", "// #rw:aligned\nParser => \"parser\";\nFormatter => \"formatter\";\nWriter => \"writer\";", ) .blank() .line("For blocks with at least two rows, Rulewright aligns `=>`, corresponding commas, and trailing `//` comments. The region ends at a blank line, a common closing delimiter, or another `#rw:` marker. Put the marker directly above the small block it describes; unmarked source is left alone.") .blank() .line("Array and slice tables can also keep each simple tuple on one line:") .blank() .code_block( "rust", "#[rustfmt::skip]\nlet cases = [\n // #rw:aligned\n (SHORT, \"first\"),\n (LONG_NAME, \"second\"),\n];", ) .blank() .line("`rulewright --fix` can add missing padding and collapse wrapped tuple rows when every field is a literal or path. Calls, blocks, nested tuples, and other expressions are reported without an automatic rewrite. Rustfmt removes manual column padding, so use `#[rustfmt::skip]` on the containing item when the layout must survive `cargo fmt`.") .blank() } ``` -------------------------------- ### Example Source: https://docs.rs/rulewright/latest/src/rulewright/lib.rs.html?search=std%3A%3Avec Example for a rule. Re-exported from registry. ```APIDOC ## Example ### Description Example for a rule. Re-exported from registry. ### Type `pub use registry::Example;` ### Usage Use this type to represent rule examples. The source does not provide further details on fields or methods. ``` -------------------------------- ### Rule examples: default_hasher rule test cases Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/performance/default_hasher.rs.html A list of example code snippets used to test the `default_hasher` rule. Each example has a label, code, and a `pass` flag indicating whether the rule should flag it. Failing examples use default SipHash hashers; passing examples use explicit hasher type parameters, fast-hasher crates, or non-hashing collections like BTreeMap. ```rust struct S { m: HashMap } ``` ```rust fn f(s: HashSet) { drop(s); } ``` ```rust fn f() { let mut m = std::collections::HashMap::new(); m.insert(1, 1); } ``` ```rust fn f() { let s: std::collections::HashSet = HashSet::with_capacity(8); drop(s); } ``` ```rust struct S { m: HashMap } ``` ```rust struct S { s: HashSet } ``` ```rust fn f(m: foldhash::HashMap) { drop(m); } ``` ```rust fn f() { let _m = HashMap::::new(); } ``` ```rust struct S { m: std::collections::BTreeMap } ``` ```rust #[cfg(test)] mod tests { fn t() { let _m: HashMap = HashMap::new(); } } ``` -------------------------------- ### Padding rule implementation with examples Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/style/padding.rs.html?search=u32+-%3E+bool Defines the padding rule constants and a list of examples with pass/fail expectations. Each example includes a label, code, and pass flag. ```rust #[cfg(test)] use googletest::prelude::*; use ra_ap_syntax::{AstNode, SyntaxNode, SyntaxToken, ast, syntax_editor::SyntaxEditor}; use crate::{AstCtx, Example, Violation}; use super::support::{gap_before_attached_comment, has_blank_line}; const CONTROL_FLOW: &str = "control-flow"; const FUNCTIONS: &str = "functions"; const LET_RUNS: &str = "let-runs"; const RETURNS: &str = "returns"; const TAIL_EXPRESSIONS: &str = "tail-expressions"; pub(crate) const VALID_BOUNDARIES: &[&str] = &[FUNCTIONS, CONTROL_FLOW, LET_RUNS, RETURNS, TAIL_EXPRESSIONS]; #[rustfmt::skip] const EXAMPLES: &[Example] = &[ Example { label: "return has padding", code: "fn value(flag: bool) -> usize {\n let value = 1;\n\n return value;\n}", pass: true, }, Example { label: "return needs padding", code: "fn value() -> usize {\n let value = 1;\n return value;\n}", pass: false, }, Example { label: "first return is exempt", code: "fn value() -> usize {\n return 1;\n}", pass: true, }, Example { label: "tail expression has padding", code: "fn value() -> usize {\n let value = 1;\n\n value\n}", pass: true, }, Example { label: "tail expression needs padding", code: "fn value() -> usize {\n let value = 1;\n value\n}", pass: false, }, Example { label: "effect followed by tail expression stays compact", code: "fn value() -> Result<(), Error> {\n verify_state()?;\n finish()\n}", pass: true, }, Example { label: "let run needs following padding", code: "fn run() {\n let one = 1;\n let two = 2;\n consume(one, two);\n}", pass: false, }, Example { label: "let run followed by padding", code: "fn run() {\n let one = 1;\n let two = 2;\n\n consume(one, two);\n}", pass: true, }, Example { label: "multiline control expression is padded", code: "fn run(flag: bool) {\n prepare();\n\n if flag {\n work();\n }\n\n finish();\n}", pass: true, }, Example { label: "multiline control expression needs padding before and after", code: "fn run(flag: bool) {\n prepare();\n if flag {\n work();\n }\n finish();\n}", pass: false, }, Example { label: "let after multiline guard needs padding", code: "fn inspect(path: &Path) {\n if path.is_dir() {\n return;\n }\n let manifest = path.join(\"Cargo.toml\");\n}", pass: false, }, Example { label: "compact guard needs following padding", code: "fn inspect(path: &Path) {\n if path.is_dir() { return; }\n observe(path);\n}", pass: false, }, Example { label: "compact consecutive guards need padding", code: "fn validate(one: bool, two: bool) {\n if one { return; }\n if two { return; }\n}", pass: false, }, Example { label: "adjacent free functions need padding", code: "fn one() {}\nfn two() {}", pass: false, }, Example { label: "separated free functions", code: "fn one() {}\n\nfn two() {}", pass: true, }, Example { label: "adjacent methods need padding", code: "impl Value {\n fn one() {}\n fn two() {}\n}", pass: false, }, Example { label: "adjacent trait methods need padding", code: "trait Value {\n fn one();\n fn two();\n}", pass: false, }, Example { label: "else-if remains one control-flow chain", code: "fn choose(one: bool, two: bool) {\n if one { work(); } else if two { work(); }\n}", pass: true, }, Example { label: "first and last multiline controls need only interior padding", code: "fn run(flag: bool) {\n if flag {\n work();\n }\n\n loop {\n break;\n }\n}", pass: true, }, Example { label: "block-like control expression separates let runs", code: "fn run(mut bits: u32) {\n while bits != 0 {\n let index = bits.trailing_zeros();\n\n if index > 10 {\n observe(index);\n }\n\n bits &= bits - 1;\n }\n}", pass: true, }, Example { label: "single-expression closure is exempt", code: "fn run() {\n consume(|| { 1 });\n}", pass: true, }, ] ``` -------------------------------- ### Test: examples() Source: https://docs.rs/rulewright/latest/src/rulewright/languages/toml/rules/cargo/edition.rs.html?search=std%3A%3Avec Runs all test cases from the `EXAMPLES` constant, checking each against the rule. Determines the file path based on whether the code contains `[workspace`. ```rust #[gtest] fn examples() -> Result<()> { for example in EXAMPLES { let rel = if example.code.contains("[workspace") { "Cargo.toml" } else { "nested/foo/Cargo.toml" }; let violations = crate::test_support::check_source_toml_at( rel, example.code, check_toml_cargo_edition, ); verify_eq!(violations.is_empty(), example.pass)?; } Ok(()) } ``` -------------------------------- ### Get field positions after commas Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/style/aligned.rs.html?search= Computes the starting positions of fields after commas, skipping empty fields and line comments. Uses comma_positions and filters out fields that are empty or start with //. ```rust fn field_positions(line: &str) -> Vec { comma_positions(line) .into_iter() .filter_map(|comma| { let remaining = line.get(comma + 1..)?; let leading = remaining.len() - remaining.trim_start().len(); let field = remaining.trim_start(); (!field.is_empty() && !field.starts_with("//")).then_some(comma + 1 + leading) }) .collect() } ``` -------------------------------- ### handle_init function Source: https://docs.rs/rulewright/latest/src/rulewright/cli.rs.html?search=u32+-%3E+bool Creates a config file with registry defaults, handling success, already-exists, and other errors. ```rust fn handle_init(registry: &RuleRegistry, config_path: &Path) -> ExitCode { let metadata = registry.metadata(); let config = Config::generate_registry_default(&metadata); match atomic::create(config_path, config.to_toml_string()) { Ok(()) => { output::success(&format!( "created {} with {} rules enabled", config_path.display(), metadata.len() )); ExitCode::SUCCESS } Err(error) if error.is_already_exists() => { output::error(&format!("{} already exists", config_path.display())); ExitCode::FAILURE } Err(error) => { output::error(&format!( "failed to create {}: {error}", config_path.display() )); ExitCode::FAILURE } } } ``` -------------------------------- ### Padding rule examples for returns, tail expressions, let runs, and control flow Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/style/padding.rs.html?search= Rust examples from the padding rule's EXAMPLES table, each with a label and pass/fail expectation. They cover padding around returns, tail expressions, let runs, multiline control flow, compact guards, adjacent functions/methods/trait methods, else-if chains, block-like control expressions, and single-expression closures. ```rust fn value(flag: bool) -> usize { let value = 1; return value; } ``` ```rust fn value() -> usize { let value = 1; return value; } ``` ```rust fn value() -> usize { return 1; } ``` ```rust fn value() -> usize { let value = 1; value } ``` ```rust fn value() -> usize { let value = 1; value } ``` ```rust fn value() -> Result<(), Error> { verify_state()?; finish() } ``` ```rust fn run() { let one = 1; let two = 2; consume(one, two); } ``` ```rust fn run() { let one = 1; let two = 2; consume(one, two); } ``` ```rust fn run(flag: bool) { prepare(); if flag { work(); } finish(); } ``` ```rust fn run(flag: bool) { prepare(); if flag { work(); } finish(); } ``` ```rust fn inspect(path: &Path) { if path.is_dir() { return; } let manifest = path.join("Cargo.toml"); } ``` ```rust fn inspect(path: &Path) { if path.is_dir() { return; } observe(path); } ``` ```rust fn validate(one: bool, two: bool) { if one { return; } if two { return; } } ``` ```rust fn one() {} fn two() {} ``` ```rust fn one() {} fn two() {} ``` ```rust impl Value { fn one() {} fn two() {} } ``` ```rust trait Value { fn one(); fn two(); } ``` ```rust fn choose(one: bool, two: bool) { if one { work(); } else if two { work(); } } ``` ```rust fn run(flag: bool) { if flag { work(); } loop { break; } } ``` ```rust fn run(mut bits: u32) { while bits != 0 { let index = bits.trailing_zeros(); if index > 10 { observe(index); } bits &= bits - 1; } } ``` ```rust fn run() { consume(|| { 1 }); } ``` -------------------------------- ### Rust: tests for build_rs_external_tool rule Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/safety/build_rs_external_tool.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Test module that runs the lint rule against example code in build.rs and non-build.rs files. It verifies that violations are produced only in build.rs and that -sys crates get the specific 'external build system' message. ```rust // The default test rel would defeat the build.rs gate, so examples run through the // rel-aware helper instead of `example_tests!`. #[cfg(test)] mod tests { use super::*; const BUILD_RS_REL: &str = "crates/mylib/build.rs"; fn run_at(rel: &str, source: &str) -> Vec { crate::test_support::check_source_ast_at(rel, source, check_build_rs_external_tool) } #[gtest] fn examples() -> Result<()> { for ex in EXAMPLES { let violations = run_at(BUILD_RS_REL, ex.code); verify_eq!(violations.is_empty(), ex.pass)?; } Ok(()) } #[gtest] fn non_build_rs_files_are_exempt() -> Result<()> { for ex in EXAMPLES { let violations = run_at("crates/mylib/src/lib.rs", ex.code); verify_true!(violations.is_empty())?; } Ok(()) } #[gtest] fn sys_crate_build_system_gets_sys_message() -> Result<()> { let violations = run_at( "crates/foo-sys/build.rs", "fn main() { let _ = std::process::Command::new(\"make\").status(); }", ); verify_eq!(violations.len(), 1)?; verify_true!(violations[0].message.contains("external build system"))?; Ok(()) } } ``` -------------------------------- ### Rust hardcoded URL detection rule with helper functions Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/safety/hardcoded_url.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Rust source code for a rulewright rule that detects hardcoded URLs. It includes helper functions to check if a string starts with a URL authority, if a method call is a string pattern match, and if a macro call contains a URL value. The rule is tested with example tests. ```rust .filter_map(|call| call.name_ref()) .any(|name| name.text() == "get_or") } fn starts_with_url_authority(value: &str) -> bool { ["https://", "http://"].iter().any(|scheme| { value .strip_prefix(scheme) .and_then(|rest| rest.chars().next()) .is_some_and(|first| !first.is_whitespace()) }) } fn is_string_match_pattern(literal: &ast::Literal) -> bool { literal .syntax() .ancestors() .find_map(ast::ArgList::cast) .and_then(|arguments| arguments.syntax().parent()) .and_then(ast::MethodCallExpr::cast) .and_then(|call| call.name_ref()) .is_some_and(|name| { matches!( name.text().as_str(), "contains" | "ends_with" | "starts_with" | "strip_prefix" | "strip_suffix" | "trim_end_matches" | "trim_start_matches" ) }) } fn macro_has_url_value(call: &ast::MacroCall) -> bool { call.token_tree().is_some_and(|tokens| { tokens .syntax() .descendants_with_tokens() .filter_map(NodeOrToken::into_token) .filter(|token| token.kind() == SyntaxKind::STRING) .any(|token| { string_token_value(token.text()) .is_some_and(|value| starts_with_url_authority(value.trim_start())) }) }) } fn string_token_value(token: &str) -> Option<&str> { let first_quote = token.find('"')?; let last_quote = token.rfind('"')?; if first_quote >= last_quote { return None; } token.get(first_quote + 1..last_quote) } crate::rulewright_ast_test!(check_hardcoded_url, { crate::example_tests!(EXAMPLES, check_hardcoded_url); }); ``` -------------------------------- ### CLI entry point: main and run_args (Rust) Source: https://docs.rs/rulewright/latest/src/rulewright/cli.rs.html?search= The main function parses arguments and delegates to run_args. run_args performs several validations for incompatible analysis options and unknown rule filters, then prints a banner unless quiet or llm mode is active, or a non-human format is selected. It handles various CLI commands like --list, --detail, --init, --clean, --llm, --suppressions, and defaults to running the analysis. ```rust 141 run_args(&Args::parse(), registry) 142} 143 144fn run_args(args: &Args, registry: &RuleRegistry) -> ExitCode { 145 if let Some(error) = incompatible_analysis_options(args) { 146 output::error(error); 147 148 return ExitCode::FAILURE; 149 } 150 151 if let Some(name) = unknown_rule_filter(registry, &args.rule) { 152 output::error(&format!("unknown rule: {name}")); 153 154 return ExitCode::FAILURE; 155 } 156 157 if !args.quiet 158 && !args.llm 159 && args.parse_config.is_none() 160 && args.format == FindingsFormat::Human 161 { 162 output::banner("Rulewright", env!("CARGO_PKG_VERSION")); 163 } 164 165 if args.list { 166 print_rule_list(registry); 167 168 return ExitCode::SUCCESS; 169 } 170 171 if let Some(config_path) = &args.parse_config { 172 return print_parsed_config(registry, config_path, args.strict); 173 } 174 175 if let Some(rule_name) = &args.detail { 176 return print_rule_detail(registry, rule_name); 177 } 178 179 let initial_directory = match std::env::current_dir() { 180 Ok(path) => path, 181 182 Err(error) => { 183 output::error(&format!("failed to resolve the current directory: {error}")); 184 185 return ExitCode::FAILURE; 186 } 187 }; 188 let project = match discover_project(args, &initial_directory) { 189 Ok(project) => project, 190 191 Err(error) => { 192 output::error(&error); 193 return ExitCode::FAILURE; 194 } 195 }; 196 let config_path = args.config.as_ref().map_or_else( 197 || project.root.join("rulewright.toml"), |path| PathBuf::from(resolve_relative(path, &initial_directory)), ); 198 199 if args.init { 200 return handle_init(registry, &config_path); 201 } 202 203 let config = match load_and_validate_config(registry, &config_path, args.strict) { 204 Ok(config) => config, 205 Err(code) => return code, 206 }; 207 let member_roots = match resolve_filters(&project, &args.filter) { 208 Ok(filters) => filters, 209 Err(error) => { 210 output::error(&error); 211 212 return ExitCode::FAILURE; 213 } 214 }; 215 let packages = workspace_packages(&project); 216 let run_ctx = runner::RunCtx { 217 registry, 218 rule_filter: &args.rule, 219 package_filter: &member_roots, 220 packages: &packages, 221 config: &config, 222 root: &project.root, 223 workspace_root: &project.root, 224 quiet: args.quiet, 225 dirty: args.dirty, 226 }; 227 228 if matches!(&args.command, Some(RulewrightCommand::Clean)) { 229 return runner::clean_suppressions(&run_ctx, args.dry_run); 230 } 231 232 if args.llm { 233 return llm::print(&run_ctx); 234 } 235 236 if args.suppressions { 237 return runner::report_suppressions( 238 registry, 239 &member_roots, 240 &config, 241 &project.root, 242 &project.root, 243 args.quiet, 244 ); 245 } 246 247 let failed = analysis_failed(args, &run_ctx, &initial_directory); 248 249 if failed { 250 ExitCode::FAILURE 251 } else { 252 ExitCode::SUCCESS 253 } 254} 255fn analysis_failed( 256 args: &Args, 257 run_ctx: &runner::RunCtx<'_>, 258 initial_directory: &std::path::Path, ) -> bool { 259 let fix_mode = match (args.fix, args.dry_run) { 260 (true, true) => runner::FixMode::DryRun, 261 (true, false) => runner::FixMode::Apply, 262 (false, _) => runner::FixMode::Off, 263 }; 264 let report_format = match args.format { 265 FindingsFormat::Human => runner::ReportFormat::Human, 266 FindingsFormat::Json => runner::ReportFormat::Json, 267 }; 268 let baseline_path = args 269 .baseline 270 .as_ref() 271 .map(|path| PathBuf::from(resolve_relative(path, initial_directory))); 272 let write_baseline_path = args 273 .write_baseline 274 .as_ref() 275 .map(|f| PathBuf::from(resolve_relative(path, initial_directory))); let mut failed = !runner::run( run_ctx, fix_mode, report_format, baseline_path.as_deref(), write_baseline_path.as_deref(), ); if args.ci { failed |= !run_cargo_check("fmt", &["fmt", "--all", "--", "--check"], run_ctx.root); let clippy_target = runner::cargo_target_dir(run_ctx.root, run_ctx.root).join("rulewright-clippy"); failed |= !run_cargo_check_with_environment( "clippy", &[ "clippy", "--workspace", "--all-targets", "--", "-D", "warnings", ], ``` -------------------------------- ### allow_reason rule examples Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/hygiene/allow_reason.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Examples of `#[allow]` and `#[expect]` attributes with and without reasons or comments, showing which pass or fail the rule. ```rust #[allow(dead_code)] ``` ```rust #[allow(dead_code)] // webhook response fields ``` ```rust // DBC fields use PascalCase #[allow(non_snake_case)] ``` ```rust #[allow(dead_code, reason = "webhook response fields")] ``` ```rust #[expect(clippy::unused_async)] ``` ```rust #[expect(clippy::unused_async, reason = "API fixed, will use I/O later")] ``` ```rust #[allow( dead_code, reason = "webhook response fields", )] ``` ```rust #[expect( clippy::cast_precision_loss, reason = "sample count enters the f64 domain", )] ``` ```rust #![expect( clippy::doc_markdown, reason = "generated documentation is external", )] ``` ```rust #[expect( clippy::cast_precision_loss, clippy::cast_sign_loss, )] ``` ```rust #![allow(clippy::too_many_arguments)] ``` ```rust // compatibility callback has many parameters by design #![allow(clippy::too_many_arguments)] ``` ```rust #[derive(Debug)] ``` ```rust #[deny(unused)] ``` -------------------------------- ### Rust rulewright rule for TODO/FIXME/HACK/XXX comments Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/hygiene/todo.rs.html?search= Defines the rulewright rule 'todo' that flags bare TODO, FIXME, HACK, and XXX comments without parenthesized context. The rule uses the crate's line_rule! macro and includes example test cases. It checks each line for comment starts and keyword suffixes, skipping keywords followed by '('. ```rust 1use crate::{Example, FileCtx, Violation, infra::parse, violation}; 2 3#[rustfmt::skip] 4const EXAMPLES: &[Example] = &[ 5 Example { 6 label: "bare TODO", 7 code: "// TODO: fix this later", 8 pass: false, 9 }, 10 Example { 11 label: "tracked TODO", 12 code: "// TODO(#123) fix this", 13 pass: true, 14 }, 15 Example { 16 label: "bare FIXME", 17 code: "// FIXME this is broken", 18 pass: false, 19 }, 20 Example { 21 label: "bare HACK", 22 code: "// HACK: workaround", 23 pass: false, 24 }, 25 Example { 26 label: "bare XXX", 27 code: "// XXX", 28 pass: false, 29 }, 30 Example { 31 label: "no comment", 32 code: "let todo = 5;", 33 pass: true, 34 }, 35 Example { 36 label: "inline TODO", 37 code: "let x = 1; // TODO fix", 38 pass: false, 39 }, 40 Example { 41 label: "tracked FIXME", 42 code: "// FIXME(perf regression in v2)", 43 pass: true, 44 }, 45]; 46 47crate::line_rule!( 48 todo, 49 "Require TODO/FIXME/HACK/XXX to have parenthesized context.", 50 "A bare TODO becomes permanent because nobody knows the intended follow-up. Add a real issue, owner, constraint, or removal condition in parentheses; do not invent placeholder metadata just to satisfy the syntax.", 51); 52 53const BANNED: &[&str] = &["TODO", "FIXME", "HACK", "XXX"]; 54 55fn check_todo(ctx: &FileCtx<'_>) -> Vec { 56 let mut out = Vec::new(); 57 58 for (i, line) in ctx.lines.iter().enumerate() { 59 let Some(comment) = parse::find_comment_start(line) else { 60 continue; 61 }; 62 63 for keyword in BANNED { 64 if let Some(after) = parse::find_keyword_suffix(comment, keyword) { 65 if parse::matches(after, '(') { 66 continue; 67 } 68 69 out.push(violation( 70 ctx.rel, 71 i + 1, 72 format!( 73 "{keyword} without tracking context \ 74 (use {keyword}(#issue) or {keyword}(reason))" 75 ), 76 )); 77 } 78 } 79 } 80 81 out 82} 83 84crate::rulewright_test!(check_todo, { 85 crate::example_tests!(EXAMPLES, check_todo); 86}); ``` -------------------------------- ### Define empty example fixture rule Source: https://docs.rs/rulewright/latest/src/rulewright/registry.rs.html?search= Defines a Rust line rule fixture with empty examples. The rule info notes that examples need labels and source to be useful. Used for testing validation of example content. ```rust static EMPTY_EXAMPLE_RULES: &[Rule] = &[Rule::rust_line( RuleInfo::new( "fixture_empty_example", "Empty example fixture.", "Examples need labels and source to be useful.", Severity::Low, EMPTY_EXAMPLES, &[], ), no_violations, None, )]; ``` -------------------------------- ### Example: re-export from local out-of-line module Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/interop/foreign_reexports.rs.html?search=std%3A%3Avec Passing example: `pub mod infra; pub use infra::Config;` re-exports from a local out-of-line module, which is allowed. ```rust pub mod infra; pub use infra::Config; ``` -------------------------------- ### Rule definition and test examples Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/performance/large_async_local.rs.html Defines the rust_rule_style and test examples for the 'large_async_local' rule in Rust. The examples cover large and small arrays in async functions, async blocks, and sync closures. Each example includes a label, code, and pass/fail flag. ```rust use ra_ap_syntax::ast; use super::support; use crate::{AstCtx, Example, Violation}; #[rustfmt::skip] const EXAMPLES: &[Example] = &[ Example { label: "large repeat-literal array in async fn", code: "async fn f() { let buf = [0u8; 2048]; consume(&buf).await; }", pass: false, }, Example { label: "large annotated array local in async fn", code: "async fn f() { let buf: [u64; 512] = [0; 512]; consume(&buf).await; }", pass: false, }, Example { label: "large by-value array parameter on async fn", code: "async fn f(buf: [u8; 4096]) { consume(&buf).await; }", pass: false, }, Example { label: "large array local in async block", code: "fn g() { let _fut = async { let buf = [0u8; 2048]; consume(&buf).await; }; }", pass: false, }, Example { label: "small array local in async fn", code: "async fn f() { let buf = [0u8; 128]; consume(&buf).await; }", pass: true, }, Example { label: "sync fn is rust_large_stack_array territory", code: "fn f() { let _buf = [0u8; 4096]; }", pass: true, }, Example { label: "array behind a reference parameter", code: "async fn f(buf: &[u8; 4096]) { consume(buf).await; }", pass: true, }, Example { label: "large array inside sync closure in async fn", code: "async fn f() { let g = || { let _buf = [0u8; 4096]; }; g(); }", pass: true, }, Example { label: "large async local in test module", code: "#[cfg(test)]\nmod tests {\n async fn t() { let _buf = [0u8; 2048]; }\n}", pass: true, }, ]; crate::ast_rule!( large_async_local, "Flag by-value `[T; N]` locals and parameters over threshold bytes inside async fns and blocks.", "Async locals and parameters embed in the future's state machine, inflating every task and spawn memcpy.", Medium, params { threshold: i64 = 1024 }, ); ``` -------------------------------- ### Example test cases for first_doc_sentence rule Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/docs/first_doc_sentence.rs.html?search=u32+-%3E+bool A set of pass/fail examples for the `example_tests!` macro, covering various scenarios like short summaries, long summaries, line spills, inner docs, code fences, and more. ```rust use crate::{Example, FileCtx, Violation, infra::parse, violation}; /// Pass/fail cases for `example_tests!`. #[rustfmt::skip] const EXAMPLES: &[Example] = &[ Example { label: "short first sentence", code: "/// Returns the parsed value.\nfn f() {}", pass: true, }, Example { label: "first sentence over the word budget", code: "/// This extremely long summary sentence keeps going and going with far too many words to fit the budget.", pass: false, }, Example { label: "first sentence spills onto the next line", code: "/// This summary continues\n/// onto the next line.", pass: false, }, Example { label: "long detail after a short summary", code: "/// Short summary.\n///\n/// Detail sentences after the summary can be as long as they want to be without limits.", pass: true, }, Example { label: "inner doc short summary", code: "//! Module docs are covered.", pass: true, }, Example { label: "inner doc summary spills", code: "//! Module summary that drifts\n//! across lines.", pass: false, }, Example { label: "single line without terminator stays in budget", code: "/// Returns `None`", pass: true, }, Example { label: "sentence ends before a code fence", code: "/// Sums things.\n/// ```\n/// let total = sum(items). More words inside fences never matter at all here\n/// ```", pass: true, }, Example { label: "heading-only block is skipped", code: "/// # Safety", pass: true, }, Example { label: "plain comments can ramble", code: "// this is not a doc comment so it can ramble on forever without any punctuation at all", pass: true, }, Example { label: "empty first doc line delays the summary", code: "///\n/// The summary arrives too late here.", pass: false, }, Example { label: "dotted names are not sentence ends", code: "/// Parses `foo.bar` fields quickly.", pass: true, }, ]; crate::line_rule!( first_doc_sentence, "Require the first doc sentence to end on the first line within a word budget.", "The first sentence becomes the rustdoc summary; long or spilling summaries break skimmable docs.", Low, params { max_words: i64 = 15 }, ); fn check_first_doc_sentence(ctx: &FileCtx<'_>) -> Vec { let max_words = ctx .config .get_usize("rust_first_doc_sentence", &FIRST_DOC_SENTENCE_PARAMS[0]); let mut out = Vec::new(); for block in doc_blocks(ctx.lines) { check_block(ctx, &block, max_words, &mut out); } out } struct DocBlock<'a> { start_line: usize, lines: Vec<&'a str>, } fn doc_blocks<'a>(lines: &[&'a str]) -> Vec> { let mut blocks = Vec::new(); let mut current: Option> = None; let mut in_fence = false; for (i, line) in lines.iter().enumerate() { if let Some(raw) = parse::doc_comment_content(line.trim()) { let text = raw.trim(); let block = current.get_or_insert_with(|| DocBlock { start_line: i + 1, lines: Vec::new(), }); if parse::matches(text, "```") { in_fence = !in_fence; continue; } if !in_fence { block.lines.push(text); } } else { if let Some(block) = current.take() { blocks.push(block); } in_fence = false; } } if let Some(block) = current.take() { blocks.push(block); } blocks } fn check_block( ctx: &FileCtx<'_>, block: &DocBlock<'_>, max_words: usize, out: &mut Vec, ) { let Some(first) = block.lines.first().copied() else { return; }; if first.is_empty() { if block.lines.iter().any(|line| !line.is_empty()) { out.push(violation( ctx.rel, block.start_line, "first doc sentence must start on the block's first line", )); } return; } if parse::matches(first, '#') { return; } let continues = block.lines.get(1).is_some_and(|line| !line.is_empty()); ``` -------------------------------- ### Example: pub use of std item Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/interop/foreign_reexports.rs.html?search=std%3A%3Avec Passing example: `pub use std::fmt::Debug;` re-exports a standard library item, which is allowed. ```rust pub use std::fmt::Debug; ``` -------------------------------- ### Rust test macro invocation for magic numbers examples Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/style/magic_numbers.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Invokes the rulewright_ast_test! macro to run example tests for the magic numbers rule using the EXAMPLES constant. ```rust crate::rulewright_ast_test!(check_magic_numbers, { crate::example_tests!(EXAMPLES, check_magic_numbers); }); ``` -------------------------------- ### Define EXAMPLES for nested_smart_pointers rule tests Source: https://docs.rs/rulewright/latest/src/rulewright/languages/rust/rules/performance/nested_smart_pointers.rs.html?search= The `EXAMPLES` array lists labeled test cases for the lint. Each `Example` specifies a snippet of Rust code and whether it should pass or fail; these drive the `example_tests!` harness in the test at the bottom. The failing cases cover nested heap pointers like `Arc>`, `Box>`, `Rc>`, plus `Arc>` and `Arc`; passing cases cover `Arc>`, `Box`, the flattened goal forms, `Box>` (left to `rust_box_vec`), and nested pointers inside a `#[cfg(test)]` module. ```rust use ra_ap_syntax::ast; use crate::{AstCtx, Example, Violation}; use super::support::type_arg_last_ident; #[rustfmt::skip] const EXAMPLES: &[Example] = &[ Example { label: "Arc> field", code: "struct S { a: Arc> }", pass: false, }, Example { label: "Box> parameter", code: "fn f(x: Box>) { drop(x); }", pass: false, }, Example { label: "Rc> type alias", code: "type T = Rc>;", pass: false, }, Example { label: "Arc> suggests Arc<[T]>", code: "struct S { d: Arc> }", pass: false, }, Example { label: "Arc suggests Arc", code: "struct S { n: Arc }", pass: false, }, Example { label: "Arc> is a single heap layer", code: "struct S { m: Arc> }", pass: true, }, Example { label: "Box is fine", code: "struct S { cb: Box }", pass: true, }, Example { label: "Arc<[T]> and Arc are the goal state", code: "fn f(b: Arc<[u8]>, s: Arc) { drop(b); drop(s); }", pass: true, }, Example { label: "Box> is owned by rust_box_vec, not this rule", code: "fn f() { let _x: Box> = Box::new(Vec::new()); }", pass: true, }, Example { label: "nested pointers in test module", code: "#[cfg(test)]\nmod tests {\n struct S { a: Arc> }\n}", pass: true, }, ]; crate::ast_rule!( nested_smart_pointers, "Flag directly nested heap pointers (`Arc>`, `Rc>`, ...) plus `Arc>`/`Arc`.", "Each nesting layer is another sequential DRAM lookup on access — flatten to one allocation (Arc<[T]>, Arc).", Medium, ); ```