1use std::path::Path;
20
21use oxc_ast::ast::{
22 BinaryExpression, BinaryOperator, Class, ClassElement, ExportDefaultDeclarationKind,
23 Expression, MethodDefinitionKind, Program, PropertyKey, Statement, TSEnumDeclaration,
24 TSEnumMemberName, TSExternalModuleDeclaration, TSGlobalDeclaration, TSNamespaceDeclaration,
25 UnaryOperator,
26};
27use oxc_ast_visit::Visit;
28use oxc_span::GetSpan;
29use oxc_syntax::symbol::SymbolFlags;
30use rustc_hash::{FxHashMap, FxHashSet};
31
32use crate::source_edits::{MergeKind, SpanEdit, declaration_names, script_blocks};
33
34#[derive(Debug, Clone, PartialEq, Eq)]
36pub enum PostEditViolation {
37 DoesNotParse,
39 DeclarationLost {
41 name: String,
43 },
44 MemberLost {
47 container: String,
49 member: String,
51 },
52 ValueChanged {
54 enumeration: String,
56 member: String,
58 },
59 UnresolvedReference {
61 name: String,
63 },
64 ExportInUse {
68 name: String,
70 },
71 MixedExport {
76 name: String,
78 },
79 ImportLeftBehind {
81 name: String,
83 },
84}
85
86impl PostEditViolation {
87 #[must_use]
89 pub fn describe(&self) -> String {
90 match self {
91 Self::DoesNotParse => "the edited file does not parse".to_owned(),
92 Self::DeclarationLost { name } => format!("the edit also removes `{name}`"),
93 Self::MemberLost { container, member } => {
94 format!("the edit also removes `{member}` of `{container}`")
95 }
96 Self::ValueChanged {
97 enumeration,
98 member,
99 } => format!("the edit changes the value of `{enumeration}.{member}`"),
100 Self::UnresolvedReference { name } => {
101 format!("the edit leaves a reference to `{name}` without a declaration")
102 }
103 Self::ExportInUse { name } => {
104 format!("the edit removes the export `{name}`, and other code still uses it")
105 }
106 Self::MixedExport { name } => {
107 format!("the edit leaves merged declarations of `{name}` partly exported")
108 }
109 Self::ImportLeftBehind { name } => {
110 format!("the edit leaves the import of `{name}` with no use")
111 }
112 }
113 }
114}
115
116#[derive(Debug, Clone)]
118enum ConstValue {
119 Number(f64),
120 Text(String),
121}
122
123impl PartialEq for ConstValue {
124 fn eq(&self, other: &Self) -> bool {
125 match (self, other) {
126 (Self::Number(left), Self::Number(right)) => left.to_bits() == right.to_bits(),
127 (Self::Text(left), Self::Text(right)) => left == right,
128 _ => false,
129 }
130 }
131}
132
133type ContainerKey = (bool, String);
136
137#[derive(Debug)]
139struct Container {
140 span: (u32, u32),
142 members: Vec<(String, (u32, u32))>,
144 values: FxHashMap<String, Option<ConstValue>>,
147}
148
149#[derive(Debug, Default)]
151pub struct SourceFacts {
152 containers: FxHashMap<ContainerKey, Vec<Container>>,
154 exports: FxHashSet<String>,
155 unresolved: FxHashSet<String>,
156 import_uses: FxHashMap<String, usize>,
158 listed_locals: FxHashSet<String>,
160 exported_declarations: FxHashMap<String, FxHashSet<MergeKind>>,
163 local_declarations: FxHashMap<String, FxHashSet<MergeKind>>,
165}
166
167impl SourceFacts {
168 #[must_use]
172 pub fn collect(path: &Path, source: &str) -> Option<Self> {
173 let mut facts = Self::default();
174 for block in script_blocks(path, source)? {
175 let text = block.text.as_ref();
176 let parsed = fallow_extract::parse_bounded(text, || {
177 let allocator = oxc_allocator::Allocator::default();
178 let parsed = oxc_parser::Parser::new(&allocator, text, block.source_type).parse();
179 if parsed.fatal_error || parsed.diagnostics.has_errors() {
180 return false;
181 }
182 let mut collector = FactCollector {
183 text,
184 offset: block.offset,
185 ambient_depth: usize::from(block.source_type.is_typescript_definition()),
186 facts: &mut facts,
187 };
188 collector.visit_program(&parsed.program);
189 collect_module_facts(&parsed.program, &mut facts);
190 true
191 });
192 if parsed != Some(true) {
193 return None;
194 }
195 }
196 Some(facts)
197 }
198
199 #[must_use]
202 pub fn exports(&self) -> &FxHashSet<String> {
203 &self.exports
204 }
205
206 pub fn check(
215 &self,
216 path: &Path,
217 after: &str,
218 deleted: &[(u32, u32)],
219 ) -> Result<Self, PostEditViolation> {
220 let facts = Self::collect(path, after).ok_or(PostEditViolation::DoesNotParse)?;
221 let inside = |span: (u32, u32)| {
222 deleted
223 .iter()
224 .any(|&(start, end)| start <= span.0 && span.1 <= end)
225 };
226 let mut keys: Vec<&ContainerKey> = self.containers.keys().collect();
227 keys.sort();
228 for key in keys {
229 let now = facts.containers.get(key).map_or(&[][..], Vec::as_slice);
230 for (before, now) in pair_containers(&key.1, &self.containers[key], now, &inside)? {
231 compare_members(&key.1, before, now, &inside)?;
232 if key.0 {
233 compare_values(&key.1, before, now)?;
234 }
235 }
236 }
237 let mut unresolved: Vec<&String> = facts.unresolved.difference(&self.unresolved).collect();
238 unresolved.sort();
239 if let Some(name) = unresolved.first() {
240 return Err(PostEditViolation::UnresolvedReference {
241 name: (*name).clone(),
242 });
243 }
244 let split_before = self.split_merges();
245 let mut mixed: Vec<&String> = facts
246 .split_merges()
247 .into_iter()
248 .filter(|name| !split_before.contains(name))
249 .collect();
250 mixed.sort();
251 if let Some(name) = mixed.first() {
252 return Err(PostEditViolation::MixedExport {
253 name: (*name).clone(),
254 });
255 }
256 let mut imports: Vec<(&String, &usize)> = facts.import_uses.iter().collect();
257 imports.sort();
258 for (name, uses) in imports {
259 let used_before = self.import_uses.get(name).is_some_and(|before| *before > 0);
260 if *uses == 0
261 && used_before
262 && self.listed_locals.contains(name)
263 && !facts.listed_locals.contains(name)
264 {
265 return Err(PostEditViolation::ImportLeftBehind { name: name.clone() });
266 }
267 }
268 Ok(facts)
269 }
270
271 fn split_merges(&self) -> Vec<&String> {
274 self.exported_declarations
275 .iter()
276 .filter(|(name, exported)| {
277 self.local_declarations.get(*name).is_some_and(|local| {
278 exported
279 .iter()
280 .any(|kind| local.iter().any(|other| kind.merges_with(*other)))
281 })
282 })
283 .map(|(name, _)| name)
284 .collect()
285 }
286
287 pub fn check_edits(
294 &self,
295 path: &Path,
296 source: &str,
297 edits: &[SpanEdit],
298 removable: impl Fn(&str) -> bool,
299 ) -> Result<(), PostEditViolation> {
300 let after = apply(source, edits).ok_or(PostEditViolation::DoesNotParse)?;
301 let deleted: Vec<(u32, u32)> = edits
302 .iter()
303 .filter(|edit| edit.replacement.is_empty())
304 .map(|edit| (edit.start, edit.end))
305 .collect();
306 let facts = self.check(path, &after, &deleted)?;
307 let mut removed: Vec<&String> = self.exports.difference(&facts.exports).collect();
308 removed.sort();
309 match removed.into_iter().find(|name| !removable(name)) {
310 Some(name) => Err(PostEditViolation::ExportInUse { name: name.clone() }),
311 None => Ok(()),
312 }
313 }
314}
315
316#[must_use]
319pub fn checks_file(path: &Path) -> bool {
320 script_blocks(path, "").is_some()
321}
322
323pub fn check_edits(
335 path: &Path,
336 source: &str,
337 edits: &[SpanEdit],
338 removable: impl Fn(&str) -> bool,
339) -> Result<(), PostEditViolation> {
340 SourceFacts::collect(path, source)
341 .ok_or(PostEditViolation::DoesNotParse)?
342 .check_edits(path, source, edits, removable)
343}
344
345fn apply(source: &str, edits: &[SpanEdit]) -> Option<String> {
348 let mut sorted: Vec<&SpanEdit> = edits.iter().collect();
349 sorted.sort_by_key(|edit| (edit.start, edit.end));
350 let mut result = String::with_capacity(source.len());
351 let mut position = 0;
352 for edit in sorted {
353 let (start, end) = (edit.start as usize, edit.end as usize);
354 if start < position || end < start {
355 return None;
356 }
357 result.push_str(source.get(position..start)?);
358 result.push_str(&edit.replacement);
359 source.get(start..end)?;
360 position = end;
361 }
362 result.push_str(source.get(position..)?);
363 Some(result)
364}
365
366fn pair_containers<'c>(
371 name: &str,
372 before: &'c [Container],
373 now: &'c [Container],
374 inside: &impl Fn((u32, u32)) -> bool,
375) -> Result<Vec<(&'c Container, &'c Container)>, PostEditViolation> {
376 let lost = || PostEditViolation::DeclarationLost {
377 name: name.to_owned(),
378 };
379 let required = before
380 .iter()
381 .filter(|container| !inside(container.span))
382 .count();
383 if now.len() < required || now.len() > before.len() {
384 return Err(lost());
385 }
386 let mut removed = before.len() - now.len();
387 let kept = before.iter().filter(|container| {
388 if removed > 0 && inside(container.span) {
389 removed -= 1;
390 return false;
391 }
392 true
393 });
394 Ok(kept.zip(now).collect())
395}
396
397fn compare_members(
402 container: &str,
403 before: &Container,
404 now: &Container,
405 inside: &impl Fn((u32, u32)) -> bool,
406) -> Result<(), PostEditViolation> {
407 let lost = |member: &str| PostEditViolation::MemberLost {
408 container: container.to_owned(),
409 member: member.to_owned(),
410 };
411 let mut remaining = before.members.iter();
412 for (key, _) in &now.members {
413 if !remaining.any(|(before_key, _)| before_key == key) {
414 return Err(lost(key));
415 }
416 }
417 let mut required: FxHashMap<&str, usize> = FxHashMap::default();
418 for (key, span) in &before.members {
419 if !inside(*span) {
420 *required.entry(key.as_str()).or_default() += 1;
421 }
422 }
423 let mut present: FxHashMap<&str, usize> = FxHashMap::default();
424 for (key, _) in &now.members {
425 *present.entry(key.as_str()).or_default() += 1;
426 }
427 let mut keys: Vec<(&str, usize)> = required.into_iter().collect();
428 keys.sort_unstable();
429 match keys
430 .into_iter()
431 .find(|(key, count)| present.get(key).copied().unwrap_or_default() < *count)
432 {
433 Some((key, _)) => Err(lost(key)),
434 None => Ok(()),
435 }
436}
437
438fn compare_values(
441 enumeration: &str,
442 before: &Container,
443 now: &Container,
444) -> Result<(), PostEditViolation> {
445 for (key, _) in &now.members {
446 let Some(Some(old)) = before.values.get(key) else {
447 continue;
448 };
449 if now.values.get(key).and_then(Option::as_ref) != Some(old) {
450 return Err(PostEditViolation::ValueChanged {
451 enumeration: enumeration.to_owned(),
452 member: key.clone(),
453 });
454 }
455 }
456 Ok(())
457}
458
459fn add_merge(map: &mut FxHashMap<String, FxHashSet<MergeKind>>, name: &str, kind: MergeKind) {
460 map.entry(name.to_owned()).or_default().insert(kind);
461}
462
463fn record_statement(statement: &Statement<'_>, facts: &mut SourceFacts) {
465 match statement {
466 Statement::ExportDeclaration(export) => {
467 if let Some((_, names)) = declaration_names(&export.declaration) {
468 if let Some(kind) = MergeKind::of(&export.declaration) {
469 for name in &names {
470 add_merge(&mut facts.exported_declarations, name, kind);
471 }
472 }
473 facts.exports.extend(names);
474 }
475 }
476 Statement::ExportDefaultDeclaration(export) => {
477 facts.exports.insert("default".to_owned());
478 if let Some((name, kind)) = named_default(&export.declaration) {
479 add_merge(&mut facts.exported_declarations, name, kind);
480 }
481 }
482 Statement::ExportNamedDeclaration(export) => {
483 for specifier in &export.specifiers {
484 facts.exports.insert(specifier.exported.name().to_string());
485 facts
486 .listed_locals
487 .insert(specifier.local.name().to_string());
488 }
489 }
490 Statement::ExportFromDeclaration(export) => {
491 for specifier in &export.specifiers {
492 facts.exports.insert(specifier.exported.name().to_string());
493 }
494 }
495 Statement::ExportAllDeclaration(export) => {
496 if let Some(exported) = &export.exported {
497 facts.exports.insert(exported.name().to_string());
498 }
499 }
500 other => {
501 if let Some(declaration) = other.as_declaration()
502 && let Some(kind) = MergeKind::of(declaration)
503 && let Some((_, names)) = declaration_names(declaration)
504 {
505 for name in &names {
506 add_merge(&mut facts.local_declarations, name, kind);
507 }
508 }
509 }
510 }
511}
512
513fn named_default<'a>(
516 declaration: &'a ExportDefaultDeclarationKind<'_>,
517) -> Option<(&'a str, MergeKind)> {
518 match declaration {
519 ExportDefaultDeclarationKind::FunctionDeclaration(function) => function
520 .id
521 .as_ref()
522 .map(|id| (id.name.as_str(), MergeKind::Function)),
523 ExportDefaultDeclarationKind::ClassDeclaration(class) => class
524 .id
525 .as_ref()
526 .map(|id| (id.name.as_str(), MergeKind::Class)),
527 _ => None,
528 }
529}
530
531fn collect_module_facts(program: &Program<'_>, facts: &mut SourceFacts) {
534 for statement in &program.body {
535 record_statement(statement, facts);
536 }
537 let semantic = oxc_semantic::SemanticBuilder::new().build(program);
538 let scoping = semantic.semantic.scoping();
539 facts.unresolved.extend(
540 scoping
541 .root_unresolved_references()
542 .keys()
543 .map(ToString::to_string),
544 );
545 let root = scoping.root_scope_id();
546 for symbol in scoping.symbol_ids() {
547 if scoping.symbol_scope_id(symbol) != root
548 || !scoping.symbol_flags(symbol).contains(SymbolFlags::Import)
549 {
550 continue;
551 }
552 *facts
553 .import_uses
554 .entry(scoping.symbol_name(symbol).to_string())
555 .or_default() += scoping.get_resolved_reference_ids(symbol).len();
556 }
557}
558
559struct FactCollector<'t, 'f> {
561 text: &'t str,
562 offset: u32,
563 ambient_depth: usize,
566 facts: &'f mut SourceFacts,
567}
568
569impl FactCollector<'_, '_> {
570 fn span(&self, span: oxc_span::Span) -> (u32, u32) {
571 (span.start + self.offset, span.end + self.offset)
572 }
573
574 fn slice(&self, span: oxc_span::Span) -> &str {
575 self.text
576 .get(span.start as usize..span.end as usize)
577 .unwrap_or_default()
578 }
579
580 fn push(&mut self, is_enum: bool, name: String, container: Container) {
581 self.facts
582 .containers
583 .entry((is_enum, name))
584 .or_default()
585 .push(container);
586 }
587
588 fn within(&mut self, declare: bool, walk: impl FnOnce(&mut Self)) {
589 let depth = usize::from(declare);
590 self.ambient_depth += depth;
591 walk(self);
592 self.ambient_depth -= depth;
593 }
594
595 fn element_key(&self, element: &ClassElement<'_>) -> String {
596 let key = |kind: &str, is_static: bool, computed: bool, key: &PropertyKey<'_>| {
597 let text = self.slice(key.span());
598 format!(
599 "{kind}{}{}{text}",
600 if is_static { " static " } else { " " },
601 if computed { "computed " } else { "" },
602 )
603 };
604 match element {
605 ClassElement::MethodDefinition(method) => {
606 let kind = match method.kind {
607 MethodDefinitionKind::Constructor => "constructor",
608 MethodDefinitionKind::Method => "method",
609 MethodDefinitionKind::Get => "get",
610 MethodDefinitionKind::Set => "set",
611 };
612 key(kind, method.r#static, method.computed, &method.key)
613 }
614 ClassElement::PropertyDefinition(property) => key(
615 "property",
616 property.r#static,
617 property.computed,
618 &property.key,
619 ),
620 ClassElement::AccessorProperty(accessor) => key(
621 "accessor",
622 accessor.r#static,
623 accessor.computed,
624 &accessor.key,
625 ),
626 ClassElement::StaticBlock(_) => "static block".to_owned(),
627 ClassElement::TSIndexSignature(signature) => {
628 format!("index {}", self.slice(signature.span))
629 }
630 }
631 }
632
633 fn enum_member_key(&self, name: &TSEnumMemberName<'_>) -> String {
634 match name {
635 TSEnumMemberName::Identifier(id) => id.name.to_string(),
636 TSEnumMemberName::String(name) | TSEnumMemberName::ComputedString(name) => name
637 .value
638 .as_str()
639 .map_or_else(|| name.value.display().to_string(), str::to_owned),
640 TSEnumMemberName::ComputedTemplateString(template) => {
641 self.slice(template.span).to_owned()
642 }
643 }
644 }
645}
646
647impl<'a> Visit<'a> for FactCollector<'_, '_> {
648 fn visit_class(&mut self, it: &Class<'a>) {
649 let members = it
650 .body
651 .body
652 .iter()
653 .map(|element| (self.element_key(element), self.span(element.span())))
654 .collect();
655 let name = it
656 .id
657 .as_ref()
658 .map_or_else(String::new, |id| id.name.to_string());
659 let container = Container {
660 span: self.span(it.span),
661 members,
662 values: FxHashMap::default(),
663 };
664 self.push(false, name, container);
665 oxc_ast_visit::walk::walk_class(self, it);
666 }
667
668 fn visit_ts_enum_declaration(&mut self, it: &TSEnumDeclaration<'a>) {
669 let ambient = (it.declare || self.ambient_depth > 0) && !it.r#const;
670 let name = it.id.name.to_string();
671 let mut known: FxHashMap<String, ConstValue> = FxHashMap::default();
672 let mut previous: Option<Option<ConstValue>> = None;
673 let mut members = Vec::with_capacity(it.body.members.len());
674 let mut values = FxHashMap::default();
675 for member in &it.body.members {
676 let key = self.enum_member_key(&member.id);
677 let value = match &member.initializer {
678 Some(initializer) => evaluate(initializer, &name, &known),
679 None if ambient => None,
680 None => match &previous {
681 None => Some(ConstValue::Number(0.0)),
682 Some(Some(ConstValue::Number(number))) => {
683 Some(ConstValue::Number(number + 1.0))
684 }
685 Some(_) => None,
686 },
687 };
688 if let Some(value) = &value {
689 known.insert(key.clone(), value.clone());
690 }
691 previous = Some(value.clone());
692 values.insert(key.clone(), value);
693 members.push((key, self.span(member.span)));
694 }
695 let container = Container {
696 span: self.span(it.span),
697 members,
698 values,
699 };
700 self.push(true, name, container);
701 oxc_ast_visit::walk::walk_ts_enum_declaration(self, it);
702 }
703
704 fn visit_ts_external_module_declaration(&mut self, it: &TSExternalModuleDeclaration<'a>) {
705 self.within(it.declare, |collector| {
706 oxc_ast_visit::walk::walk_ts_external_module_declaration(collector, it);
707 });
708 }
709
710 fn visit_ts_namespace_declaration(&mut self, it: &TSNamespaceDeclaration<'a>) {
711 self.within(it.declare, |collector| {
712 oxc_ast_visit::walk::walk_ts_namespace_declaration(collector, it);
713 });
714 }
715
716 fn visit_ts_global_declaration(&mut self, it: &TSGlobalDeclaration<'a>) {
717 self.within(it.declare, |collector| {
718 oxc_ast_visit::walk::walk_ts_global_declaration(collector, it);
719 });
720 }
721}
722
723fn evaluate(
727 expression: &Expression<'_>,
728 enumeration: &str,
729 known: &FxHashMap<String, ConstValue>,
730) -> Option<ConstValue> {
731 match expression {
732 Expression::NumericLiteral(literal) => Some(ConstValue::Number(literal.value)),
733 Expression::StringLiteral(literal) => {
734 Some(ConstValue::Text(literal.value.as_str()?.to_owned()))
735 }
736 Expression::TemplateLiteral(template) if template.expressions.is_empty() => {
737 let quasi = template.quasis.first()?;
738 Some(ConstValue::Text(quasi.value.cooked?.as_str()?.to_owned()))
739 }
740 Expression::ParenthesizedExpression(inner) => {
741 evaluate(&inner.expression, enumeration, known)
742 }
743 Expression::Identifier(identifier) => known.get(identifier.name.as_str()).cloned(),
744 Expression::StaticMemberExpression(member) => match &member.object {
745 Expression::Identifier(object) if object.name == enumeration => {
746 known.get(member.property.name.as_str()).cloned()
747 }
748 _ => None,
749 },
750 Expression::ComputedMemberExpression(member) => {
751 match (&member.object, &member.expression) {
752 (Expression::Identifier(object), Expression::StringLiteral(property))
753 if object.name == enumeration =>
754 {
755 known.get(property.value.as_str()?).cloned()
756 }
757 _ => None,
758 }
759 }
760 Expression::UnaryExpression(unary) => {
761 let ConstValue::Number(value) = evaluate(&unary.argument, enumeration, known)? else {
762 return None;
763 };
764 let result = match unary.operator {
765 UnaryOperator::UnaryPlus => value,
766 UnaryOperator::UnaryNegation => -value,
767 UnaryOperator::BitwiseNot => f64::from(!to_int32(value)),
768 _ => return None,
769 };
770 Some(ConstValue::Number(result))
771 }
772 Expression::BinaryExpression(binary) => evaluate_binary(binary, enumeration, known),
773 _ => None,
774 }
775}
776
777fn evaluate_binary(
778 binary: &BinaryExpression<'_>,
779 enumeration: &str,
780 known: &FxHashMap<String, ConstValue>,
781) -> Option<ConstValue> {
782 let left = evaluate(&binary.left, enumeration, known)?;
783 let right = evaluate(&binary.right, enumeration, known)?;
784 let (left, right) = match (left, right) {
785 (ConstValue::Number(left), ConstValue::Number(right)) => (left, right),
786 (ConstValue::Text(left), ConstValue::Text(right))
787 if binary.operator == BinaryOperator::Addition =>
788 {
789 return Some(ConstValue::Text(format!("{left}{right}")));
790 }
791 _ => return None,
792 };
793 let shift = |value: f64| to_int32(value).cast_unsigned() & 31;
794 let result = match binary.operator {
795 BinaryOperator::Addition => left + right,
796 BinaryOperator::Subtraction => left - right,
797 BinaryOperator::Multiplication => left * right,
798 BinaryOperator::Division => left / right,
799 BinaryOperator::Remainder => left % right,
800 BinaryOperator::Exponential => left.powf(right),
801 BinaryOperator::ShiftLeft => f64::from(to_int32(left).wrapping_shl(shift(right))),
802 BinaryOperator::ShiftRight => f64::from(to_int32(left).wrapping_shr(shift(right))),
803 BinaryOperator::ShiftRightZeroFill => {
804 f64::from(to_int32(left).cast_unsigned().wrapping_shr(shift(right)))
805 }
806 BinaryOperator::BitwiseAnd => f64::from(to_int32(left) & to_int32(right)),
807 BinaryOperator::BitwiseOR => f64::from(to_int32(left) | to_int32(right)),
808 BinaryOperator::BitwiseXOR => f64::from(to_int32(left) ^ to_int32(right)),
809 _ => return None,
810 };
811 Some(ConstValue::Number(result))
812}
813
814fn to_int32(value: f64) -> i32 {
816 const TWO_32: f64 = 4_294_967_296.0;
817 if !value.is_finite() {
818 return 0;
819 }
820 let wrapped = value.trunc().rem_euclid(TWO_32);
821 #[expect(
822 clippy::cast_possible_truncation,
823 clippy::cast_sign_loss,
824 reason = "rem_euclid gives an integer in 0..2^32"
825 )]
826 let unsigned = wrapped as u32;
827 unsigned.cast_signed()
828}
829
830#[cfg(test)]
831#[path = "post_edit_tests.rs"]
832mod tests;