Skip to main content

fallow_engine/
post_edit.rs

1//! The check that each source edit keeps the meaning of the code that it
2//! keeps.
3//!
4//! `fallow fix`, the language server and the CI review comments remove code
5//! that the analysis found unused. A guard before an edit protects one known
6//! shape. This module compares the facts of the text before and after the
7//! edit, so that an edit of a new shape gets the same check:
8//!
9//! - the edited text parses;
10//! - each kept class element and enum member is still there, in the same
11//!   class or enum and in the same order;
12//! - each kept enum member keeps its constant value;
13//! - no reference that resolved before the edit is unresolved after it;
14//! - no import stays behind whose binding only a removed export list used.
15//!
16//! [`SourceFacts::exports`] gives the exported names of the text, so that a
17//! caller can also check the exports that other files use.
18
19use 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/// Why the check refuses an edit.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub enum PostEditViolation {
37    /// The edited text does not parse.
38    DoesNotParse,
39    /// A class or an enum outside the edited bytes is not in the edited text.
40    DeclarationLost {
41        /// The name of the class or the enum.
42        name: String,
43    },
44    /// A class element or an enum member outside the edited bytes is not in
45    /// the edited text, for example because the edit joined two members.
46    MemberLost {
47        /// The name of the class or the enum.
48        container: String,
49        /// The key of the lost member.
50        member: String,
51    },
52    /// A kept enum member has a different constant value.
53    ValueChanged {
54        /// The name of the enum.
55        enumeration: String,
56        /// The name of the member.
57        member: String,
58    },
59    /// A reference that resolved before the edit is unresolved after it.
60    UnresolvedReference {
61        /// The referenced name.
62        name: String,
63    },
64    /// The edit removes an export that other code still uses. The caller
65    /// reports this violation: the check of one file does not know the other
66    /// files.
67    ExportInUse {
68        /// The exported name.
69        name: String,
70    },
71    /// Declarations of one name that TypeScript merges are partly exported,
72    /// as after the removal of `export` from one overload signature, or from
73    /// a class but not from its interface. TypeScript requires all
74    /// declarations of one merge to be exported, or none.
75    MixedExport {
76        /// The declared name.
77        name: String,
78    },
79    /// An import stays, but the export list that used its binding is gone.
80    ImportLeftBehind {
81        /// The local name of the import binding.
82        name: String,
83    },
84}
85
86impl PostEditViolation {
87    /// A short text for a person.
88    #[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/// The constant value of an enum member.
117#[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
133/// The kind (`true` for an enum) and the name of a class or an enum. An
134/// anonymous class has the name `""`.
135type ContainerKey = (bool, String);
136
137/// One class or enum of a text.
138#[derive(Debug)]
139struct Container {
140    /// The bytes of the whole declaration, in file offsets.
141    span: (u32, u32),
142    /// The key and the bytes of each member, in source order.
143    members: Vec<(String, (u32, u32))>,
144    /// The constant value of each member of an enum, by member key. `None`
145    /// when the syntax does not give a constant value.
146    values: FxHashMap<String, Option<ConstValue>>,
147}
148
149/// The facts of one file text that the check compares.
150#[derive(Debug, Default)]
151pub struct SourceFacts {
152    /// The classes and enums of each kind and name, in source order.
153    containers: FxHashMap<ContainerKey, Vec<Container>>,
154    exports: FxHashSet<String>,
155    unresolved: FxHashSet<String>,
156    /// The number of references of each top-level import binding.
157    import_uses: FxHashMap<String, usize>,
158    /// The local names that an `export { ... }` list without `from` names.
159    listed_locals: FxHashSet<String>,
160    /// The merge kinds of the exported top-level declarations of each name,
161    /// including a named `export default function` or `class`.
162    exported_declarations: FxHashMap<String, FxHashSet<MergeKind>>,
163    /// The merge kinds of the top-level declarations without `export`.
164    local_declarations: FxHashMap<String, FxHashSet<MergeKind>>,
165}
166
167impl SourceFacts {
168    /// The facts of `source`, the text of the file at `path`. `None` for a
169    /// file type that the engine does not parse here, or for a text with a
170    /// parse error.
171    #[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    /// Each name that the text exports. A default export has the name
200    /// `default`.
201    #[must_use]
202    pub fn exports(&self) -> &FxHashSet<String> {
203        &self.exports
204    }
205
206    /// Check `after`, the edited text of the file at `path`. `deleted` holds
207    /// the byte ranges of the deletions in the text before the edit. A member
208    /// or a declaration inside one of these ranges may go; each other member
209    /// must stay.
210    ///
211    /// # Errors
212    ///
213    /// The first violation that the check finds.
214    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    /// The names with an exported and a local declaration that TypeScript
272    /// merges, which it rejects (TS2383, TS2395).
273    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    /// Check `edits` of `source`, the text that these facts describe. See
288    /// [`check_edits`].
289    ///
290    /// # Errors
291    ///
292    /// The first violation that the check finds.
293    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/// True for a file type that the check parses: JavaScript, TypeScript, and
317/// the script blocks of Vue, Svelte and Astro files.
318#[must_use]
319pub fn checks_file(path: &Path) -> bool {
320    script_blocks(path, "").is_some()
321}
322
323/// Check the edit of one file: `edits` applied to `source`, the text of the
324/// file at `path`. `removable` tells which exported names the edit may
325/// remove. The language server and the CI review comments call this check
326/// before they offer an edit. `fallow fix` runs the same check over all the
327/// files that it edits.
328///
329/// # Errors
330///
331/// The first violation that the check finds. An edit list with overlapping
332/// or invalid ranges, or a `source` that does not parse, gives
333/// [`PostEditViolation::DoesNotParse`].
334pub 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
345/// `source` with `edits` applied, or `None` when two edits overlap or an edit
346/// is not a valid range of `source`.
347fn 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
366/// Pair each class or enum of one kind and name after the edit with its
367/// declaration before the edit. A declaration inside a deletion may go. When
368/// fewer declarations stay, the first ones inside a deletion are the removed
369/// ones.
370fn 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
397/// Check that the member keys of `now` keep the order of `before`, and that
398/// each member outside a deletion is still there. Two members can share a
399/// key, such as an overload signature and its implementation, so the check
400/// counts the members of each key.
401fn 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
438/// Check that each enum member with a known value in `before` has the same
439/// value in `now`.
440fn 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
463/// Record the exports and the merge kinds of one top-level statement.
464fn 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
513/// The name and the merge kind of a named `export default function` or
514/// `export default class`.
515fn 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
531/// Collect the exports, the unresolved references and the import uses of one
532/// parsed block.
533fn 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
559/// Collects the classes and enums of one block.
560struct FactCollector<'t, 'f> {
561    text: &'t str,
562    offset: u32,
563    /// The number of enclosing ambient contexts: a declaration file, and each
564    /// `declare` module, namespace or global block around the visit position.
565    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
723/// The constant value of an enum initializer, as TypeScript computes it for
724/// a constant enum expression. `known` holds the values of the members
725/// before it. `None` for each other expression.
726fn 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
814/// The ECMAScript `ToInt32` conversion of a number.
815fn 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;