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/policy.rs ADDED
@@ -0,0 +1,640 @@
1
+ use std::collections::BTreeMap;
2
+ use std::fs;
3
+ use std::path::{Path, PathBuf};
4
+
5
+ use glob::Pattern;
6
+ use serde::{Deserialize, Serialize};
7
+ use serde_json::{Value, json};
8
+ use thiserror::Error;
9
+ use tree_sitter::Node;
10
+
11
+ use crate::graph::normalize_against;
12
+ use crate::{DartFile, DependencyKind, Location, ScannedProject};
13
+
14
+ mod packs;
15
+ pub use packs::load_policy_pack;
16
+
17
+ /// Stable JSON schema version for Dart Decimate policy rule packs.
18
+ pub const RULE_PACK_SCHEMA_VERSION: &str = "dart-decimate.rule-pack.v1";
19
+
20
+ /// Boundary-local forbidden call rule.
21
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22
+ pub struct BoundaryCallRule {
23
+ /// Source zone covered by the rule.
24
+ pub from: PathBuf,
25
+ /// Forbidden direct call patterns.
26
+ pub forbidden: Vec<String>,
27
+ }
28
+
29
+ impl BoundaryCallRule {
30
+ /// Create a boundary call rule.
31
+ #[must_use]
32
+ pub fn new(from: impl Into<PathBuf>, forbidden: Vec<String>) -> Self {
33
+ Self {
34
+ from: from.into(),
35
+ forbidden,
36
+ }
37
+ }
38
+ }
39
+
40
+ /// A direct call made from a zone where that call is forbidden.
41
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42
+ pub struct BoundaryCallViolation {
43
+ /// File containing the call.
44
+ pub path: PathBuf,
45
+ /// Rule source zone.
46
+ pub from_boundary: PathBuf,
47
+ /// Call text extracted from syntax.
48
+ pub callee: String,
49
+ /// Pattern that matched the call.
50
+ pub pattern: String,
51
+ /// Location of the call expression.
52
+ pub location: Location,
53
+ }
54
+
55
+ /// Declarative policy pack.
56
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57
+ pub struct PolicyPack {
58
+ /// Stable pack name used in finding rule ids.
59
+ pub name: String,
60
+ /// Path to the pack file, when loaded from disk.
61
+ pub path: Option<PathBuf>,
62
+ /// Pack rules.
63
+ pub rules: Vec<PolicyRule>,
64
+ }
65
+
66
+ /// Declarative policy rule.
67
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68
+ pub struct PolicyRule {
69
+ /// Rule id unique within the pack.
70
+ pub id: String,
71
+ /// Human-readable rule description.
72
+ pub message: Option<String>,
73
+ /// Optional per-rule severity override.
74
+ pub severity: Option<PolicySeverity>,
75
+ /// Rule matcher.
76
+ pub kind: PolicyRuleKind,
77
+ }
78
+
79
+ /// Policy rule severity declared inside a rule pack.
80
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
81
+ #[serde(rename_all = "kebab-case")]
82
+ pub enum PolicySeverity {
83
+ /// Fails the command verdict.
84
+ Error,
85
+ /// Reports without failing the command verdict.
86
+ Warn,
87
+ }
88
+
89
+ /// Supported declarative policy rule families.
90
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91
+ #[serde(rename_all = "kebab-case")]
92
+ pub enum PolicyRuleKind {
93
+ /// Ban Dart import/export URI patterns.
94
+ BannedImport { patterns: Vec<String> },
95
+ /// Ban direct syntactic call patterns.
96
+ BannedCall { patterns: Vec<String> },
97
+ /// Catalogue/effect rule retained for pack compatibility.
98
+ BannedEffect { effects: Vec<String> },
99
+ }
100
+
101
+ /// Policy violation detected from a rule pack.
102
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103
+ pub struct PolicyViolation {
104
+ /// Pack name.
105
+ pub pack: String,
106
+ /// Rule id inside the pack.
107
+ pub rule: String,
108
+ /// Stable rule id for output.
109
+ pub rule_id: String,
110
+ /// File containing the violation.
111
+ pub path: PathBuf,
112
+ /// Matched import/export URI or call text.
113
+ pub target: String,
114
+ /// Matched policy pattern.
115
+ pub pattern: String,
116
+ /// Location of the import/export directive or call expression.
117
+ pub location: Location,
118
+ /// Message from the rule pack, if any.
119
+ pub message: Option<String>,
120
+ /// Per-rule severity override, if any.
121
+ pub severity: Option<PolicySeverity>,
122
+ }
123
+
124
+ /// Errors returned while loading policy packs or source needed for call checks.
125
+ #[derive(Debug, Error)]
126
+ pub enum PolicyError {
127
+ /// Policy pack path did not exist.
128
+ #[error("policy pack not found: {path}")]
129
+ NotFound {
130
+ /// Missing pack path.
131
+ path: PathBuf,
132
+ },
133
+ /// Policy pack file could not be read.
134
+ #[error("failed to read policy pack {path}: {source}")]
135
+ ReadPack {
136
+ /// Pack path.
137
+ path: PathBuf,
138
+ /// Underlying IO error.
139
+ source: std::io::Error,
140
+ },
141
+ /// JSON or JSONC pack could not be parsed.
142
+ #[error("failed to parse policy pack {path}: {source}")]
143
+ ParseJson {
144
+ /// Pack path.
145
+ path: PathBuf,
146
+ /// JSON parse error.
147
+ source: serde_json::Error,
148
+ },
149
+ /// TOML pack could not be parsed.
150
+ #[error("failed to parse policy pack {path}: {source}")]
151
+ ParseToml {
152
+ /// Pack path.
153
+ path: PathBuf,
154
+ /// TOML parse error.
155
+ source: toml::de::Error,
156
+ },
157
+ /// Policy pack rule was invalid.
158
+ #[error("invalid policy pack {path}: {message}")]
159
+ InvalidPack {
160
+ /// Pack path.
161
+ path: PathBuf,
162
+ /// Validation message.
163
+ message: String,
164
+ },
165
+ /// Dart source could not be read for call analysis.
166
+ #[error("failed to read Dart file {path}: {source}")]
167
+ ReadSource {
168
+ /// Source path.
169
+ path: PathBuf,
170
+ /// Underlying IO error.
171
+ source: std::io::Error,
172
+ },
173
+ /// Tree-Sitter rejected the Dart grammar.
174
+ #[error("failed to load Dart grammar: {0}")]
175
+ Language(#[from] tree_sitter::LanguageError),
176
+ /// Tree-Sitter did not produce a parse tree.
177
+ #[error("tree-sitter did not return a parse tree for {path}")]
178
+ ParseCancelled {
179
+ /// Path being parsed.
180
+ path: PathBuf,
181
+ },
182
+ }
183
+
184
+ /// Detect configured boundary-call violations.
185
+ ///
186
+ /// # Errors
187
+ ///
188
+ /// Returns [`PolicyError`] if a checked Dart source file cannot be read or
189
+ /// parsed for call expressions.
190
+ pub fn detect_boundary_call_violations(
191
+ project: &ScannedProject,
192
+ rules: &[BoundaryCallRule],
193
+ ) -> Result<Vec<BoundaryCallViolation>, PolicyError> {
194
+ if rules.is_empty() {
195
+ return Ok(Vec::new());
196
+ }
197
+
198
+ let normalized_rules = rules
199
+ .iter()
200
+ .map(|rule| {
201
+ (
202
+ normalize_against(&project.root, &rule.from),
203
+ compile_patterns(&rule.forbidden),
204
+ )
205
+ })
206
+ .collect::<Vec<_>>();
207
+
208
+ let mut source_cache = SourceCallCache::default();
209
+ let mut violations = Vec::new();
210
+ for file in &project.files {
211
+ let path = normalize_against(&project.root, &file.path);
212
+ for (from_boundary, patterns) in &normalized_rules {
213
+ if !path.starts_with(from_boundary) {
214
+ continue;
215
+ }
216
+ let calls = source_cache.calls_for(&path)?;
217
+ for call in calls {
218
+ for pattern in patterns {
219
+ if pattern.matches(&call.callee) {
220
+ violations.push(BoundaryCallViolation {
221
+ path: path.clone(),
222
+ from_boundary: from_boundary.clone(),
223
+ callee: call.callee.clone(),
224
+ pattern: pattern.source.clone(),
225
+ location: call.location,
226
+ });
227
+ }
228
+ }
229
+ }
230
+ }
231
+ }
232
+
233
+ violations.sort_by(|left, right| {
234
+ (
235
+ &left.path,
236
+ left.location.line,
237
+ left.location.column,
238
+ &left.callee,
239
+ &left.pattern,
240
+ )
241
+ .cmp(&(
242
+ &right.path,
243
+ right.location.line,
244
+ right.location.column,
245
+ &right.callee,
246
+ &right.pattern,
247
+ ))
248
+ });
249
+ Ok(violations)
250
+ }
251
+
252
+ /// Detect policy pack violations.
253
+ ///
254
+ /// # Errors
255
+ ///
256
+ /// Returns [`PolicyError`] if a checked Dart source file cannot be read or
257
+ /// parsed for call-expression rules.
258
+ pub fn detect_policy_violations(
259
+ project: &ScannedProject,
260
+ packs: &[PolicyPack],
261
+ ) -> Result<Vec<PolicyViolation>, PolicyError> {
262
+ if packs.is_empty() {
263
+ return Ok(Vec::new());
264
+ }
265
+
266
+ let compiled = compile_policy_packs(packs);
267
+ let mut source_cache = SourceCallCache::default();
268
+ let mut violations = Vec::new();
269
+ for file in &project.files {
270
+ let path = normalize_against(&project.root, &file.path);
271
+ if !path.starts_with(&project.root) {
272
+ continue;
273
+ }
274
+ detect_import_policy(file, &path, &compiled, &mut violations);
275
+ detect_call_policy(&mut source_cache, &path, &compiled, &mut violations)?;
276
+ }
277
+
278
+ violations.sort_by(|left, right| {
279
+ (
280
+ &left.path,
281
+ left.location.line,
282
+ left.location.column,
283
+ &left.rule_id,
284
+ &left.target,
285
+ )
286
+ .cmp(&(
287
+ &right.path,
288
+ right.location.line,
289
+ right.location.column,
290
+ &right.rule_id,
291
+ &right.target,
292
+ ))
293
+ });
294
+ Ok(violations)
295
+ }
296
+
297
+ /// Return the JSON schema for declarative policy rule packs.
298
+ #[must_use]
299
+ pub fn rule_pack_schema() -> Value {
300
+ json!({
301
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
302
+ "schema_version": RULE_PACK_SCHEMA_VERSION,
303
+ "title": "Dart Decimate policy rule pack",
304
+ "type": "object",
305
+ "additionalProperties": false,
306
+ "required": ["rules"],
307
+ "properties": {
308
+ "name": { "type": "string" },
309
+ "rules": {
310
+ "type": "array",
311
+ "items": { "$ref": "#/$defs/rule" }
312
+ }
313
+ },
314
+ "$defs": {
315
+ "rule": {
316
+ "type": "object",
317
+ "additionalProperties": false,
318
+ "required": ["id", "type"],
319
+ "properties": {
320
+ "id": { "type": "string", "minLength": 1 },
321
+ "type": {
322
+ "type": "string",
323
+ "enum": ["banned-import", "banned-call", "banned-effect"]
324
+ },
325
+ "kind": {
326
+ "type": "string",
327
+ "enum": ["banned-import", "banned-call", "banned-effect"]
328
+ },
329
+ "message": { "type": "string" },
330
+ "severity": {
331
+ "type": "string",
332
+ "enum": ["warn", "error"]
333
+ },
334
+ "pattern": { "type": "string" },
335
+ "patterns": {
336
+ "type": "array",
337
+ "items": { "type": "string" }
338
+ },
339
+ "effect": { "type": "string" },
340
+ "effects": {
341
+ "type": "array",
342
+ "items": { "type": "string" }
343
+ }
344
+ }
345
+ }
346
+ }
347
+ })
348
+ }
349
+
350
+ fn detect_import_policy(
351
+ file: &DartFile,
352
+ path: &Path,
353
+ packs: &[CompiledPolicyPack],
354
+ violations: &mut Vec<PolicyViolation>,
355
+ ) {
356
+ for directive in file
357
+ .imports
358
+ .iter()
359
+ .map(|import| (DependencyKind::Import, import.uri.as_str(), import.location))
360
+ .chain(
361
+ file.exports
362
+ .iter()
363
+ .map(|export| (DependencyKind::Export, export.uri.as_str(), export.location)),
364
+ )
365
+ {
366
+ let (_, uri, location) = directive;
367
+ for pack in packs {
368
+ for rule in &pack.import_rules {
369
+ for pattern in &rule.patterns {
370
+ if pattern.matches(uri) {
371
+ violations.push(PolicyViolation {
372
+ pack: pack.name.clone(),
373
+ rule: rule.id.clone(),
374
+ rule_id: policy_rule_id(&pack.name, &rule.id),
375
+ path: path.to_path_buf(),
376
+ target: uri.to_owned(),
377
+ pattern: pattern.source.clone(),
378
+ location,
379
+ message: rule.message.clone(),
380
+ severity: rule.severity,
381
+ });
382
+ }
383
+ }
384
+ }
385
+ }
386
+ }
387
+ }
388
+
389
+ fn detect_call_policy(
390
+ source_cache: &mut SourceCallCache,
391
+ path: &Path,
392
+ packs: &[CompiledPolicyPack],
393
+ violations: &mut Vec<PolicyViolation>,
394
+ ) -> Result<(), PolicyError> {
395
+ if !packs.iter().any(|pack| !pack.call_rules.is_empty()) {
396
+ return Ok(());
397
+ }
398
+ let calls = source_cache.calls_for(path)?;
399
+ for call in calls {
400
+ for pack in packs {
401
+ for rule in &pack.call_rules {
402
+ for pattern in &rule.patterns {
403
+ if pattern.matches(&call.callee) {
404
+ violations.push(PolicyViolation {
405
+ pack: pack.name.clone(),
406
+ rule: rule.id.clone(),
407
+ rule_id: policy_rule_id(&pack.name, &rule.id),
408
+ path: path.to_path_buf(),
409
+ target: call.callee.clone(),
410
+ pattern: pattern.source.clone(),
411
+ location: call.location,
412
+ message: rule.message.clone(),
413
+ severity: rule.severity,
414
+ });
415
+ }
416
+ }
417
+ }
418
+ }
419
+ }
420
+ Ok(())
421
+ }
422
+
423
+ fn policy_rule_id(pack: &str, rule: &str) -> String {
424
+ format!("dart-decimate/policy/{pack}/{rule}")
425
+ }
426
+
427
+ #[derive(Debug, Clone)]
428
+ struct CompiledPolicyPack {
429
+ name: String,
430
+ import_rules: Vec<CompiledPolicyRule>,
431
+ call_rules: Vec<CompiledPolicyRule>,
432
+ }
433
+
434
+ #[derive(Debug, Clone)]
435
+ struct CompiledPolicyRule {
436
+ id: String,
437
+ message: Option<String>,
438
+ severity: Option<PolicySeverity>,
439
+ patterns: Vec<CompiledPattern>,
440
+ }
441
+
442
+ fn compile_policy_packs(packs: &[PolicyPack]) -> Vec<CompiledPolicyPack> {
443
+ packs
444
+ .iter()
445
+ .map(|pack| {
446
+ let mut import_rules = Vec::new();
447
+ let mut call_rules = Vec::new();
448
+ for rule in &pack.rules {
449
+ match &rule.kind {
450
+ PolicyRuleKind::BannedImport { patterns } => {
451
+ import_rules.push(CompiledPolicyRule {
452
+ id: rule.id.clone(),
453
+ message: rule.message.clone(),
454
+ severity: rule.severity,
455
+ patterns: compile_patterns(patterns),
456
+ });
457
+ }
458
+ PolicyRuleKind::BannedCall { patterns } => {
459
+ call_rules.push(CompiledPolicyRule {
460
+ id: rule.id.clone(),
461
+ message: rule.message.clone(),
462
+ severity: rule.severity,
463
+ patterns: compile_patterns(patterns),
464
+ });
465
+ }
466
+ PolicyRuleKind::BannedEffect { .. } => {}
467
+ }
468
+ }
469
+ CompiledPolicyPack {
470
+ name: pack.name.clone(),
471
+ import_rules,
472
+ call_rules,
473
+ }
474
+ })
475
+ .collect()
476
+ }
477
+
478
+ #[derive(Debug, Clone)]
479
+ struct CompiledPattern {
480
+ source: String,
481
+ glob: Option<Pattern>,
482
+ }
483
+
484
+ impl CompiledPattern {
485
+ fn matches(&self, value: &str) -> bool {
486
+ self.glob
487
+ .as_ref()
488
+ .is_some_and(|pattern| pattern.matches(value))
489
+ || self.source == value
490
+ }
491
+ }
492
+
493
+ fn compile_patterns(patterns: &[String]) -> Vec<CompiledPattern> {
494
+ patterns
495
+ .iter()
496
+ .map(|pattern| CompiledPattern {
497
+ source: pattern.clone(),
498
+ glob: Pattern::new(pattern).ok(),
499
+ })
500
+ .collect()
501
+ }
502
+
503
+ #[derive(Debug, Default)]
504
+ struct SourceCallCache {
505
+ calls: BTreeMap<PathBuf, Vec<CallSite>>,
506
+ }
507
+
508
+ impl SourceCallCache {
509
+ fn calls_for(&mut self, path: &Path) -> Result<Vec<CallSite>, PolicyError> {
510
+ if let Some(calls) = self.calls.get(path) {
511
+ return Ok(calls.clone());
512
+ }
513
+ let calls = extract_calls(path)?;
514
+ self.calls.insert(path.to_path_buf(), calls.clone());
515
+ Ok(calls)
516
+ }
517
+ }
518
+
519
+ #[derive(Debug, Clone, PartialEq, Eq)]
520
+ struct CallSite {
521
+ callee: String,
522
+ location: Location,
523
+ }
524
+
525
+ fn extract_calls(path: &Path) -> Result<Vec<CallSite>, PolicyError> {
526
+ let source = fs::read_to_string(path).map_err(|source| PolicyError::ReadSource {
527
+ path: path.to_path_buf(),
528
+ source,
529
+ })?;
530
+ let parsed =
531
+ crate::dart_parser::parse_dart_source_lossy(path, &source).map_err(policy_parse_error)?;
532
+ let mut calls = Vec::new();
533
+ collect_calls(parsed.tree().root_node(), parsed.source(), &mut calls);
534
+ calls.sort_by(|left, right| {
535
+ (left.location.line, left.location.column, &left.callee).cmp(&(
536
+ right.location.line,
537
+ right.location.column,
538
+ &right.callee,
539
+ ))
540
+ });
541
+ calls.dedup();
542
+ Ok(calls)
543
+ }
544
+
545
+ fn policy_parse_error(error: crate::dart_parser::DartParseError) -> PolicyError {
546
+ match error {
547
+ crate::dart_parser::DartParseError::Language(source) => PolicyError::Language(source),
548
+ crate::dart_parser::DartParseError::ParseCancelled { path } => {
549
+ PolicyError::ParseCancelled { path }
550
+ }
551
+ crate::dart_parser::DartParseError::Syntax { path } => PolicyError::ParseCancelled { path },
552
+ }
553
+ }
554
+
555
+ fn collect_calls(node: Node<'_>, source: &str, calls: &mut Vec<CallSite>) {
556
+ match node.kind() {
557
+ "call_expression" => push_call_expression(node, source, calls),
558
+ "cascade_call_expression" => push_cascade_call_expression(node, source, calls),
559
+ _ => {}
560
+ }
561
+
562
+ let mut cursor = node.walk();
563
+ for child in node.named_children(&mut cursor) {
564
+ collect_calls(child, source, calls);
565
+ }
566
+ }
567
+
568
+ fn push_call_expression(node: Node<'_>, source: &str, calls: &mut Vec<CallSite>) {
569
+ let Some(function) = node.child_by_field_name("function") else {
570
+ return;
571
+ };
572
+ let Some(callee) = callee_text(function, source) else {
573
+ return;
574
+ };
575
+ calls.push(CallSite {
576
+ callee,
577
+ location: node.start_position().into(),
578
+ });
579
+ }
580
+
581
+ fn push_cascade_call_expression(node: Node<'_>, source: &str, calls: &mut Vec<CallSite>) {
582
+ let property = node
583
+ .child_by_field_name("property")
584
+ .or_else(|| node.child_by_field_name("function"));
585
+ let Some(property) = property else {
586
+ return;
587
+ };
588
+ let Some(callee) = callee_text(property, source) else {
589
+ return;
590
+ };
591
+ calls.push(CallSite {
592
+ callee,
593
+ location: node.start_position().into(),
594
+ });
595
+ }
596
+
597
+ fn callee_text(node: Node<'_>, source: &str) -> Option<String> {
598
+ match node.kind() {
599
+ "identifier" => text(node, source),
600
+ "member_expression" | "null_aware_member_expression" => {
601
+ let object = node.child_by_field_name("object")?;
602
+ let property = node.child_by_field_name("property")?;
603
+ Some(format!(
604
+ "{}.{}",
605
+ callee_text(object, source)?,
606
+ text(property, source)?
607
+ ))
608
+ }
609
+ "instantiation_expression" => node
610
+ .child_by_field_name("function")
611
+ .and_then(|function| callee_text(function, source)),
612
+ "null_assertion_expression" => node
613
+ .child_by_field_name("value")
614
+ .and_then(|value| callee_text(value, source)),
615
+ "parenthesized_expression" => {
616
+ first_named_child(node).and_then(|child| callee_text(child, source))
617
+ }
618
+ _ => text(node, source).map(|value| {
619
+ value
620
+ .split_once('(')
621
+ .map_or(value.clone(), |(callee, _)| callee.trim().to_owned())
622
+ }),
623
+ }
624
+ }
625
+
626
+ fn first_named_child(node: Node<'_>) -> Option<Node<'_>> {
627
+ let mut cursor = node.walk();
628
+ node.named_children(&mut cursor).next()
629
+ }
630
+
631
+ fn text(node: Node<'_>, source: &str) -> Option<String> {
632
+ node.utf8_text(source.as_bytes())
633
+ .ok()
634
+ .map(str::trim)
635
+ .filter(|value| !value.is_empty())
636
+ .map(str::to_owned)
637
+ }
638
+
639
+ #[cfg(test)]
640
+ mod tests;