dart-decimate 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/Cargo.lock +572 -0
  2. package/Cargo.toml +41 -0
  3. package/LICENSE +21 -0
  4. package/README.md +617 -0
  5. package/assets/dart-decimate-banner.png +0 -0
  6. package/npm/bin/dart-decimate-mcp.js +48 -0
  7. package/npm/bin/dart-decimate.js +48 -0
  8. package/npm/scripts/postinstall.js +46 -0
  9. package/npm/scripts/test-npx-local.js +54 -0
  10. package/npm/scripts/test-npx-mcp-local.js +56 -0
  11. package/package.json +45 -0
  12. package/src/baseline.rs +643 -0
  13. package/src/bin/dart-decimate-mcp.rs +11 -0
  14. package/src/boundaries/tests.rs +60 -0
  15. package/src/boundaries.rs +317 -0
  16. package/src/changed_scope.rs +117 -0
  17. package/src/ci_template.rs +399 -0
  18. package/src/cli/analyze.rs +462 -0
  19. package/src/cli/analyzer_options.rs +82 -0
  20. package/src/cli/audit_run.rs +327 -0
  21. package/src/cli/boundary_args.rs +44 -0
  22. package/src/cli/ci_template_run.rs +196 -0
  23. package/src/cli/command_name.rs +20 -0
  24. package/src/cli/common_args.rs +167 -0
  25. package/src/cli/config_run.rs +78 -0
  26. package/src/cli/coverage_run.rs +393 -0
  27. package/src/cli/decision_surface_run.rs +99 -0
  28. package/src/cli/default_command.rs +69 -0
  29. package/src/cli/dupes_args.rs +150 -0
  30. package/src/cli/entry_points.rs +121 -0
  31. package/src/cli/error.rs +149 -0
  32. package/src/cli/error_output.rs +68 -0
  33. package/src/cli/explain_run.rs +72 -0
  34. package/src/cli/fix_run.rs +162 -0
  35. package/src/cli/flags_args.rs +23 -0
  36. package/src/cli/health_args.rs +200 -0
  37. package/src/cli/hooks_run.rs +191 -0
  38. package/src/cli/impact_run.rs +95 -0
  39. package/src/cli/init_run.rs +49 -0
  40. package/src/cli/inspect_args.rs +20 -0
  41. package/src/cli/inspect_run.rs +66 -0
  42. package/src/cli/issue_filter_args.rs +240 -0
  43. package/src/cli/list_run.rs +311 -0
  44. package/src/cli/mode_args.rs +72 -0
  45. package/src/cli/output_format.rs +62 -0
  46. package/src/cli/regression_args.rs +156 -0
  47. package/src/cli/request_args.rs +175 -0
  48. package/src/cli/schema_commands.rs +72 -0
  49. package/src/cli/scope_args.rs +174 -0
  50. package/src/cli/security_args.rs +175 -0
  51. package/src/cli/security_gate_run.rs +66 -0
  52. package/src/cli/security_summary_run.rs +43 -0
  53. package/src/cli/summary_args.rs +12 -0
  54. package/src/cli/tests.rs +516 -0
  55. package/src/cli/trace_args.rs +67 -0
  56. package/src/cli/trace_run.rs +131 -0
  57. package/src/cli/trace_tests.rs +235 -0
  58. package/src/cli/unsupported_run.rs +116 -0
  59. package/src/cli/watch_run.rs +153 -0
  60. package/src/cli.rs +603 -0
  61. package/src/config/boundary_config.rs +235 -0
  62. package/src/config/cache.rs +25 -0
  63. package/src/config/dependencies.rs +114 -0
  64. package/src/config/health.rs +237 -0
  65. package/src/config/jsonc.rs +66 -0
  66. package/src/config/policy.rs +91 -0
  67. package/src/config/rule_aliases.rs +487 -0
  68. package/src/config/rules.rs +339 -0
  69. package/src/config.rs +635 -0
  70. package/src/coverage.rs +469 -0
  71. package/src/dart_parser.rs +673 -0
  72. package/src/decision_surface.rs +405 -0
  73. package/src/dependencies/analyze.rs +218 -0
  74. package/src/dependencies/codegen.rs +118 -0
  75. package/src/dependencies/discovery.rs +60 -0
  76. package/src/dependencies/overrides.rs +76 -0
  77. package/src/dependencies/private_src_imports.rs +32 -0
  78. package/src/dependencies/pubspec_document.rs +86 -0
  79. package/src/dependencies/pubspec_entry.rs +96 -0
  80. package/src/dependencies/tests.rs +544 -0
  81. package/src/dependencies/usage.rs +33 -0
  82. package/src/dependencies.rs +553 -0
  83. package/src/dependency_scripts.rs +91 -0
  84. package/src/dupes/lex.rs +236 -0
  85. package/src/dupes/tests.rs +119 -0
  86. package/src/dupes.rs +625 -0
  87. package/src/explain.rs +692 -0
  88. package/src/extract/directives.rs +252 -0
  89. package/src/extract/error_tests.rs +25 -0
  90. package/src/extract/members.rs +210 -0
  91. package/src/extract/primary_constructors.rs +421 -0
  92. package/src/extract/references.rs +151 -0
  93. package/src/extract/routes.rs +691 -0
  94. package/src/extract/signatures.rs +266 -0
  95. package/src/extract/string_tests.rs +18 -0
  96. package/src/extract/strings.rs +107 -0
  97. package/src/extract/tests.rs +697 -0
  98. package/src/extract.rs +680 -0
  99. package/src/feature_flags/tests.rs +76 -0
  100. package/src/feature_flags.rs +453 -0
  101. package/src/finding_identity.rs +60 -0
  102. package/src/fix.rs +551 -0
  103. package/src/generated.rs +53 -0
  104. package/src/graph/augment_tests.rs +212 -0
  105. package/src/graph/conditionals.rs +74 -0
  106. package/src/graph/package_config_tests.rs +100 -0
  107. package/src/graph/parts.rs +248 -0
  108. package/src/graph/pubspec_tests.rs +119 -0
  109. package/src/graph/tests.rs +837 -0
  110. package/src/graph/uri_tests.rs +102 -0
  111. package/src/graph.rs +644 -0
  112. package/src/health/coverage.rs +309 -0
  113. package/src/health/ownership.rs +175 -0
  114. package/src/health/runtime_coverage.rs +616 -0
  115. package/src/health/runtime_intelligence.rs +511 -0
  116. package/src/health/scores.rs +296 -0
  117. package/src/health/tests.rs +240 -0
  118. package/src/health/threshold_types.rs +163 -0
  119. package/src/health/thresholds.rs +229 -0
  120. package/src/health/types.rs +636 -0
  121. package/src/health.rs +597 -0
  122. package/src/hooks/agent_settings.rs +175 -0
  123. package/src/hooks/templates.rs +51 -0
  124. package/src/hooks.rs +569 -0
  125. package/src/impact.rs +287 -0
  126. package/src/init.rs +237 -0
  127. package/src/inspect.rs +142 -0
  128. package/src/intelligence/tests.rs +232 -0
  129. package/src/intelligence.rs +305 -0
  130. package/src/lib.rs +198 -0
  131. package/src/main.rs +5 -0
  132. package/src/manifest/mcp.rs +565 -0
  133. package/src/manifest.rs +552 -0
  134. package/src/mcp/cli_args/value_args.rs +175 -0
  135. package/src/mcp/cli_args.rs +658 -0
  136. package/src/mcp/cli_args_tests.rs +522 -0
  137. package/src/mcp/code_execute.rs +671 -0
  138. package/src/mcp/tools.rs +660 -0
  139. package/src/mcp.rs +325 -0
  140. package/src/output/audit_risk.rs +135 -0
  141. package/src/output/dependency_findings.rs +327 -0
  142. package/src/output/duplication_findings.rs +114 -0
  143. package/src/output/feature_flag_findings.rs +122 -0
  144. package/src/output/format.rs +31 -0
  145. package/src/output/graph_findings.rs +461 -0
  146. package/src/output/health_findings.rs +612 -0
  147. package/src/output/human.rs +27 -0
  148. package/src/output/next_steps.rs +92 -0
  149. package/src/output/route_findings.rs +76 -0
  150. package/src/output/runtime_coverage.rs +515 -0
  151. package/src/output/scope.rs +183 -0
  152. package/src/output/security_findings.rs +390 -0
  153. package/src/output/security_sarif.rs +150 -0
  154. package/src/output/suppressions.rs +323 -0
  155. package/src/output/symbol_findings.rs +257 -0
  156. package/src/output/tests.rs +114 -0
  157. package/src/output/types.rs +604 -0
  158. package/src/output/widget_findings.rs +213 -0
  159. package/src/output.rs +682 -0
  160. package/src/package_map.rs +495 -0
  161. package/src/policy/packs.rs +232 -0
  162. package/src/policy/tests.rs +134 -0
  163. package/src/policy.rs +640 -0
  164. package/src/project_list.rs +376 -0
  165. package/src/report_schema/inventory.rs +418 -0
  166. package/src/report_schema.rs +488 -0
  167. package/src/routes.rs +354 -0
  168. package/src/scan/tests.rs +250 -0
  169. package/src/scan.rs +275 -0
  170. package/src/security/detect.rs +639 -0
  171. package/src/security/tests.rs +178 -0
  172. package/src/security.rs +373 -0
  173. package/src/security_gate.rs +555 -0
  174. package/src/symbols/path_filters.rs +27 -0
  175. package/src/symbols/private_type_leaks.rs +125 -0
  176. package/src/symbols/riverpod.rs +113 -0
  177. package/src/symbols/tests.rs +692 -0
  178. package/src/symbols.rs +693 -0
  179. package/src/trace/tests.rs +225 -0
  180. package/src/trace.rs +690 -0
  181. package/src/unsupported.rs +47 -0
  182. package/src/widgets/lifecycle.rs +484 -0
  183. package/src/widgets/params.rs +236 -0
  184. package/src/widgets/tests.rs +430 -0
  185. package/src/widgets/top_level.rs +110 -0
  186. package/src/widgets/unrendered.rs +374 -0
  187. package/src/widgets.rs +590 -0
  188. package/src/workspace_scope.rs +358 -0
