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
@@ -0,0 +1,673 @@
1
+ use std::borrow::Cow;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use thiserror::Error;
5
+ use tree_sitter::{Parser, Tree};
6
+
7
+ /// Parsed Dart source and the source buffer used for the parse.
8
+ ///
9
+ /// Tree-Sitter node byte ranges are relative to this buffer, which may be a
10
+ /// normalized compatibility copy when the upstream grammar lags new Dart syntax.
11
+ pub(crate) struct ParsedDart<'source> {
12
+ tree: Tree,
13
+ source: Cow<'source, str>,
14
+ }
15
+
16
+ impl ParsedDart<'_> {
17
+ pub(crate) fn tree(&self) -> &Tree {
18
+ &self.tree
19
+ }
20
+
21
+ pub(crate) fn source(&self) -> &str {
22
+ &self.source
23
+ }
24
+ }
25
+
26
+ /// Errors returned while parsing Dart source.
27
+ #[derive(Debug, Error)]
28
+ pub(crate) enum DartParseError {
29
+ /// Tree-Sitter rejected the Dart grammar.
30
+ #[error("failed to load Dart grammar: {0}")]
31
+ Language(#[from] tree_sitter::LanguageError),
32
+ /// Tree-Sitter did not produce a parse tree.
33
+ #[error("tree-sitter did not return a parse tree for {path}")]
34
+ ParseCancelled {
35
+ /// Path being parsed.
36
+ path: PathBuf,
37
+ },
38
+ /// The source parsed with syntax errors.
39
+ #[error("Dart syntax errors found in {path}")]
40
+ Syntax {
41
+ /// Path being parsed.
42
+ path: PathBuf,
43
+ },
44
+ }
45
+
46
+ /// Parse Dart source and reject unrecoverable syntax errors.
47
+ pub(crate) fn parse_dart_source_strict<'source>(
48
+ path: &Path,
49
+ source: &'source str,
50
+ ) -> Result<ParsedDart<'source>, DartParseError> {
51
+ let original = parse_raw(path, source)?;
52
+ if !original.root_node().has_error() {
53
+ return Ok(ParsedDart {
54
+ tree: original,
55
+ source: Cow::Borrowed(source),
56
+ });
57
+ }
58
+
59
+ if let Some(normalized) = normalize_modern_dart_compatibility(source) {
60
+ let tree = parse_raw(path, &normalized)?;
61
+ if !tree.root_node().has_error() {
62
+ return Ok(ParsedDart {
63
+ tree,
64
+ source: Cow::Owned(normalized),
65
+ });
66
+ }
67
+ }
68
+
69
+ Err(DartParseError::Syntax {
70
+ path: path.to_path_buf(),
71
+ })
72
+ }
73
+
74
+ /// Parse Dart source, preferring a syntax-clean compatibility parse when possible.
75
+ ///
76
+ /// Some analyzers historically tolerated partial Tree-Sitter trees. This keeps
77
+ /// that behavior while still letting them benefit from compatibility rewrites.
78
+ pub(crate) fn parse_dart_source_lossy<'source>(
79
+ path: &Path,
80
+ source: &'source str,
81
+ ) -> Result<ParsedDart<'source>, DartParseError> {
82
+ let original = parse_raw(path, source)?;
83
+ if !original.root_node().has_error() {
84
+ return Ok(ParsedDart {
85
+ tree: original,
86
+ source: Cow::Borrowed(source),
87
+ });
88
+ }
89
+
90
+ if let Some(normalized) = normalize_modern_dart_compatibility(source) {
91
+ let tree = parse_raw(path, &normalized)?;
92
+ if !tree.root_node().has_error() {
93
+ return Ok(ParsedDart {
94
+ tree,
95
+ source: Cow::Owned(normalized),
96
+ });
97
+ }
98
+ }
99
+
100
+ Ok(ParsedDart {
101
+ tree: original,
102
+ source: Cow::Borrowed(source),
103
+ })
104
+ }
105
+
106
+ fn parse_raw(path: &Path, source: &str) -> Result<Tree, DartParseError> {
107
+ let mut parser = Parser::new();
108
+ parser.set_language(&tree_sitter_dart::LANGUAGE.into())?;
109
+ parser
110
+ .parse(source, None)
111
+ .ok_or_else(|| DartParseError::ParseCancelled {
112
+ path: path.to_path_buf(),
113
+ })
114
+ }
115
+
116
+ fn normalize_modern_dart_compatibility(source: &str) -> Option<String> {
117
+ let mut normalized = normalize_primary_constructors(source);
118
+ let mut output = normalized.take().unwrap_or_else(|| source.to_owned());
119
+ let mut changed = output != source;
120
+ changed |= normalize_dot_shorthands(&mut output);
121
+ changed |= normalize_null_aware_collection_elements(&mut output);
122
+ changed.then_some(output)
123
+ }
124
+
125
+ fn normalize_primary_constructors(source: &str) -> Option<String> {
126
+ let mut replacements = Vec::new();
127
+ let mut cursor = 0;
128
+
129
+ while cursor < source.len() {
130
+ let Some((keyword_start, keyword)) = find_next_header_keyword(source, cursor) else {
131
+ break;
132
+ };
133
+ let after_keyword = keyword_start + keyword.len();
134
+ if let Some(header) =
135
+ primary_constructor_header(source, after_keyword, keyword, &mut replacements)
136
+ {
137
+ cursor = push_primary_constructor_replacements(source, &mut replacements, &header);
138
+ } else {
139
+ cursor = after_keyword;
140
+ }
141
+ }
142
+
143
+ if replacements.is_empty() {
144
+ return None;
145
+ }
146
+
147
+ Some(apply_primary_constructor_replacements(source, replacements))
148
+ }
149
+
150
+ fn primary_constructor_header(
151
+ source: &str,
152
+ cursor: usize,
153
+ keyword: &'static str,
154
+ replacements: &mut Vec<Replacement>,
155
+ ) -> Option<PrimaryConstructorHeader> {
156
+ let mut name_start = skip_whitespace(source, cursor)?;
157
+ if matches!(keyword, "class" | "enum") && starts_keyword(source, name_start, "const") {
158
+ let const_end = name_start + "const".len();
159
+ replacements.push(Replacement {
160
+ start: name_start,
161
+ end: const_end,
162
+ kind: ReplacementKind::Whitespace,
163
+ });
164
+ name_start = skip_whitespace(source, const_end)?;
165
+ }
166
+ let name_end = identifier_end(source, name_start)?;
167
+ let class_name = source[name_start..name_end].to_owned();
168
+ let mut header_cursor = skip_whitespace(source, name_end).unwrap_or(name_end);
169
+
170
+ if source.as_bytes().get(header_cursor).copied() == Some(b'<')
171
+ && let Some(type_params_end) = matching_delimiter(source, header_cursor, b'<', b'>')
172
+ {
173
+ header_cursor = skip_whitespace(source, type_params_end + 1).unwrap_or(type_params_end + 1);
174
+ }
175
+
176
+ let replacement_start = primary_constructor_replacement_start(source, &mut header_cursor)?;
177
+ if source.as_bytes().get(header_cursor).copied() != Some(b'(') {
178
+ return None;
179
+ }
180
+ let params_end = matching_delimiter(source, header_cursor, b'(', b')')?;
181
+ let after_params = skip_whitespace(source, params_end + 1).unwrap_or(params_end + 1);
182
+ Some(PrimaryConstructorHeader {
183
+ keyword,
184
+ class_name,
185
+ replacement_start,
186
+ params_end,
187
+ after_params,
188
+ next: source.as_bytes().get(after_params).copied(),
189
+ terminator: find_header_terminator(source, after_params),
190
+ })
191
+ }
192
+
193
+ fn primary_constructor_replacement_start(source: &str, header_cursor: &mut usize) -> Option<usize> {
194
+ if source.as_bytes().get(*header_cursor).copied() != Some(b'.') {
195
+ return Some(*header_cursor);
196
+ }
197
+ let dot_start = *header_cursor;
198
+ let suffix_start = skip_whitespace(source, *header_cursor + 1).unwrap_or(*header_cursor + 1);
199
+ let suffix_end = identifier_end(source, suffix_start)?;
200
+ *header_cursor = skip_whitespace(source, suffix_end).unwrap_or(suffix_end);
201
+ Some(dot_start)
202
+ }
203
+
204
+ fn push_primary_constructor_replacements(
205
+ source: &str,
206
+ replacements: &mut Vec<Replacement>,
207
+ header: &PrimaryConstructorHeader,
208
+ ) -> usize {
209
+ match header.next {
210
+ Some(b'{') => {
211
+ push_primary_constructor_param_whitespace(replacements, header);
212
+ push_constructor_body_replacement(source, replacements, header);
213
+ header.params_end + 1
214
+ }
215
+ Some(b';') if header.keyword == "class" => {
216
+ replacements.push(Replacement {
217
+ start: header.replacement_start,
218
+ end: header.after_params + 1,
219
+ kind: ReplacementKind::EmptyBody,
220
+ });
221
+ header.after_params + 1
222
+ }
223
+ _ if header
224
+ .terminator
225
+ .is_some_and(|(_, byte)| byte == b';' && header.keyword == "class") =>
226
+ {
227
+ push_primary_constructor_param_whitespace(replacements, header);
228
+ if let Some((terminator_start, _)) = header.terminator {
229
+ replacements.push(Replacement {
230
+ start: terminator_start,
231
+ end: terminator_start + 1,
232
+ kind: ReplacementKind::Body,
233
+ });
234
+ }
235
+ header.params_end + 1
236
+ }
237
+ _ if header.terminator.is_some_and(|(_, byte)| byte == b'{') => {
238
+ push_primary_constructor_param_whitespace(replacements, header);
239
+ push_constructor_body_replacement(source, replacements, header);
240
+ header.params_end + 1
241
+ }
242
+ _ => header.params_end + 1,
243
+ }
244
+ }
245
+
246
+ fn push_primary_constructor_param_whitespace(
247
+ replacements: &mut Vec<Replacement>,
248
+ header: &PrimaryConstructorHeader,
249
+ ) {
250
+ replacements.push(Replacement {
251
+ start: header.replacement_start,
252
+ end: header.params_end + 1,
253
+ kind: ReplacementKind::Whitespace,
254
+ });
255
+ }
256
+
257
+ fn push_constructor_body_replacement(
258
+ source: &str,
259
+ replacements: &mut Vec<Replacement>,
260
+ header: &PrimaryConstructorHeader,
261
+ ) {
262
+ if let Some((terminator_start, _)) = header.terminator
263
+ && let Some(body_end) = matching_delimiter(source, terminator_start, b'{', b'}')
264
+ && let Some(this_start) =
265
+ find_primary_constructor_body(source, terminator_start + 1, body_end)
266
+ {
267
+ replacements.push(Replacement {
268
+ start: this_start,
269
+ end: this_start + "this".len(),
270
+ kind: ReplacementKind::ConstructorBody(header.class_name.clone()),
271
+ });
272
+ }
273
+ }
274
+
275
+ fn apply_primary_constructor_replacements(source: &str, replacements: Vec<Replacement>) -> String {
276
+ let mut normalized = String::with_capacity(source.len());
277
+ let mut copied = 0;
278
+ for replacement in replacements {
279
+ normalized.push_str(&source[copied..replacement.start]);
280
+ match replacement.kind {
281
+ ReplacementKind::Whitespace => {
282
+ push_preserved_whitespace(
283
+ &mut normalized,
284
+ &source[replacement.start..replacement.end],
285
+ );
286
+ }
287
+ ReplacementKind::EmptyBody => {
288
+ normalized.push_str("{}");
289
+ let span = &source[replacement.start..replacement.end];
290
+ let skip = span
291
+ .char_indices()
292
+ .nth(2)
293
+ .map_or(span.len(), |(index, _)| index);
294
+ push_preserved_whitespace(&mut normalized, &span[skip..]);
295
+ }
296
+ ReplacementKind::Body => normalized.push_str("{}"),
297
+ ReplacementKind::ConstructorBody(name) => {
298
+ normalized.push_str(&name);
299
+ normalized.push_str("()");
300
+ }
301
+ }
302
+ copied = replacement.end;
303
+ }
304
+ normalized.push_str(&source[copied..]);
305
+ normalized
306
+ }
307
+
308
+ fn normalize_dot_shorthands(source: &mut String) -> bool {
309
+ let bytes = source.as_bytes().to_vec();
310
+ let mut replacements = Vec::new();
311
+ let mut cursor = 0;
312
+ while cursor < bytes.len() {
313
+ if bytes[cursor] != b'.' {
314
+ cursor += 1;
315
+ continue;
316
+ }
317
+ if !is_dot_shorthand_start(&bytes, cursor) {
318
+ cursor += 1;
319
+ continue;
320
+ }
321
+ if source
322
+ .get(cursor + 1..)
323
+ .is_some_and(|suffix| suffix.starts_with("new"))
324
+ && source
325
+ .get(cursor + 4..)
326
+ .and_then(|suffix| suffix.chars().next())
327
+ .is_none_or(|ch| !is_identifier_char(ch))
328
+ {
329
+ replacements.push((cursor, cursor + 4, "New_".to_owned()));
330
+ cursor += 4;
331
+ } else {
332
+ replacements.push((cursor, cursor + 1, " ".to_owned()));
333
+ cursor += 1;
334
+ }
335
+ }
336
+ apply_text_replacements(source, replacements)
337
+ }
338
+
339
+ fn is_dot_shorthand_start(bytes: &[u8], cursor: usize) -> bool {
340
+ if cursor > 0 && bytes[cursor - 1] == b'?' {
341
+ return false;
342
+ }
343
+ let Some(next) = bytes.get(cursor + 1).copied() else {
344
+ return false;
345
+ };
346
+ if !(next == b'_' || next.is_ascii_alphabetic()) {
347
+ return false;
348
+ }
349
+ if matches!(next, b'.' | b'?') {
350
+ return false;
351
+ }
352
+ let Some(previous) = previous_non_whitespace_byte(bytes, cursor) else {
353
+ return true;
354
+ };
355
+ matches!(
356
+ previous,
357
+ b'=' | b'(' | b'[' | b'{' | b',' | b':' | b'?' | b'!' | b'>' | b'|'
358
+ )
359
+ }
360
+
361
+ fn normalize_null_aware_collection_elements(source: &mut String) -> bool {
362
+ let bytes = source.as_bytes().to_vec();
363
+ let mut replacements = Vec::new();
364
+ for cursor in 0..bytes.len() {
365
+ if bytes[cursor] != b'?' || !is_null_aware_collection_marker(&bytes, cursor) {
366
+ continue;
367
+ }
368
+ replacements.push((cursor, cursor + 1, " ".to_owned()));
369
+ }
370
+ apply_text_replacements(source, replacements)
371
+ }
372
+
373
+ fn is_null_aware_collection_marker(bytes: &[u8], cursor: usize) -> bool {
374
+ if matches!(bytes.get(cursor + 1), Some(b'?' | b'.')) {
375
+ return false;
376
+ }
377
+ let Some(next) = next_non_whitespace_byte(bytes, cursor + 1) else {
378
+ return false;
379
+ };
380
+ if next == b':' || next == b',' || next == b']' || next == b'}' {
381
+ return false;
382
+ }
383
+ let Some(previous) = previous_non_whitespace_byte(bytes, cursor) else {
384
+ return false;
385
+ };
386
+ matches!(previous, b'[' | b'{' | b',' | b':')
387
+ || (previous == b'.'
388
+ && cursor >= 3
389
+ && bytes.get(cursor - 3..cursor) == Some(&[b'.', b'.', b'.'][..]))
390
+ }
391
+
392
+ fn apply_text_replacements(source: &mut String, replacements: Vec<(usize, usize, String)>) -> bool {
393
+ if replacements.is_empty() {
394
+ return false;
395
+ }
396
+ for (start, end, replacement) in replacements.into_iter().rev() {
397
+ source.replace_range(start..end, &replacement);
398
+ }
399
+ true
400
+ }
401
+
402
+ fn find_header_terminator(source: &str, start: usize) -> Option<(usize, u8)> {
403
+ let bytes = source.as_bytes();
404
+ let mut cursor = start;
405
+ while cursor < bytes.len() {
406
+ match bytes[cursor] {
407
+ b'{' | b';' => return Some((cursor, bytes[cursor])),
408
+ b'(' => cursor = matching_delimiter(source, cursor, b'(', b')')?,
409
+ b'<' => cursor = matching_delimiter(source, cursor, b'<', b'>')?,
410
+ b'\'' | b'"' => cursor = skip_quoted(source, cursor)?,
411
+ _ => {}
412
+ }
413
+ cursor += 1;
414
+ }
415
+ None
416
+ }
417
+
418
+ fn previous_non_whitespace_byte(bytes: &[u8], cursor: usize) -> Option<u8> {
419
+ bytes
420
+ .get(..cursor)?
421
+ .iter()
422
+ .rev()
423
+ .copied()
424
+ .find(|byte| !byte.is_ascii_whitespace())
425
+ }
426
+
427
+ fn next_non_whitespace_byte(bytes: &[u8], cursor: usize) -> Option<u8> {
428
+ bytes
429
+ .get(cursor..)?
430
+ .iter()
431
+ .copied()
432
+ .find(|byte| !byte.is_ascii_whitespace())
433
+ }
434
+
435
+ #[derive(Debug)]
436
+ struct Replacement {
437
+ start: usize,
438
+ end: usize,
439
+ kind: ReplacementKind,
440
+ }
441
+
442
+ struct PrimaryConstructorHeader {
443
+ keyword: &'static str,
444
+ class_name: String,
445
+ replacement_start: usize,
446
+ params_end: usize,
447
+ after_params: usize,
448
+ next: Option<u8>,
449
+ terminator: Option<(usize, u8)>,
450
+ }
451
+
452
+ #[derive(Debug)]
453
+ enum ReplacementKind {
454
+ Whitespace,
455
+ EmptyBody,
456
+ Body,
457
+ ConstructorBody(String),
458
+ }
459
+
460
+ fn find_primary_constructor_body(source: &str, start: usize, end: usize) -> Option<usize> {
461
+ let bytes = source.as_bytes();
462
+ let mut depth = 0usize;
463
+ let mut cursor = start;
464
+ while cursor < end {
465
+ match bytes[cursor] {
466
+ b'{' | b'(' | b'[' => depth += 1,
467
+ b'}' | b')' | b']' => depth = depth.saturating_sub(1),
468
+ b'\'' | b'"' => cursor = skip_quoted(source, cursor)?,
469
+ _ if depth == 0 && starts_keyword(source, cursor, "this") => {
470
+ let after_this = skip_whitespace(source, cursor + "this".len())?;
471
+ if matches!(
472
+ source.as_bytes().get(after_this).copied(),
473
+ Some(b':' | b'{' | b';')
474
+ ) {
475
+ return Some(cursor);
476
+ }
477
+ }
478
+ _ => {}
479
+ }
480
+ cursor += 1;
481
+ }
482
+ None
483
+ }
484
+
485
+ fn find_next_header_keyword(source: &str, start: usize) -> Option<(usize, &'static str)> {
486
+ let mut cursor = start;
487
+ while cursor < source.len() {
488
+ if starts_keyword(source, cursor, "class") {
489
+ return Some((cursor, "class"));
490
+ }
491
+ if starts_keyword(source, cursor, "enum") {
492
+ return Some((cursor, "enum"));
493
+ }
494
+ cursor = next_char_boundary(source, cursor)?;
495
+ }
496
+ None
497
+ }
498
+
499
+ fn starts_keyword(source: &str, start: usize, keyword: &str) -> bool {
500
+ source
501
+ .get(start..)
502
+ .is_some_and(|suffix| suffix.starts_with(keyword))
503
+ && !source
504
+ .get(..start)
505
+ .and_then(|prefix| prefix.chars().next_back())
506
+ .is_some_and(is_identifier_char)
507
+ && !source
508
+ .get(start + keyword.len()..)
509
+ .and_then(|suffix| suffix.chars().next())
510
+ .is_some_and(is_identifier_char)
511
+ }
512
+
513
+ fn skip_whitespace(source: &str, start: usize) -> Option<usize> {
514
+ let mut cursor = start;
515
+ while cursor < source.len() {
516
+ let ch = source.get(cursor..)?.chars().next()?;
517
+ if !ch.is_whitespace() {
518
+ return Some(cursor);
519
+ }
520
+ cursor += ch.len_utf8();
521
+ }
522
+ Some(cursor)
523
+ }
524
+
525
+ fn identifier_end(source: &str, start: usize) -> Option<usize> {
526
+ let mut chars = source.get(start..)?.char_indices();
527
+ let (_, first) = chars.next()?;
528
+ if !is_identifier_start(first) {
529
+ return None;
530
+ }
531
+
532
+ for (offset, ch) in chars {
533
+ if !is_identifier_char(ch) {
534
+ return Some(start + offset);
535
+ }
536
+ }
537
+ Some(source.len())
538
+ }
539
+
540
+ fn matching_delimiter(source: &str, start: usize, open: u8, close: u8) -> Option<usize> {
541
+ let bytes = source.as_bytes();
542
+ if bytes.get(start).copied() != Some(open) {
543
+ return None;
544
+ }
545
+
546
+ let mut depth = 0usize;
547
+ let mut cursor = start;
548
+ while cursor < bytes.len() {
549
+ match bytes[cursor] {
550
+ byte if byte == open => depth += 1,
551
+ byte if byte == close => {
552
+ depth = depth.checked_sub(1)?;
553
+ if depth == 0 {
554
+ return Some(cursor);
555
+ }
556
+ }
557
+ b'\'' | b'"' => cursor = skip_quoted(source, cursor)?,
558
+ _ => {}
559
+ }
560
+ cursor += 1;
561
+ }
562
+ None
563
+ }
564
+
565
+ fn skip_quoted(source: &str, start: usize) -> Option<usize> {
566
+ let quote = source.as_bytes().get(start).copied()?;
567
+ let mut cursor = start + 1;
568
+ while cursor < source.len() {
569
+ match source.as_bytes()[cursor] {
570
+ b'\\' => cursor += 2,
571
+ byte if byte == quote => return Some(cursor),
572
+ _ => cursor += 1,
573
+ }
574
+ }
575
+ None
576
+ }
577
+
578
+ fn push_preserved_whitespace(output: &mut String, span: &str) {
579
+ for ch in span.chars() {
580
+ if ch == '\n' || ch == '\r' {
581
+ output.push(ch);
582
+ } else {
583
+ output.push(' ');
584
+ }
585
+ }
586
+ }
587
+
588
+ fn next_char_boundary(source: &str, start: usize) -> Option<usize> {
589
+ source
590
+ .get(start..)?
591
+ .chars()
592
+ .next()
593
+ .map(|ch| start + ch.len_utf8())
594
+ }
595
+
596
+ fn is_identifier_start(ch: char) -> bool {
597
+ ch == '_' || ch.is_ascii_alphabetic()
598
+ }
599
+
600
+ fn is_identifier_char(ch: char) -> bool {
601
+ is_identifier_start(ch) || ch.is_ascii_digit()
602
+ }
603
+
604
+ #[cfg(test)]
605
+ mod tests {
606
+ use std::path::Path;
607
+
608
+ use super::{DartParseError, parse_dart_source_strict};
609
+
610
+ #[test]
611
+ fn strict_parse_normalizes_primary_constructor_headers() -> Result<(), DartParseError> {
612
+ let source = "\
613
+ class Point(
614
+ var int x,
615
+ var int y
616
+ ) extends Shape with Traceable implements Drawable;
617
+
618
+ class const ConstPoint._(final int x, final int y) {
619
+ final int z;
620
+ this : z = x + y;
621
+ }
622
+
623
+ enum const Tone(final String label) {
624
+ quiet('q');
625
+ }
626
+ ";
627
+
628
+ let parsed = parse_dart_source_strict(Path::new("lib/modern.dart"), source)?;
629
+
630
+ assert!(!parsed.tree().root_node().has_error());
631
+ assert!(parsed.source().contains("class Point"));
632
+ assert!(parsed.source().contains("ConstPoint"));
633
+ assert!(parsed.source().contains("extends Shape"));
634
+ assert!(parsed.source().contains("Tone"));
635
+
636
+ Ok(())
637
+ }
638
+
639
+ #[test]
640
+ fn strict_parse_normalizes_current_dart_shorthands() -> Result<(), DartParseError> {
641
+ let source = "\
642
+ enum Color { red, blue }
643
+
644
+ Widget build(Banner? banner, List<Widget>? extras) {
645
+ final key = banner?.key;
646
+ final color = .red;
647
+ return Column(children: [
648
+ ?banner,
649
+ ...?extras,
650
+ Button.style(.filled),
651
+ ]);
652
+ }
653
+ ";
654
+
655
+ let parsed = parse_dart_source_strict(Path::new("lib/current.dart"), source)?;
656
+
657
+ assert!(!parsed.tree().root_node().has_error());
658
+
659
+ Ok(())
660
+ }
661
+
662
+ #[test]
663
+ fn strict_parse_keeps_unrecoverable_syntax_errors() {
664
+ let error = parse_dart_source_strict(Path::new("lib/bad.dart"), "class {")
665
+ .err()
666
+ .map(|error| error.to_string());
667
+
668
+ assert_eq!(
669
+ error.as_deref(),
670
+ Some("Dart syntax errors found in lib/bad.dart")
671
+ );
672
+ }
673
+ }