dart-decimate 0.0.39 → 0.0.41

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.
@@ -53,8 +53,24 @@ pub(crate) fn parse_dart_source_strict<'source>(
53
53
  path: &Path,
54
54
  source: &'source str,
55
55
  ) -> Result<ParsedDart<'source>, DartParseError> {
56
+ if has_malformed_concise_constructor(source) {
57
+ return Err(DartParseError::Syntax {
58
+ path: path.to_path_buf(),
59
+ });
60
+ }
61
+
56
62
  let original = parse_raw(path, source)?;
57
63
  if !original.root_node().has_error() {
64
+ let mut normalized = source.to_owned();
65
+ if normalize_concise_constructors(&mut normalized) {
66
+ let tree = parse_raw(path, &normalized)?;
67
+ if !tree.root_node().has_error() {
68
+ return Ok(ParsedDart {
69
+ tree,
70
+ source: Cow::Owned(normalized),
71
+ });
72
+ }
73
+ }
58
74
  return Ok(ParsedDart {
59
75
  tree: original,
60
76
  source: Cow::Borrowed(source),
@@ -86,6 +102,16 @@ pub(crate) fn parse_dart_source_lossy<'source>(
86
102
  ) -> Result<ParsedDart<'source>, DartParseError> {
87
103
  let original = parse_raw(path, source)?;
88
104
  if !original.root_node().has_error() {
105
+ let mut normalized = source.to_owned();
106
+ if normalize_concise_constructors(&mut normalized) {
107
+ let tree = parse_raw(path, &normalized)?;
108
+ if !tree.root_node().has_error() {
109
+ return Ok(ParsedDart {
110
+ tree,
111
+ source: Cow::Owned(normalized),
112
+ });
113
+ }
114
+ }
89
115
  return Ok(ParsedDart {
90
116
  tree: original,
91
117
  source: Cow::Borrowed(source),
@@ -125,11 +151,349 @@ fn normalize_modern_dart_compatibility(source: &str) -> Option<String> {
125
151
  let mut normalized = normalize_primary_constructors(source);
126
152
  let mut output = normalized.take().unwrap_or_else(|| source.to_owned());
127
153
  let mut changed = output != source;
154
+ changed |= normalize_concise_constructors(&mut output);
128
155
  changed |= normalize_dot_shorthands(&mut output);
129
156
  changed |= normalize_null_aware_collection_elements(&mut output);
130
157
  changed.then_some(output)
131
158
  }
132
159
 
160
+ fn normalize_concise_constructors(source: &mut String) -> bool {
161
+ let mut replacements = Vec::new();
162
+ let mut cursor = 0;
163
+
164
+ while let Some((keyword_start, keyword)) = find_next_class_like_header(source, cursor) {
165
+ let Some((class_name, body_start, body_end)) =
166
+ class_like_body(source, keyword_start + keyword.len(), keyword)
167
+ else {
168
+ cursor = keyword_start + keyword.len();
169
+ continue;
170
+ };
171
+ push_concise_constructor_replacements(
172
+ source,
173
+ body_start + 1,
174
+ body_end,
175
+ &class_name,
176
+ &mut replacements,
177
+ );
178
+ cursor = body_end + 1;
179
+ }
180
+
181
+ apply_text_replacements(source, replacements)
182
+ }
183
+
184
+ fn has_malformed_concise_constructor(source: &str) -> bool {
185
+ let mut cursor = 0;
186
+
187
+ while let Some((keyword_start, keyword)) = find_next_class_like_header(source, cursor) {
188
+ let Some((_, body_start, body_end)) =
189
+ class_like_body(source, keyword_start + keyword.len(), keyword)
190
+ else {
191
+ cursor = keyword_start + keyword.len();
192
+ continue;
193
+ };
194
+ let mut member_cursor = body_start + 1;
195
+ while let Some((member_start, member_end)) =
196
+ next_class_like_member(source, member_cursor, body_end)
197
+ {
198
+ if malformed_concise_constructor_member(source, member_start, member_end) {
199
+ return true;
200
+ }
201
+ member_cursor = member_end;
202
+ }
203
+ cursor = body_end + 1;
204
+ }
205
+
206
+ false
207
+ }
208
+
209
+ fn class_like_body(
210
+ source: &str,
211
+ cursor: usize,
212
+ keyword: &'static str,
213
+ ) -> Option<(String, usize, usize)> {
214
+ let mut name_start = skip_whitespace(source, cursor)?;
215
+ if matches!(keyword, "class" | "enum") && starts_keyword(source, name_start, "const") {
216
+ name_start = skip_whitespace(source, name_start + "const".len())?;
217
+ }
218
+ let name_end = identifier_end(source, name_start)?;
219
+ let name = source[name_start..name_end].to_owned();
220
+ let (body_start, terminator) = find_header_terminator(source, name_end)?;
221
+ if terminator != b'{' {
222
+ return None;
223
+ }
224
+ let body_end = matching_delimiter(source, body_start, b'{', b'}')?;
225
+ Some((name, body_start, body_end))
226
+ }
227
+
228
+ fn find_next_class_like_header(source: &str, start: usize) -> Option<(usize, &'static str)> {
229
+ let mut cursor = start;
230
+ while cursor < source.len() {
231
+ if let Some(after) = skip_non_code(source, cursor) {
232
+ cursor = after;
233
+ continue;
234
+ }
235
+ if starts_keyword(source, cursor, "class") {
236
+ return Some((cursor, "class"));
237
+ }
238
+ if starts_keyword(source, cursor, "enum") {
239
+ return Some((cursor, "enum"));
240
+ }
241
+ if starts_keyword(source, cursor, "extension") {
242
+ let type_start = skip_whitespace(source, cursor + "extension".len())?;
243
+ if starts_keyword(source, type_start, "type") {
244
+ return Some((type_start, "type"));
245
+ }
246
+ }
247
+ cursor = next_char_boundary(source, cursor)?;
248
+ }
249
+ None
250
+ }
251
+
252
+ fn push_concise_constructor_replacements(
253
+ source: &str,
254
+ start: usize,
255
+ end: usize,
256
+ class_name: &str,
257
+ replacements: &mut Vec<(usize, usize, String)>,
258
+ ) {
259
+ let mut cursor = start;
260
+ while let Some((member_start, member_end)) = next_class_like_member(source, cursor, end) {
261
+ if let Some((replacement_start, replacement_end, replacement)) =
262
+ concise_constructor_replacement(source, member_start, member_end, class_name)
263
+ {
264
+ replacements.push((replacement_start, replacement_end, replacement));
265
+ }
266
+ cursor = member_end;
267
+ }
268
+ }
269
+
270
+ fn next_class_like_member(source: &str, start: usize, end: usize) -> Option<(usize, usize)> {
271
+ let member_start = skip_member_trivia(source, start, end);
272
+ if member_start >= end {
273
+ return None;
274
+ }
275
+
276
+ let bytes = source.as_bytes();
277
+ let mut cursor = member_start;
278
+ let mut delimiters = Vec::new();
279
+ while cursor < end {
280
+ if let Some(after) = skip_non_code(source, cursor) {
281
+ cursor = after;
282
+ continue;
283
+ }
284
+ match bytes[cursor] {
285
+ b'{' => delimiters.push(b'}'),
286
+ b'(' => delimiters.push(b')'),
287
+ b'[' => delimiters.push(b']'),
288
+ b'}' | b')' | b']' => {
289
+ if delimiters.last().copied() == Some(bytes[cursor]) {
290
+ delimiters.pop();
291
+ if delimiters.is_empty() && bytes[cursor] == b'}' {
292
+ return Some((member_start, cursor + 1));
293
+ }
294
+ }
295
+ }
296
+ b';' if delimiters.is_empty() => return Some((member_start, cursor + 1)),
297
+ _ => {}
298
+ }
299
+ cursor += 1;
300
+ }
301
+
302
+ Some((member_start, end))
303
+ }
304
+
305
+ fn concise_constructor_replacement(
306
+ source: &str,
307
+ start: usize,
308
+ end: usize,
309
+ class_name: &str,
310
+ ) -> Option<(usize, usize, String)> {
311
+ let mut cursor = skip_member_trivia(source, start, end);
312
+ cursor = skip_member_annotations(source, cursor, end)?;
313
+
314
+ while let Some(after) = skip_member_modifier(source, cursor, end) {
315
+ cursor = after;
316
+ }
317
+
318
+ let (keyword_end, factory) = if starts_keyword(source, cursor, "factory") {
319
+ (cursor + "factory".len(), true)
320
+ } else if starts_keyword(source, cursor, "new") {
321
+ (cursor + "new".len(), false)
322
+ } else {
323
+ return None;
324
+ };
325
+ let (suffix, after_suffix) = concise_constructor_suffix(source, keyword_end, end)?;
326
+ let replacement = if factory {
327
+ format!("factory {class_name}{suffix}")
328
+ } else {
329
+ format!("{class_name}{suffix}")
330
+ };
331
+ Some((cursor, after_suffix, replacement))
332
+ }
333
+
334
+ fn skip_member_modifier(source: &str, cursor: usize, end: usize) -> Option<usize> {
335
+ for modifier in ["augment", "const", "external"] {
336
+ if starts_keyword(source, cursor, modifier) {
337
+ let after = cursor + modifier.len();
338
+ return (after <= end).then(|| skip_member_trivia(source, after, end));
339
+ }
340
+ }
341
+ None
342
+ }
343
+
344
+ fn malformed_concise_constructor_member(source: &str, start: usize, end: usize) -> bool {
345
+ let mut cursor = skip_member_trivia(source, start, end);
346
+ let Some(after_annotations) = skip_member_annotations(source, cursor, end) else {
347
+ return false;
348
+ };
349
+ cursor = after_annotations;
350
+
351
+ while let Some(after) = skip_member_modifier(source, cursor, end) {
352
+ cursor = after;
353
+ }
354
+
355
+ let keyword_end = if starts_keyword(source, cursor, "factory") {
356
+ cursor + "factory".len()
357
+ } else if starts_keyword(source, cursor, "new") {
358
+ cursor + "new".len()
359
+ } else {
360
+ return false;
361
+ };
362
+ let suffix_start = skip_member_trivia(source, keyword_end, end);
363
+ if suffix_start >= end || source.as_bytes().get(suffix_start) == Some(&b'(') {
364
+ return false;
365
+ }
366
+ let Some(suffix_end) = identifier_end(source, suffix_start) else {
367
+ return false;
368
+ };
369
+ let after_suffix = skip_member_trivia(source, suffix_end, end);
370
+
371
+ after_suffix < end
372
+ && source.as_bytes().get(after_suffix) == Some(&b'(')
373
+ && is_reserved_dart_word(&source[suffix_start..suffix_end])
374
+ }
375
+
376
+ fn is_reserved_dart_word(word: &str) -> bool {
377
+ matches!(
378
+ word,
379
+ "assert"
380
+ | "break"
381
+ | "case"
382
+ | "catch"
383
+ | "class"
384
+ | "const"
385
+ | "continue"
386
+ | "default"
387
+ | "do"
388
+ | "else"
389
+ | "enum"
390
+ | "extends"
391
+ | "false"
392
+ | "final"
393
+ | "finally"
394
+ | "for"
395
+ | "if"
396
+ | "in"
397
+ | "is"
398
+ | "new"
399
+ | "null"
400
+ | "rethrow"
401
+ | "return"
402
+ | "super"
403
+ | "switch"
404
+ | "this"
405
+ | "throw"
406
+ | "true"
407
+ | "try"
408
+ | "var"
409
+ | "void"
410
+ | "while"
411
+ | "with"
412
+ )
413
+ }
414
+
415
+ fn skip_member_annotations(source: &str, mut cursor: usize, end: usize) -> Option<usize> {
416
+ loop {
417
+ cursor = skip_member_trivia(source, cursor, end);
418
+ if source.as_bytes().get(cursor).copied() != Some(b'@') {
419
+ return Some(cursor);
420
+ }
421
+ cursor += 1;
422
+ cursor = skip_member_trivia(source, cursor, end);
423
+ cursor = identifier_end(source, cursor)?;
424
+ loop {
425
+ cursor = skip_member_trivia(source, cursor, end);
426
+ if source.as_bytes().get(cursor).copied() != Some(b'.') {
427
+ break;
428
+ }
429
+ cursor += 1;
430
+ cursor = skip_member_trivia(source, cursor, end);
431
+ cursor = identifier_end(source, cursor)?;
432
+ }
433
+ cursor = skip_member_trivia(source, cursor, end);
434
+ if source.as_bytes().get(cursor).copied() == Some(b'(') {
435
+ cursor = matching_delimiter(source, cursor, b'(', b')')? + 1;
436
+ }
437
+ }
438
+ }
439
+
440
+ fn skip_member_trivia(source: &str, mut cursor: usize, end: usize) -> usize {
441
+ while cursor < end {
442
+ if source.as_bytes()[cursor].is_ascii_whitespace() {
443
+ cursor += 1;
444
+ continue;
445
+ }
446
+ if (source.as_bytes().get(cursor..cursor + 2) == Some(b"//")
447
+ || source.as_bytes().get(cursor..cursor + 2) == Some(b"/*"))
448
+ && let Some(after) = skip_non_code(source, cursor)
449
+ {
450
+ cursor = after;
451
+ continue;
452
+ }
453
+ break;
454
+ }
455
+ cursor.min(end)
456
+ }
457
+
458
+ fn concise_constructor_suffix(source: &str, cursor: usize, end: usize) -> Option<(String, usize)> {
459
+ let suffix_start = skip_member_trivia(source, cursor, end);
460
+ if suffix_start >= end {
461
+ return None;
462
+ }
463
+ if source.as_bytes().get(suffix_start).copied() == Some(b'(') {
464
+ return Some((
465
+ preserved_line_breaks(&source[cursor..suffix_start]),
466
+ suffix_start,
467
+ ));
468
+ }
469
+ let suffix_end = identifier_end(source, suffix_start)?;
470
+ if suffix_end > end {
471
+ return None;
472
+ }
473
+ let after_suffix = skip_member_trivia(source, suffix_end, end);
474
+ if after_suffix >= end {
475
+ return None;
476
+ }
477
+ if source.as_bytes().get(after_suffix).copied() != Some(b'(') {
478
+ return None;
479
+ }
480
+ Some((
481
+ format!(
482
+ "{}.{}{}",
483
+ preserved_line_breaks(&source[cursor..suffix_start]),
484
+ &source[suffix_start..suffix_end],
485
+ preserved_line_breaks(&source[suffix_end..after_suffix]),
486
+ ),
487
+ after_suffix,
488
+ ))
489
+ }
490
+
491
+ fn preserved_line_breaks(span: &str) -> String {
492
+ span.chars()
493
+ .filter(|character| matches!(character, '\n' | '\r'))
494
+ .collect()
495
+ }
496
+
133
497
  fn normalize_primary_constructors(source: &str) -> Option<String> {
134
498
  let mut replacements = Vec::new();
135
499
  let mut cursor = 0;
@@ -175,11 +539,10 @@ fn primary_constructor_header(
175
539
  let class_name = source[name_start..name_end].to_owned();
176
540
  let mut header_cursor = skip_whitespace(source, name_end).unwrap_or(name_end);
177
541
 
178
- if source.as_bytes().get(header_cursor).copied() == Some(b'<') {
179
- if let Some(type_params_end) = matching_delimiter(source, header_cursor, b'<', b'>') {
180
- header_cursor =
181
- skip_whitespace(source, type_params_end + 1).unwrap_or(type_params_end + 1);
182
- }
542
+ if source.as_bytes().get(header_cursor).copied() == Some(b'<')
543
+ && let Some(type_params_end) = matching_delimiter(source, header_cursor, b'<', b'>')
544
+ {
545
+ header_cursor = skip_whitespace(source, type_params_end + 1).unwrap_or(type_params_end + 1);
183
546
  }
184
547
 
185
548
  let replacement_start = primary_constructor_replacement_start(source, &mut header_cursor)?;
@@ -268,18 +631,16 @@ fn push_constructor_body_replacement(
268
631
  replacements: &mut Vec<Replacement>,
269
632
  header: &PrimaryConstructorHeader,
270
633
  ) {
271
- if let Some((terminator_start, _)) = header.terminator {
272
- if let Some(body_end) = matching_delimiter(source, terminator_start, b'{', b'}') {
273
- if let Some(this_start) =
274
- find_primary_constructor_body(source, terminator_start + 1, body_end)
275
- {
276
- replacements.push(Replacement {
277
- start: this_start,
278
- end: this_start + "this".len(),
279
- kind: ReplacementKind::ConstructorBody(header.class_name.clone()),
280
- });
281
- }
282
- }
634
+ if let Some((terminator_start, _)) = header.terminator
635
+ && let Some(body_end) = matching_delimiter(source, terminator_start, b'{', b'}')
636
+ && let Some(this_start) =
637
+ find_primary_constructor_body(source, terminator_start + 1, body_end)
638
+ {
639
+ replacements.push(Replacement {
640
+ start: this_start,
641
+ end: this_start + "this".len(),
642
+ kind: ReplacementKind::ConstructorBody(header.class_name.clone()),
643
+ });
283
644
  }
284
645
  }
285
646
 
@@ -321,6 +682,10 @@ fn normalize_dot_shorthands(source: &mut String) -> bool {
321
682
  let mut replacements = Vec::new();
322
683
  let mut cursor = 0;
323
684
  while cursor < bytes.len() {
685
+ if let Some(after) = skip_non_code(source, cursor) {
686
+ cursor = after;
687
+ continue;
688
+ }
324
689
  if bytes[cursor] != b'.' {
325
690
  cursor += 1;
326
691
  continue;
@@ -372,11 +737,18 @@ fn is_dot_shorthand_start(bytes: &[u8], cursor: usize) -> bool {
372
737
  fn normalize_null_aware_collection_elements(source: &mut String) -> bool {
373
738
  let bytes = source.as_bytes().to_vec();
374
739
  let mut replacements = Vec::new();
375
- for cursor in 0..bytes.len() {
740
+ let mut cursor = 0;
741
+ while cursor < bytes.len() {
742
+ if let Some(after) = skip_non_code(source, cursor) {
743
+ cursor = after;
744
+ continue;
745
+ }
376
746
  if bytes[cursor] != b'?' || !is_null_aware_collection_marker(&bytes, cursor) {
747
+ cursor += 1;
377
748
  continue;
378
749
  }
379
750
  replacements.push((cursor, cursor + 1, " ".to_owned()));
751
+ cursor += 1;
380
752
  }
381
753
  apply_text_replacements(source, replacements)
382
754
  }
@@ -412,11 +784,14 @@ fn find_header_terminator(source: &str, start: usize) -> Option<(usize, u8)> {
412
784
  let bytes = source.as_bytes();
413
785
  let mut cursor = start;
414
786
  while cursor < bytes.len() {
787
+ if let Some(after) = skip_non_code(source, cursor) {
788
+ cursor = after;
789
+ continue;
790
+ }
415
791
  match bytes[cursor] {
416
792
  b'{' | b';' => return Some((cursor, bytes[cursor])),
417
793
  b'(' => cursor = matching_delimiter(source, cursor, b'(', b')')?,
418
794
  b'<' => cursor = matching_delimiter(source, cursor, b'<', b'>')?,
419
- b'\'' | b'"' => cursor = skip_quoted(source, cursor)?,
420
795
  _ => {}
421
796
  }
422
797
  cursor += 1;
@@ -471,10 +846,13 @@ fn find_primary_constructor_body(source: &str, start: usize, end: usize) -> Opti
471
846
  let mut depth = 0usize;
472
847
  let mut cursor = start;
473
848
  while cursor < end {
849
+ if let Some(after) = skip_non_code(source, cursor) {
850
+ cursor = after;
851
+ continue;
852
+ }
474
853
  match bytes[cursor] {
475
854
  b'{' | b'(' | b'[' => depth += 1,
476
855
  b'}' | b')' | b']' => depth = depth.saturating_sub(1),
477
- b'\'' | b'"' => cursor = skip_quoted(source, cursor)?,
478
856
  _ if depth == 0 && starts_keyword(source, cursor, "this") => {
479
857
  let after_this = skip_whitespace(source, cursor + "this".len())?;
480
858
  if matches!(
@@ -494,6 +872,10 @@ fn find_primary_constructor_body(source: &str, start: usize, end: usize) -> Opti
494
872
  fn find_next_header_keyword(source: &str, start: usize) -> Option<(usize, &'static str)> {
495
873
  let mut cursor = start;
496
874
  while cursor < source.len() {
875
+ if let Some(after) = skip_non_code(source, cursor) {
876
+ cursor = after;
877
+ continue;
878
+ }
497
879
  if starts_keyword(source, cursor, "class") {
498
880
  return Some((cursor, "class"));
499
881
  }
@@ -555,6 +937,10 @@ fn matching_delimiter(source: &str, start: usize, open: u8, close: u8) -> Option
555
937
  let mut depth = 0usize;
556
938
  let mut cursor = start;
557
939
  while cursor < bytes.len() {
940
+ if let Some(after) = skip_non_code(source, cursor) {
941
+ cursor = after;
942
+ continue;
943
+ }
558
944
  match bytes[cursor] {
559
945
  byte if byte == open => depth += 1,
560
946
  byte if byte == close => {
@@ -563,7 +949,6 @@ fn matching_delimiter(source: &str, start: usize, open: u8, close: u8) -> Option
563
949
  return Some(cursor);
564
950
  }
565
951
  }
566
- b'\'' | b'"' => cursor = skip_quoted(source, cursor)?,
567
952
  _ => {}
568
953
  }
569
954
  cursor += 1;
@@ -571,17 +956,65 @@ fn matching_delimiter(source: &str, start: usize, open: u8, close: u8) -> Option
571
956
  None
572
957
  }
573
958
 
574
- fn skip_quoted(source: &str, start: usize) -> Option<usize> {
575
- let quote = source.as_bytes().get(start).copied()?;
576
- let mut cursor = start + 1;
577
- while cursor < source.len() {
578
- match source.as_bytes()[cursor] {
579
- b'\\' => cursor += 2,
580
- byte if byte == quote => return Some(cursor),
581
- _ => cursor += 1,
959
+ fn skip_non_code(source: &str, start: usize) -> Option<usize> {
960
+ let bytes = source.as_bytes();
961
+ if bytes.get(start..start + 2) == Some(b"//") {
962
+ return Some(
963
+ bytes[start + 2..]
964
+ .iter()
965
+ .position(|byte| *byte == b'\n')
966
+ .map_or(bytes.len(), |offset| start + 2 + offset),
967
+ );
968
+ }
969
+ if bytes.get(start..start + 2) == Some(b"/*") {
970
+ let mut depth = 1usize;
971
+ let mut cursor = start + 2;
972
+ while cursor < bytes.len() {
973
+ if bytes.get(cursor..cursor + 2) == Some(b"/*") {
974
+ depth += 1;
975
+ cursor += 2;
976
+ } else if bytes.get(cursor..cursor + 2) == Some(b"*/") {
977
+ depth -= 1;
978
+ cursor += 2;
979
+ if depth == 0 {
980
+ return Some(cursor);
981
+ }
982
+ } else {
983
+ cursor += 1;
984
+ }
582
985
  }
986
+ return Some(bytes.len());
583
987
  }
584
- None
988
+
989
+ let raw = matches!(bytes.get(start), Some(b'r' | b'R'))
990
+ && matches!(bytes.get(start + 1), Some(b'\'' | b'"'))
991
+ && !source
992
+ .get(..start)
993
+ .and_then(|prefix| prefix.chars().next_back())
994
+ .is_some_and(is_identifier_char);
995
+ let quote_start = if raw { start + 1 } else { start };
996
+ let quote = bytes.get(quote_start).copied()?;
997
+ if !matches!(quote, b'\'' | b'"') {
998
+ return None;
999
+ }
1000
+ let triple = bytes.get(quote_start..quote_start + 3) == Some(&[quote, quote, quote]);
1001
+ let delimiter_len = if triple { 3 } else { 1 };
1002
+ let mut cursor = quote_start + delimiter_len;
1003
+ while cursor < bytes.len() {
1004
+ if !raw && bytes[cursor] == b'\\' {
1005
+ cursor = (cursor + 2).min(bytes.len());
1006
+ continue;
1007
+ }
1008
+ if triple {
1009
+ if bytes.get(cursor..cursor + 3) == Some(&[quote, quote, quote]) {
1010
+ return Some(cursor + 3);
1011
+ }
1012
+ } else if bytes[cursor] == quote {
1013
+ return Some(cursor + 1);
1014
+ }
1015
+ cursor += 1;
1016
+ }
1017
+ Some(bytes.len())
585
1018
  }
586
1019
 
587
1020
  fn push_preserved_whitespace(output: &mut String, span: &str) {
@@ -614,7 +1047,9 @@ fn is_identifier_char(ch: char) -> bool {
614
1047
  mod tests {
615
1048
  use std::path::Path;
616
1049
 
617
- use super::{DartParseError, parse_dart_source_strict};
1050
+ use super::{
1051
+ DartParseError, normalize_modern_dart_compatibility, parse_dart_source_strict, parse_raw,
1052
+ };
618
1053
 
619
1054
  #[test]
620
1055
  fn strict_parse_normalizes_primary_constructor_headers() -> Result<(), DartParseError> {
@@ -668,6 +1103,152 @@ Widget build(Banner? banner, List<Widget>? extras) {
668
1103
  Ok(())
669
1104
  }
670
1105
 
1106
+ #[test]
1107
+ fn strict_parse_normalizes_concise_constructor_forms() -> Result<(), DartParseError> {
1108
+ let source = r"
1109
+ class BodyDefault {
1110
+ new() {}
1111
+ }
1112
+
1113
+ class BodyNamed {
1114
+ new named() {}
1115
+ }
1116
+
1117
+ class ConstDefault {
1118
+ const new();
1119
+ }
1120
+
1121
+ class ConstNamed {
1122
+ const new named();
1123
+ }
1124
+
1125
+ class InitializerDefault {
1126
+ new() : this.other();
1127
+ InitializerDefault.other();
1128
+ }
1129
+
1130
+ class InitializerNamed {
1131
+ new named() : this();
1132
+ InitializerNamed();
1133
+ }
1134
+
1135
+ class ConstInitializerDefault {
1136
+ const new() : this.other();
1137
+ const ConstInitializerDefault.other();
1138
+ }
1139
+
1140
+ class ConstInitializerNamed {
1141
+ const new named() : this();
1142
+ const ConstInitializerNamed();
1143
+ }
1144
+
1145
+ class FactoryBodyDefault {
1146
+ factory() { return FactoryBodyDefault._(); }
1147
+ FactoryBodyDefault._();
1148
+ }
1149
+
1150
+ class FactoryBodyNamed {
1151
+ factory named() { return FactoryBodyNamed._(); }
1152
+ FactoryBodyNamed._();
1153
+ }
1154
+
1155
+ class FactoryRedirectDefault {
1156
+ factory() = FactoryRedirectDefault._;
1157
+ FactoryRedirectDefault._();
1158
+ }
1159
+
1160
+ class FactoryRedirectNamed {
1161
+ factory named() = FactoryRedirectNamed._;
1162
+ FactoryRedirectNamed._();
1163
+ }
1164
+
1165
+ class ConstFactoryRedirectDefault {
1166
+ const factory() = ConstFactoryRedirectDefault._;
1167
+ const ConstFactoryRedirectDefault._();
1168
+ }
1169
+
1170
+ class ConstFactoryRedirectNamed {
1171
+ const factory named() = ConstFactoryRedirectNamed._;
1172
+ const ConstFactoryRedirectNamed._();
1173
+ }
1174
+ ";
1175
+
1176
+ let parsed = parse_dart_source_strict(Path::new("lib/constructors.dart"), source)?;
1177
+
1178
+ assert!(!parsed.tree().root_node().has_error());
1179
+ for expected in [
1180
+ "BodyDefault() {}",
1181
+ "BodyNamed.named() {}",
1182
+ "const ConstDefault();",
1183
+ "const ConstNamed.named();",
1184
+ "InitializerDefault() : this.other();",
1185
+ "InitializerNamed.named() : this();",
1186
+ "const ConstInitializerDefault() : this.other();",
1187
+ "const ConstInitializerNamed.named() : this();",
1188
+ "factory FactoryBodyDefault()",
1189
+ "factory FactoryBodyNamed.named()",
1190
+ "factory FactoryRedirectDefault() =",
1191
+ "factory FactoryRedirectNamed.named() =",
1192
+ "const factory ConstFactoryRedirectDefault() =",
1193
+ "const factory ConstFactoryRedirectNamed.named() =",
1194
+ ] {
1195
+ assert!(
1196
+ parsed.source().contains(expected),
1197
+ "missing normalized constructor {expected:?}"
1198
+ );
1199
+ }
1200
+
1201
+ Ok(())
1202
+ }
1203
+
1204
+ #[test]
1205
+ fn compatibility_normalizer_never_changes_comments_or_strings() {
1206
+ let source = r#"
1207
+ class Example {
1208
+ // new fake() {} .center ?value
1209
+ /* nested /* new nested() {} */ .center */
1210
+ static const text = "new quoted() {} .center ?value";
1211
+ static const raw = r'''factory raw() {} .center ?value''';
1212
+ new() {}
1213
+ }
1214
+ "#;
1215
+
1216
+ let Some(normalized) = normalize_modern_dart_compatibility(source) else {
1217
+ panic!("code was not normalized");
1218
+ };
1219
+
1220
+ assert!(normalized.contains("// new fake() {} .center ?value"));
1221
+ assert!(normalized.contains("/* nested /* new nested() {} */ .center */"));
1222
+ assert!(normalized.contains("\"new quoted() {} .center ?value\""));
1223
+ assert!(normalized.contains("r'''factory raw() {} .center ?value'''"));
1224
+ assert!(normalized.contains("Example() {}"));
1225
+ }
1226
+
1227
+ #[test]
1228
+ fn concise_constructor_normalization_accepts_intertoken_comments() {
1229
+ let source = r"
1230
+ class Commented {
1231
+ @deprecated
1232
+ const new /* before name */
1233
+ named // before parameters
1234
+ ();
1235
+ factory /* before name */ create
1236
+ /* before parameters */ () => Commented.named();
1237
+ }
1238
+ ";
1239
+ let Some(normalized) = normalize_modern_dart_compatibility(source) else {
1240
+ panic!("commented constructors were not normalized");
1241
+ };
1242
+ let Ok(tree) = parse_raw(Path::new("commented.dart"), &normalized) else {
1243
+ panic!("normalized commented constructors did not parse");
1244
+ };
1245
+
1246
+ assert!(!tree.root_node().has_error());
1247
+ assert!(normalized.contains("const Commented\n.named\n();"));
1248
+ assert!(normalized.contains("factory Commented.create\n()"));
1249
+ assert_eq!(normalized.lines().count(), source.lines().count());
1250
+ }
1251
+
671
1252
  #[test]
672
1253
  fn strict_parse_keeps_unrecoverable_syntax_errors() {
673
1254
  let error = parse_dart_source_strict(Path::new("lib/bad.dart"), "class {")
@@ -679,4 +1260,99 @@ Widget build(Banner? banner, List<Widget>? extras) {
679
1260
  Some("Dart syntax errors found in lib/bad.dart")
680
1261
  );
681
1262
  }
1263
+
1264
+ #[test]
1265
+ fn strict_parse_normalizes_concise_constructors_even_when_raw_parse_is_clean()
1266
+ -> Result<(), DartParseError> {
1267
+ let source = "class Clean { new() {} }";
1268
+ let raw = parse_raw(Path::new("clean.dart"), source)?;
1269
+ assert!(!raw.root_node().has_error());
1270
+
1271
+ let strict = parse_dart_source_strict(Path::new("clean.dart"), source)?;
1272
+ assert!(!strict.tree().root_node().has_error());
1273
+ assert!(strict.source().contains("Clean()"));
1274
+
1275
+ let lossy = super::parse_dart_source_lossy(Path::new("clean.dart"), source)?;
1276
+ assert!(!lossy.tree().root_node().has_error());
1277
+ assert!(lossy.source().contains("Clean()"));
1278
+ Ok(())
1279
+ }
1280
+
1281
+ #[test]
1282
+ fn concise_constructor_normalization_is_limited_to_top_level_members() {
1283
+ let source = r"
1284
+ class Owner {
1285
+ new() {}
1286
+ new named() {}
1287
+ const new cached();
1288
+ factory() {}
1289
+ factory namedFactory() {}
1290
+ const factory constFactory() = Target.cached;
1291
+
1292
+ final field = new Target();
1293
+ static final qualified = Target.new();
1294
+ void method() {
1295
+ final local = new Target();
1296
+ }
1297
+ }
1298
+
1299
+ mixin class MixinOwner {
1300
+ new() {}
1301
+ }
1302
+
1303
+ enum Tone {
1304
+ quiet;
1305
+ new() {}
1306
+ }
1307
+
1308
+ extension type UserId(int value) {
1309
+ new() : this(0);
1310
+ }
1311
+ ";
1312
+ let Some(normalized) = normalize_modern_dart_compatibility(source) else {
1313
+ panic!("constructor source was not normalized");
1314
+ };
1315
+ let Ok(tree) = parse_raw(Path::new("normalized.dart"), &normalized) else {
1316
+ panic!("normalized source did not parse");
1317
+ };
1318
+ assert!(!tree.root_node().has_error());
1319
+
1320
+ for expected in [
1321
+ "Owner() {}",
1322
+ "Owner.named() {}",
1323
+ "const Owner.cached();",
1324
+ "factory Owner() {}",
1325
+ "factory Owner.namedFactory() {}",
1326
+ "const factory Owner.constFactory() = Target.cached;",
1327
+ "MixinOwner() {}",
1328
+ "Tone() {}",
1329
+ "UserId() : this(0);",
1330
+ ] {
1331
+ assert!(
1332
+ normalized.contains(expected),
1333
+ "missing normalized {expected:?}"
1334
+ );
1335
+ }
1336
+ for untouched in [
1337
+ "final field = new Target();",
1338
+ "static final qualified = Target.new();",
1339
+ "final local = new Target();",
1340
+ ] {
1341
+ assert!(normalized.contains(untouched), "changed {untouched:?}");
1342
+ }
1343
+ }
1344
+
1345
+ #[test]
1346
+ fn strict_parse_rejects_reserved_concise_constructor_names() {
1347
+ for source in [
1348
+ "class Invalid { new new() {} }",
1349
+ "class Invalid { factory class() = Invalid._; Invalid._(); }",
1350
+ "class Invalid { const new void(); }",
1351
+ ] {
1352
+ assert!(matches!(
1353
+ parse_dart_source_strict(Path::new("lib/invalid.dart"), source),
1354
+ Err(DartParseError::Syntax { .. })
1355
+ ));
1356
+ }
1357
+ }
682
1358
  }