package/src/health.rs ADDED
@@ -0,0 +1,597 @@
1
+ use std::fs;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use tree_sitter::Node;
5
+
6
+ use crate::generated::is_generated_dart_path;
7
+ use crate::graph::normalize_against;
8
+ use crate::{Location, ScannedProject};
9
+
10
+ mod coverage;
11
+ mod ownership;
12
+ mod runtime_coverage;
13
+ mod runtime_intelligence;
14
+ mod scores;
15
+ mod threshold_types;
16
+ mod thresholds;
17
+ mod types;
18
+ use coverage::{CoverageMap, coverage_gap_findings, crap_findings, load_lcov};
19
+ use runtime_coverage::load_runtime_coverage;
20
+ pub use runtime_intelligence::{
21
+ RuntimeBlastRadius, RuntimeBlastRisk, RuntimeCoverageAction, RuntimeCoverageIntelligence,
22
+ RuntimeCoverageIntelligenceKind, RuntimeImportance,
23
+ };
24
+ use scores::{file_health_scores, health_hotspots, project_quality_score, refactoring_targets};
25
+ use threshold_types::AppliedThresholds;
26
+ pub use threshold_types::{
27
+ EffectiveThresholds, HealthThresholdOverride, HealthThresholdOverrideReport,
28
+ HealthThresholdOverrideStatus, ThresholdSource,
29
+ };
30
+ use thresholds::ThresholdContext;
31
+ pub use types::{
32
+ ComplexityContribution, ComplexityFinding, ComplexityFunctionKind, ComplexityRule,
33
+ CoverageGapFinding, CoverageGapReason, CrapFinding, FileCoverageStatus, FileHealthScore,
34
+ HealthError, HealthHotspot, HealthOptions, HealthReport, HealthToggle, LowTrafficThreshold,
35
+ RefactoringTarget, RuntimeCoverageConfidence, RuntimeCoverageFinding,
36
+ RuntimeCoverageFindingKind, RuntimeCoverageFormat, RuntimeCoverageReport, RuntimeHotPath,
37
+ SourceMapConfidence,
38
+ };
39
+
40
+ #[derive(Debug, Clone, PartialEq, Eq)]
41
+ struct FunctionMetrics {
42
+ pub(super) path: PathBuf,
43
+ pub(super) symbol: String,
44
+ pub(super) kind: ComplexityFunctionKind,
45
+ pub(super) location: Location,
46
+ pub(super) end_line: usize,
47
+ pub(super) cyclomatic: usize,
48
+ pub(super) cognitive: usize,
49
+ pub(super) contributions: Vec<ComplexityContribution>,
50
+ }
51
+
52
+ #[derive(Debug, Clone, PartialEq, Eq)]
53
+ struct ComplexityState {
54
+ cyclomatic: usize,
55
+ cognitive: usize,
56
+ contributions: Vec<ComplexityContribution>,
57
+ }
58
+
59
+ /// Analyze Dart function complexity for a scanned project.
60
+ ///
61
+ /// # Errors
62
+ ///
63
+ /// Returns [`HealthError`] when a source file cannot be read or parsed.
64
+ pub fn analyze_health(
65
+ project: &ScannedProject,
66
+ options: &HealthOptions,
67
+ ) -> Result<HealthReport, HealthError> {
68
+ let (functions, analyzed_files) = collect_project_functions(project)?;
69
+ let mut threshold_context = ThresholdContext::new(&project.root, options);
70
+ let coverage = load_coverage(project, options)?;
71
+ let runtime_coverage = load_runtime_coverage(project, options, &functions)?;
72
+ let coverage_files = coverage.as_ref().map_or(0, CoverageMap::file_count);
73
+ let complexity = complexity_findings(&functions, options, &mut threshold_context);
74
+ let coverage_gaps = coverage
75
+ .as_ref()
76
+ .filter(|_| options.coverage_gaps.is_enabled())
77
+ .map_or_else(Vec::new, |coverage| {
78
+ coverage_gap_findings(&functions, coverage)
79
+ });
80
+ let mut crap = coverage.as_ref().map_or_else(Vec::new, |coverage| {
81
+ crap_findings(&functions, coverage, &mut threshold_context)
82
+ });
83
+ sort_crap_findings(&mut crap);
84
+ let threshold_overrides = threshold_context.reports();
85
+ let include_hotspots = options.hotspots.is_enabled()
86
+ || options.targets.is_enabled()
87
+ || options.ownership.is_enabled();
88
+ let all_file_scores =
89
+ file_health_scores(&functions, &complexity, &crap, coverage.as_ref(), options);
90
+ let quality_score = project_quality_score(&all_file_scores);
91
+ let mut file_scores =
92
+ if options.file_scores.is_enabled() || include_hotspots || options.ownership.is_enabled() {
93
+ all_file_scores.clone()
94
+ } else {
95
+ Vec::new()
96
+ };
97
+ let mut hotspots = if include_hotspots {
98
+ health_hotspots(&file_scores, options.min_score)
99
+ } else {
100
+ Vec::new()
101
+ };
102
+ let mut refactoring_targets = if options.targets.is_enabled() {
103
+ refactoring_targets(&file_scores)
104
+ } else {
105
+ Vec::new()
106
+ };
107
+ if options.ownership.is_enabled() {
108
+ ownership::apply_ownership(
109
+ &project.root,
110
+ &mut file_scores,
111
+ &mut hotspots,
112
+ &mut refactoring_targets,
113
+ );
114
+ }
115
+
116
+ Ok(HealthReport {
117
+ options: options.clone(),
118
+ quality_score,
119
+ analyzed_files,
120
+ functions: functions.len(),
121
+ max_cyclomatic_complexity: max_cyclomatic_complexity(&functions),
122
+ max_cognitive_complexity: max_cognitive_complexity(&functions),
123
+ coverage_files,
124
+ max_crap_score: max_crap_score(&crap),
125
+ complexity,
126
+ coverage_gaps,
127
+ crap,
128
+ threshold_overrides,
129
+ runtime_coverage,
130
+ file_scores,
131
+ hotspots,
132
+ refactoring_targets,
133
+ })
134
+ }
135
+
136
+ fn collect_project_functions(
137
+ project: &ScannedProject,
138
+ ) -> Result<(Vec<FunctionMetrics>, usize), HealthError> {
139
+ let mut functions = Vec::new();
140
+ let mut analyzed_files = 0;
141
+ for file in &project.files {
142
+ let path = normalize_against(&project.root, &file.path);
143
+ if !path.starts_with(&project.root) || is_ignored_path(&path) {
144
+ continue;
145
+ }
146
+ analyzed_files += 1;
147
+ let source = fs::read_to_string(&path).map_err(|source| HealthError::ReadFile {
148
+ path: path.clone(),
149
+ source,
150
+ })?;
151
+ let parsed = crate::dart_parser::parse_dart_source_lossy(&path, &source)
152
+ .map_err(health_parse_error)?;
153
+ collect_functions(
154
+ parsed.tree().root_node(),
155
+ parsed.source(),
156
+ &path,
157
+ &mut functions,
158
+ );
159
+ }
160
+
161
+ Ok((functions, analyzed_files))
162
+ }
163
+
164
+ fn health_parse_error(error: crate::dart_parser::DartParseError) -> HealthError {
165
+ match error {
166
+ crate::dart_parser::DartParseError::Language(source) => HealthError::Language(source),
167
+ crate::dart_parser::DartParseError::ParseCancelled { path } => {
168
+ HealthError::ParseCancelled { path }
169
+ }
170
+ crate::dart_parser::DartParseError::Syntax { path } => HealthError::ParseCancelled { path },
171
+ }
172
+ }
173
+
174
+ fn max_cyclomatic_complexity(functions: &[FunctionMetrics]) -> usize {
175
+ functions
176
+ .iter()
177
+ .map(|function| function.cyclomatic)
178
+ .max()
179
+ .unwrap_or(0)
180
+ }
181
+
182
+ fn max_cognitive_complexity(functions: &[FunctionMetrics]) -> usize {
183
+ functions
184
+ .iter()
185
+ .map(|function| function.cognitive)
186
+ .max()
187
+ .unwrap_or(0)
188
+ }
189
+
190
+ fn complexity_findings(
191
+ functions: &[FunctionMetrics],
192
+ options: &HealthOptions,
193
+ threshold_context: &mut ThresholdContext,
194
+ ) -> Vec<ComplexityFinding> {
195
+ let mut complexity = functions
196
+ .iter()
197
+ .cloned()
198
+ .filter_map(|function| threshold_finding(function, options, threshold_context))
199
+ .collect::<Vec<_>>();
200
+
201
+ sort_complexity_findings(&mut complexity);
202
+ if let Some(top) = options.top {
203
+ complexity.truncate(top);
204
+ }
205
+ if !options.complexity_breakdown.is_enabled() {
206
+ for finding in &mut complexity {
207
+ finding.contributions.clear();
208
+ }
209
+ }
210
+ complexity
211
+ }
212
+
213
+ fn sort_complexity_findings(findings: &mut [ComplexityFinding]) {
214
+ findings.sort_by(|left, right| {
215
+ (
216
+ std::cmp::Reverse(left.cyclomatic_complexity),
217
+ std::cmp::Reverse(left.cognitive_complexity),
218
+ &left.path,
219
+ left.location.line,
220
+ left.location.column,
221
+ &left.symbol,
222
+ )
223
+ .cmp(&(
224
+ std::cmp::Reverse(right.cyclomatic_complexity),
225
+ std::cmp::Reverse(right.cognitive_complexity),
226
+ &right.path,
227
+ right.location.line,
228
+ right.location.column,
229
+ &right.symbol,
230
+ ))
231
+ });
232
+ }
233
+
234
+ fn sort_crap_findings(findings: &mut [CrapFinding]) {
235
+ findings.sort_by(|left, right| {
236
+ (
237
+ std::cmp::Reverse(left.crap_score),
238
+ std::cmp::Reverse(left.cyclomatic_complexity),
239
+ &left.path,
240
+ left.location.line,
241
+ left.location.column,
242
+ &left.symbol,
243
+ )
244
+ .cmp(&(
245
+ std::cmp::Reverse(right.crap_score),
246
+ std::cmp::Reverse(right.cyclomatic_complexity),
247
+ &right.path,
248
+ right.location.line,
249
+ right.location.column,
250
+ &right.symbol,
251
+ ))
252
+ });
253
+ }
254
+
255
+ fn max_crap_score(findings: &[CrapFinding]) -> usize {
256
+ findings
257
+ .iter()
258
+ .map(|finding| finding.crap_score)
259
+ .max()
260
+ .unwrap_or(0)
261
+ }
262
+
263
+ fn collect_functions(
264
+ node: Node<'_>,
265
+ source: &str,
266
+ path: &Path,
267
+ functions: &mut Vec<FunctionMetrics>,
268
+ ) {
269
+ if let Some(function) = function_from_node(node, source, path) {
270
+ functions.push(function);
271
+ }
272
+
273
+ let mut cursor = node.walk();
274
+ for child in node.named_children(&mut cursor) {
275
+ collect_functions(child, source, path, functions);
276
+ }
277
+ }
278
+
279
+ fn function_from_node(node: Node<'_>, source: &str, path: &Path) -> Option<FunctionMetrics> {
280
+ let (symbol, kind, body) = match node.kind() {
281
+ "function_declaration" => named_function(node, source, ComplexityFunctionKind::Function)?,
282
+ "getter_declaration" => named_function(node, source, ComplexityFunctionKind::Getter)?,
283
+ "setter_declaration" => named_function(node, source, ComplexityFunctionKind::Setter)?,
284
+ "method_declaration" => method_function(node, source)?,
285
+ "function_expression" => (
286
+ "<closure>".to_owned(),
287
+ ComplexityFunctionKind::Closure,
288
+ find_first_named_descendant(node, "function_expression_body")?,
289
+ ),
290
+ _ => return None,
291
+ };
292
+
293
+ let state = score_body(body);
294
+ Some(FunctionMetrics {
295
+ path: path.to_path_buf(),
296
+ symbol,
297
+ kind,
298
+ location: node.start_position().into(),
299
+ end_line: node.end_position().row + 1,
300
+ cyclomatic: state.cyclomatic,
301
+ cognitive: state.cognitive,
302
+ contributions: state.contributions,
303
+ })
304
+ }
305
+
306
+ fn named_function<'tree>(
307
+ node: Node<'tree>,
308
+ source: &str,
309
+ kind: ComplexityFunctionKind,
310
+ ) -> Option<(String, ComplexityFunctionKind, Node<'tree>)> {
311
+ let signature = node.child_by_field_name("signature")?;
312
+ let symbol = field_text(signature, "name", source)?;
313
+ let body = node.child_by_field_name("body")?;
314
+ Some((symbol, kind, body))
315
+ }
316
+
317
+ fn method_function<'tree>(
318
+ node: Node<'tree>,
319
+ source: &str,
320
+ ) -> Option<(String, ComplexityFunctionKind, Node<'tree>)> {
321
+ let signature = node.child_by_field_name("signature")?;
322
+ let body = node.child_by_field_name("body")?;
323
+ let Some(inner) = first_named_child(signature) else {
324
+ return Some(("<method>".to_owned(), ComplexityFunctionKind::Method, body));
325
+ };
326
+ let (symbol, kind) = match inner.kind() {
327
+ "function_signature" | "getter_signature" | "setter_signature" => (
328
+ field_text(inner, "name", source).unwrap_or_else(|| "<method>".to_owned()),
329
+ ComplexityFunctionKind::Method,
330
+ ),
331
+ "operator_signature" => (
332
+ operator_name(inner, source).unwrap_or_else(|| "operator".to_owned()),
333
+ ComplexityFunctionKind::Operator,
334
+ ),
335
+ "constructor_signature"
336
+ | "constant_constructor_signature"
337
+ | "factory_constructor_signature"
338
+ | "redirecting_factory_constructor_signature" => (
339
+ constructor_name(inner, source).unwrap_or_else(|| "<constructor>".to_owned()),
340
+ ComplexityFunctionKind::Constructor,
341
+ ),
342
+ _ => ("<method>".to_owned(), ComplexityFunctionKind::Method),
343
+ };
344
+
345
+ Some((symbol, kind, body))
346
+ }
347
+
348
+ fn score_body(body: Node<'_>) -> ComplexityState {
349
+ let mut state = ComplexityState {
350
+ cyclomatic: 1,
351
+ cognitive: 0,
352
+ contributions: Vec::new(),
353
+ };
354
+ walk_complexity(body, 0, &mut state);
355
+ state
356
+ }
357
+
358
+ fn walk_complexity(node: Node<'_>, nesting: usize, state: &mut ComplexityState) {
359
+ if matches!(
360
+ node.kind(),
361
+ "function_declaration" | "method_declaration" | "function_expression"
362
+ ) {
363
+ return;
364
+ }
365
+
366
+ let decision = decision_for(node);
367
+ if let Some(decision) = decision {
368
+ let cognitive = decision.cognitive + usize::from(decision.nesting_penalty) * nesting;
369
+ state.cyclomatic += decision.cyclomatic;
370
+ state.cognitive += cognitive;
371
+ state.contributions.push(ComplexityContribution {
372
+ location: node.start_position().into(),
373
+ kind: decision.kind.to_owned(),
374
+ cyclomatic: decision.cyclomatic,
375
+ cognitive,
376
+ nesting,
377
+ });
378
+ }
379
+
380
+ let child_nesting = nesting + usize::from(decision.is_some_and(|item| item.nests_children));
381
+ let mut cursor = node.walk();
382
+ for child in node.named_children(&mut cursor) {
383
+ if should_skip_decision_child(node, child) {
384
+ continue;
385
+ }
386
+ walk_complexity(child, child_nesting, state);
387
+ }
388
+ }
389
+
390
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
391
+ struct Decision {
392
+ kind: &'static str,
393
+ cyclomatic: usize,
394
+ cognitive: usize,
395
+ nesting_penalty: bool,
396
+ nests_children: bool,
397
+ }
398
+
399
+ fn decision_for(node: Node<'_>) -> Option<Decision> {
400
+ let decision = match node.kind() {
401
+ "if_statement" => Decision {
402
+ kind: "if",
403
+ cyclomatic: 1,
404
+ cognitive: 1,
405
+ nesting_penalty: true,
406
+ nests_children: true,
407
+ },
408
+ "for_statement" | "for_in_statement" | "while_statement" | "do_statement" => Decision {
409
+ kind: "loop",
410
+ cyclomatic: 1,
411
+ cognitive: 1,
412
+ nesting_penalty: true,
413
+ nests_children: true,
414
+ },
415
+ "catch_clause" => Decision {
416
+ kind: "catch",
417
+ cyclomatic: 1,
418
+ cognitive: 1,
419
+ nesting_penalty: true,
420
+ nests_children: true,
421
+ },
422
+ "conditional_expression" => Decision {
423
+ kind: "ternary",
424
+ cyclomatic: 1,
425
+ cognitive: 1,
426
+ nesting_penalty: true,
427
+ nests_children: true,
428
+ },
429
+ "switch_statement_case" | "switch_expression_case" => Decision {
430
+ kind: "case",
431
+ cyclomatic: 1,
432
+ cognitive: 1,
433
+ nesting_penalty: false,
434
+ nests_children: true,
435
+ },
436
+ "logical_and_expression" => boolean_decision("&&"),
437
+ "logical_or_expression" => boolean_decision("||"),
438
+ "if_null_expression" => boolean_decision("??"),
439
+ _ => return None,
440
+ };
441
+ Some(decision)
442
+ }
443
+
444
+ fn boolean_decision(kind: &'static str) -> Decision {
445
+ Decision {
446
+ kind,
447
+ cyclomatic: 1,
448
+ cognitive: 1,
449
+ nesting_penalty: false,
450
+ nests_children: false,
451
+ }
452
+ }
453
+
454
+ fn should_skip_decision_child(parent: Node<'_>, child: Node<'_>) -> bool {
455
+ matches!(
456
+ (parent.kind(), child.kind()),
457
+ ("logical_and_expression", "logical_and_expression")
458
+ | ("logical_or_expression", "logical_or_expression")
459
+ | ("if_null_expression", "if_null_expression")
460
+ )
461
+ }
462
+
463
+ fn threshold_finding(
464
+ function: FunctionMetrics,
465
+ options: &HealthOptions,
466
+ threshold_context: &mut ThresholdContext,
467
+ ) -> Option<ComplexityFinding> {
468
+ let thresholds = threshold_context.static_thresholds(&function);
469
+ let max_cyclomatic = thresholds
470
+ .effective
471
+ .max_cyclomatic
472
+ .unwrap_or(options.max_cyclomatic);
473
+ let max_cognitive = thresholds
474
+ .effective
475
+ .max_cognitive
476
+ .unwrap_or(options.max_cognitive);
477
+ let high_cyclomatic = function.cyclomatic > max_cyclomatic;
478
+ let high_cognitive = function.cognitive > max_cognitive;
479
+ if !high_cyclomatic && !high_cognitive {
480
+ return None;
481
+ }
482
+
483
+ let rule = match (high_cyclomatic, high_cognitive) {
484
+ (true, true) => ComplexityRule::HighComplexity,
485
+ (true, false) => ComplexityRule::HighCyclomaticComplexity,
486
+ (false, true) => ComplexityRule::HighCognitiveComplexity,
487
+ (false, false) => unreachable!("guarded above"),
488
+ };
489
+
490
+ Some(ComplexityFinding {
491
+ path: function.path,
492
+ symbol: function.symbol,
493
+ kind: function.kind,
494
+ location: function.location,
495
+ cyclomatic_complexity: function.cyclomatic,
496
+ cognitive_complexity: function.cognitive,
497
+ rule,
498
+ effective_thresholds: override_thresholds(&thresholds),
499
+ threshold_source: thresholds.source,
500
+ threshold_reason: thresholds.reason,
501
+ contributions: function.contributions,
502
+ })
503
+ }
504
+
505
+ fn override_thresholds(thresholds: &AppliedThresholds) -> Option<EffectiveThresholds> {
506
+ thresholds.source.map(|_| thresholds.effective.clone())
507
+ }
508
+
509
+ fn load_coverage(
510
+ project: &ScannedProject,
511
+ options: &HealthOptions,
512
+ ) -> Result<Option<CoverageMap>, HealthError> {
513
+ if let Some(path) = &options.coverage_path {
514
+ return load_lcov(&project.root, &normalize_against(&project.root, path)).map(Some);
515
+ }
516
+
517
+ if options.coverage_gaps.is_enabled() || has_crap_threshold(options) {
518
+ let path = project.root.join("coverage/lcov.info");
519
+ if path.is_file() {
520
+ return load_lcov(&project.root, &path).map(Some);
521
+ }
522
+ return Err(HealthError::MissingCoverageData {
523
+ root: project.root.clone(),
524
+ });
525
+ }
526
+
527
+ Ok(None)
528
+ }
529
+
530
+ fn has_crap_threshold(options: &HealthOptions) -> bool {
531
+ options.max_crap.is_some()
532
+ || options
533
+ .threshold_overrides
534
+ .iter()
535
+ .any(HealthThresholdOverride::has_crap_threshold)
536
+ }
537
+
538
+ pub(super) fn is_ignored_path(path: &Path) -> bool {
539
+ if is_generated_dart_path(path) {
540
+ return true;
541
+ }
542
+
543
+ path.components().any(|component| {
544
+ matches!(
545
+ component.as_os_str().to_str(),
546
+ Some("test" | "integration_test" | "test_driver" | "__tests__" | "__mocks__")
547
+ )
548
+ })
549
+ }
550
+
551
+ fn field_text(node: Node<'_>, field_name: &str, source: &str) -> Option<String> {
552
+ node.child_by_field_name(field_name)
553
+ .and_then(|child| child.utf8_text(source.as_bytes()).ok())
554
+ .map(str::to_owned)
555
+ }
556
+
557
+ fn operator_name(node: Node<'_>, source: &str) -> Option<String> {
558
+ node.child_by_field_name("operator")
559
+ .and_then(|child| child.utf8_text(source.as_bytes()).ok())
560
+ .map(|operator| format!("operator {operator}"))
561
+ }
562
+
563
+ fn constructor_name(node: Node<'_>, source: &str) -> Option<String> {
564
+ let mut cursor = node.walk();
565
+ let names = node
566
+ .children_by_field_name("name", &mut cursor)
567
+ .filter(|child| child.kind() == "identifier")
568
+ .filter_map(|child| child.utf8_text(source.as_bytes()).ok())
569
+ .collect::<Vec<_>>();
570
+ if names.is_empty() {
571
+ None
572
+ } else {
573
+ Some(names.join("."))
574
+ }
575
+ }
576
+
577
+ fn first_named_child(node: Node<'_>) -> Option<Node<'_>> {
578
+ let mut cursor = node.walk();
579
+ node.named_children(&mut cursor).next()
580
+ }
581
+
582
+ fn find_first_named_descendant<'tree>(node: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
583
+ if node.kind() == kind {
584
+ return Some(node);
585
+ }
586
+
587
+ let mut cursor = node.walk();
588
+ for child in node.named_children(&mut cursor) {
589
+ if let Some(found) = find_first_named_descendant(child, kind) {
590
+ return Some(found);
591
+ }
592
+ }
593
+ None
594
+ }
595
+
596
+ #[cfg(test)]
597
+ mod tests;