Skip to main content

fallow_engine/
source_edits.rs

1//! The byte spans of the top-level export statements of a file, and the
2//! edits that remove their `export` keyword.
3//!
4//! `fallow fix`, the language server and the CI review comments change
5//! source text. A line rule cannot tell which `export` keyword of a line
6//! belongs to a name, which names one keyword exports, or where a
7//! declaration ends. This module parses the file and answers these
8//! questions from the syntax tree. A file that does not parse gets no
9//! index, and so no edit.
10
11use std::path::Path;
12
13use oxc_ast::ast::{
14    ClassBody, Declaration, ExportDefaultDeclarationKind, Expression, Program, Statement,
15    TSEnumBody, TSEnumDeclaration, TSEnumMemberName, TSExternalModuleDeclaration,
16    TSGlobalDeclaration, TSNamespaceDeclaration, UnaryOperator,
17};
18use oxc_ast_visit::Visit;
19use oxc_span::{GetSpan, SourceType};
20
21/// One replacement of a byte range of the source text.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct SpanEdit {
24    /// The byte offset of the first replaced byte.
25    pub start: u32,
26    /// The byte offset after the last replaced byte.
27    pub end: u32,
28    /// The new text. Empty for a deletion.
29    pub replacement: String,
30}
31
32/// Why the index gives no statement for a request.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum EditRefusal {
35    /// No export statement on the line binds the name.
36    NameNotFound,
37    /// More than one export statement matches, and the column selects none.
38    Ambiguous,
39    /// The removal of an enum member changes the value of a kept member, and
40    /// the index does not know the old value, so it cannot keep it.
41    UnknownValue,
42}
43
44/// The form of one export statement.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum ExportStatementKind {
47    /// `export const`, `export let`, `export var`.
48    Variable,
49    /// `export enum`, `export const enum`, `export declare enum`.
50    Enum,
51    /// Each other `export <declaration>`.
52    Declaration,
53    /// `export default function name` or `export default class Name`.
54    NamedDefault,
55    /// Each other `export default`: no name, an interface, or an expression.
56    OtherDefault,
57}
58
59/// A declaration form that TypeScript merges with other declarations of the
60/// same name. All declarations of one merge must be exported, or none
61/// (TS2383 for function overloads, TS2395 for each other merge).
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
63pub enum MergeKind {
64    /// A function declaration or an overload signature.
65    Function,
66    /// A class declaration.
67    Class,
68    /// A namespace or module declaration with a name.
69    Namespace,
70    /// An interface declaration.
71    Interface,
72    /// An enum declaration.
73    Enum,
74}
75
76impl MergeKind {
77    /// The merge kind of `declaration`, or `None` for a form that TypeScript
78    /// does not merge under the export rule, such as a variable or a type
79    /// alias.
80    #[must_use]
81    pub(crate) fn of(declaration: &Declaration<'_>) -> Option<Self> {
82        match declaration {
83            Declaration::FunctionDeclaration(_) => Some(Self::Function),
84            Declaration::ClassDeclaration(_) => Some(Self::Class),
85            Declaration::TSNamespaceDeclaration(_) => Some(Self::Namespace),
86            Declaration::TSInterfaceDeclaration(_) => Some(Self::Interface),
87            Declaration::TSEnumDeclaration(_) => Some(Self::Enum),
88            _ => None,
89        }
90    }
91
92    /// True when TypeScript merges a declaration of `self` with one of
93    /// `other`, so that both must have the same export. A value and a type
94    /// of one name, such as `const Foo` and `type Foo`, do not merge.
95    #[must_use]
96    pub fn merges_with(self, other: Self) -> bool {
97        use MergeKind::{Class, Enum, Function, Interface, Namespace};
98        matches!(
99            (self, other),
100            (Function | Namespace, Function)
101                | (Function | Class | Namespace | Enum, Namespace)
102                | (Namespace | Interface, Class)
103                | (Class | Interface, Interface)
104                | (Namespace | Enum, Enum)
105        )
106    }
107}
108
109/// One top-level `export <declaration>` or `export default` statement.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct ExportStatement {
112    /// The byte offset of the `export` keyword.
113    pub start: u32,
114    /// The byte offset after the end of the statement.
115    pub end: u32,
116    /// The form of the statement.
117    pub kind: ExportStatementKind,
118    /// Each name that the statement exports, in source order. A default
119    /// export has the one name `default`.
120    pub names: Vec<String>,
121    /// The merge kind of the declaration, or `None` when TypeScript does not
122    /// merge it with other declarations of the name.
123    pub merge: Option<MergeKind>,
124    /// The end of the text that the removal of the export deletes, or `None`
125    /// when the statement has no safe removal.
126    keyword_end: Option<u32>,
127}
128
129impl ExportStatement {
130    /// The edit that removes the export and keeps the declaration.
131    #[must_use]
132    pub fn keyword_edit(&self) -> Option<SpanEdit> {
133        self.keyword_end.map(|end| SpanEdit {
134            start: self.start,
135            end,
136            replacement: String::new(),
137        })
138    }
139}
140
141/// One class element or enum member.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub struct MemberSpan {
144    /// The byte offset of the first byte of the member.
145    pub start: u32,
146    /// The byte offset after the last byte of the member.
147    pub end: u32,
148    /// True for a class element whose static key another element of the same
149    /// class also has, such as an overload signature, its implementation, or
150    /// one half of a getter and setter pair. Always false for an enum member.
151    pub shares_its_key: bool,
152}
153
154/// One enum declaration with the spans of its members.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct EnumSpans {
157    /// The name of the enum.
158    pub name: String,
159    /// The byte offset after the `{` of the body.
160    pub body_start: u32,
161    /// The byte offset of the `}` of the body.
162    pub body_end: u32,
163    /// The name and the span of each member, in source order. A member with
164    /// a computed template name has no entry, and `complete` is then false.
165    pub members: Vec<(String, MemberSpan)>,
166    /// True when `members` has an entry for each member of the enum.
167    pub complete: bool,
168    /// The bytes of the whole declaration.
169    declaration: (u32, u32),
170    /// The value of each entry of `members`, in the same order.
171    values: Vec<MemberValue>,
172}
173
174/// The value of one enum member, as far as the syntax tells it.
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176struct MemberValue {
177    /// True when the member has an initializer.
178    initialized: bool,
179    /// The integer value of the member, or `None` when the syntax does not
180    /// give it: a computed or string initializer, a member that counts on
181    /// from such a member, or a member of a `declare enum`.
182    number: Option<i64>,
183}
184
185/// The largest integer that a JavaScript number holds exactly.
186const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
187
188/// The integer value of an enum initializer that is a number literal, with an
189/// optional sign.
190fn literal_integer(initializer: &Expression<'_>) -> Option<i64> {
191    let value = match initializer {
192        Expression::NumericLiteral(literal) => literal.value,
193        Expression::UnaryExpression(unary) => {
194            let Expression::NumericLiteral(literal) = &unary.argument else {
195                return None;
196            };
197            match unary.operator {
198                UnaryOperator::UnaryNegation => -literal.value,
199                UnaryOperator::UnaryPlus => literal.value,
200                _ => return None,
201            }
202        }
203        _ => return None,
204    };
205    if value.fract() != 0.0 || value.abs() > MAX_SAFE_INTEGER {
206        return None;
207    }
208    #[expect(
209        clippy::cast_possible_truncation,
210        reason = "the value is an integer inside the safe integer range"
211    )]
212    Some(value as i64)
213}
214
215/// The value of each member of `declaration`, in source order. A member
216/// without an initializer counts on from the member before it, and the first
217/// member is 0. The members of an ambient enum without `const` have no known
218/// value without an initializer, because TypeScript treats them as computed.
219/// An enum is ambient when it has `declare`, when it is inside a `declare`
220/// module, namespace or global block, or when it is in a declaration file
221/// (`in_ambient_context`).
222fn member_values(
223    declaration: &TSEnumDeclaration<'_>,
224    in_ambient_context: bool,
225) -> Vec<MemberValue> {
226    let ambient = (declaration.declare || in_ambient_context) && !declaration.r#const;
227    let mut previous: Option<Option<i64>> = None;
228    let mut values = Vec::with_capacity(declaration.body.members.len());
229    for member in &declaration.body.members {
230        let number = match &member.initializer {
231            Some(initializer) => literal_integer(initializer),
232            None if ambient => None,
233            None => match previous {
234                None => Some(0),
235                Some(before) => before.and_then(|value| value.checked_add(1)),
236            },
237        };
238        previous = Some(number);
239        values.push(MemberValue {
240            initialized: member.initializer.is_some(),
241            number,
242        });
243    }
244    values
245}
246
247/// The export statements and the class and enum members of one file text.
248pub struct SourceEditIndex {
249    statements: Vec<ExportStatement>,
250    members: Vec<MemberSpan>,
251    enums: Vec<EnumSpans>,
252    source: String,
253    line_starts: Vec<u32>,
254}
255
256impl SourceEditIndex {
257    /// Parse `source`, the text of the file at `path`.
258    ///
259    /// A JavaScript or TypeScript file is parsed as a whole. A Vue or Svelte
260    /// file is parsed per inline `<script>` block and an Astro file per
261    /// frontmatter block. Each offset is an offset into `source`.
262    ///
263    /// Returns `None` for a file type that the engine does not parse here,
264    /// or when a block does not parse without an error.
265    #[must_use]
266    pub fn parse(path: &Path, source: &str) -> Option<Self> {
267        let Parsed {
268            statements,
269            members,
270            enums,
271        } = parse_file(path, source)?;
272        let line_starts = std::iter::once(0)
273            .chain(
274                source
275                    .match_indices('\n')
276                    .map(|(offset, _)| u32::try_from(offset + 1).unwrap_or(u32::MAX)),
277            )
278            .collect();
279        Some(Self {
280            statements,
281            members,
282            enums,
283            source: source.to_owned(),
284            line_starts,
285        })
286    }
287
288    /// The statement that exports `name` on the 1-based `line`.
289    ///
290    /// `col` is the 0-based byte column of the name. It decides only between
291    /// two statements on one line that both export `name`.
292    ///
293    /// # Errors
294    ///
295    /// [`EditRefusal::NameNotFound`] when no statement of the line exports
296    /// `name`, and [`EditRefusal::Ambiguous`] when the column does not select
297    /// one of several such statements.
298    pub fn export_statement(
299        &self,
300        name: &str,
301        line: u32,
302        col: u32,
303    ) -> Result<&ExportStatement, EditRefusal> {
304        let line_idx = line.saturating_sub(1) as usize;
305        let candidates: Vec<&ExportStatement> = self
306            .statements
307            .iter()
308            .filter(|statement| {
309                let (first, last) = self.line_range(statement.start, statement.end);
310                (first..=last).contains(&line_idx)
311                    && statement.names.iter().any(|bound| bound == name)
312            })
313            .collect();
314        match candidates.as_slice() {
315            [] => Err(EditRefusal::NameNotFound),
316            [only] => Ok(only),
317            _ => {
318                let offset = self
319                    .line_starts
320                    .get(line_idx)
321                    .map(|start| start.saturating_add(col));
322                let mut containing = candidates.iter().filter(|statement| {
323                    offset.is_some_and(|offset| statement.start <= offset && offset < statement.end)
324                });
325                match (containing.next(), containing.next()) {
326                    (Some(statement), None) => Ok(statement),
327                    _ => Err(EditRefusal::Ambiguous),
328                }
329            }
330        }
331    }
332
333    /// Each export statement of the file, in source order.
334    #[must_use]
335    pub fn statements(&self) -> &[ExportStatement] {
336        &self.statements
337    }
338
339    /// The statements whose `export` keyword is on the 1-based `line`.
340    pub fn export_statements_on_line(&self, line: u32) -> impl Iterator<Item = &ExportStatement> {
341        let line_idx = line.saturating_sub(1) as usize;
342        self.statements
343            .iter()
344            .filter(move |statement| self.line_of(statement.start) == line_idx)
345    }
346
347    /// The class elements and enum members whose first byte is on the
348    /// 1-based `line`, at each depth of the file.
349    pub fn members_on_line(&self, line: u32) -> impl Iterator<Item = &MemberSpan> {
350        let line_idx = line.saturating_sub(1) as usize;
351        self.members
352            .iter()
353            .filter(move |member| self.line_of(member.start) == line_idx)
354    }
355
356    /// The enum declarations named `name`, at each depth.
357    pub fn enums_named<'s>(&'s self, name: &'s str) -> impl Iterator<Item = &'s EnumSpans> {
358        self.enums
359            .iter()
360            .filter(move |enumeration| enumeration.name == name)
361    }
362
363    /// The edits that remove `members` from the enum `name`. The 1-based
364    /// `line` of one member selects the enum when more than one has the name.
365    ///
366    /// A member that owns its lines is deleted with its lines, also an
367    /// initializer over several lines. A member that shares a line with
368    /// another member is deleted with one separating comma, and each other
369    /// byte of the enum stays as it is. A kept member without an initializer
370    /// that follows a removed member gets an initializer with its old value,
371    /// as in `Medium = 1`, so each kept member keeps its value.
372    ///
373    /// # Errors
374    ///
375    /// [`EditRefusal::NameNotFound`] when no complete enum of the name has
376    /// each member, [`EditRefusal::Ambiguous`] when `line` does not select
377    /// one enum, or when two edits overlap, and [`EditRefusal::UnknownValue`]
378    /// when a kept member needs an initializer and its old value is not a
379    /// known integer.
380    pub fn remove_enum_members(
381        &self,
382        name: &str,
383        members: &[&str],
384        line: u32,
385    ) -> Result<Vec<SpanEdit>, EditRefusal> {
386        let enumeration = self.select_enum(name, members, line)?;
387        let removed: Vec<bool> = enumeration
388            .members
389            .iter()
390            .map(|(member, _)| members.contains(&member.as_str()))
391            .collect();
392        let mut edits = Vec::new();
393        let mut packed = Vec::new();
394        for (position, (_, span)) in enumeration.members.iter().enumerate() {
395            if !removed[position] {
396                continue;
397            }
398            match self.owned_lines(*span) {
399                Some((start, end)) => edits.push(deletion(start, end)),
400                None => packed.push(position),
401            }
402        }
403        if !packed.is_empty() && removed.iter().all(|&gone| gone) {
404            let body = deletion(enumeration.body_start, enumeration.body_end);
405            if self.deletes_a_comment(enumeration, &removed, &body) {
406                return Err(EditRefusal::Ambiguous);
407            }
408            return Ok(vec![body]);
409        }
410        for run in neighbour_runs(&packed) {
411            let edit = packed_run_edit(enumeration, &removed, run);
412            if self.deletes_a_comment(enumeration, &removed, &edit) {
413                return Err(EditRefusal::Ambiguous);
414            }
415            edits.push(edit);
416        }
417        edits.extend(self.value_pins(enumeration, &removed)?);
418        edits.sort_by_key(|edit| edit.start);
419        if edits.windows(2).any(|pair| pair[1].start < pair[0].end) {
420            return Err(EditRefusal::Ambiguous);
421        }
422        Ok(edits)
423    }
424
425    /// The edits that give each kept member, whose value counts on from a
426    /// removed member, an initializer with its old value. The member keeps
427    /// its value after the removal, and each member after it too.
428    ///
429    /// # Errors
430    ///
431    /// [`EditRefusal::UnknownValue`] when such a member has no known value.
432    fn value_pins(
433        &self,
434        enumeration: &EnumSpans,
435        removed: &[bool],
436    ) -> Result<Vec<SpanEdit>, EditRefusal> {
437        let mut pins = Vec::new();
438        for (position, (_, span)) in enumeration.members.iter().enumerate() {
439            let shifts = position > 0
440                && removed[position - 1]
441                && !removed[position]
442                && !enumeration.values[position].initialized;
443            if !shifts {
444                continue;
445            }
446            let value = enumeration.values[position]
447                .number
448                .ok_or(EditRefusal::UnknownValue)?;
449            let key = self
450                .source
451                .get(span.start as usize..span.end as usize)
452                .ok_or(EditRefusal::UnknownValue)?;
453            pins.push(SpanEdit {
454                start: span.start,
455                end: span.end,
456                replacement: format!("{key} = {value}"),
457            });
458        }
459        Ok(pins)
460    }
461
462    /// True when `edit` deletes a comment that lies between members. The
463    /// text of a removed member, such as a string with `//` in it, does not
464    /// count.
465    fn deletes_a_comment(
466        &self,
467        enumeration: &EnumSpans,
468        removed: &[bool],
469        edit: &SpanEdit,
470    ) -> bool {
471        let mut cursor = edit.start;
472        let mut gaps = Vec::new();
473        for (position, (_, span)) in enumeration.members.iter().enumerate() {
474            if !removed[position] || span.end <= edit.start || span.start >= edit.end {
475                continue;
476            }
477            gaps.push((cursor, span.start.max(cursor)));
478            cursor = span.end;
479        }
480        gaps.push((cursor, edit.end));
481        gaps.iter().any(|&(start, end)| {
482            self.source
483                .get(start as usize..end.max(start) as usize)
484                .is_some_and(|gap| gap.contains("//") || gap.contains("/*"))
485        })
486    }
487
488    /// The enum named `name` whose declaration covers the 1-based `line`,
489    /// when exactly one does.
490    #[must_use]
491    pub fn enum_on_line(&self, name: &str, line: u32) -> Option<&EnumSpans> {
492        let line_idx = line.saturating_sub(1) as usize;
493        let mut covering = self.enums.iter().filter(|enumeration| {
494            let (start, end) = enumeration.declaration;
495            let (first, last) = self.line_range(start, end);
496            enumeration.name == name && (first..=last).contains(&line_idx)
497        });
498        match (covering.next(), covering.next()) {
499            (Some(enumeration), None) => Some(enumeration),
500            _ => None,
501        }
502    }
503
504    fn select_enum(
505        &self,
506        name: &str,
507        members: &[&str],
508        line: u32,
509    ) -> Result<&EnumSpans, EditRefusal> {
510        let candidates: Vec<&EnumSpans> = self
511            .enums
512            .iter()
513            .filter(|enumeration| enumeration.name == name)
514            .filter(|enumeration| {
515                members
516                    .iter()
517                    .all(|member| enumeration.members.iter().any(|(known, _)| known == member))
518            })
519            .collect();
520        let enumeration = match candidates.as_slice() {
521            [] => return Err(EditRefusal::NameNotFound),
522            [only] => *only,
523            _ => self
524                .enum_on_line(name, line)
525                .filter(|selected| {
526                    candidates
527                        .iter()
528                        .any(|candidate| std::ptr::eq(*candidate, *selected))
529                })
530                .ok_or(EditRefusal::Ambiguous)?,
531        };
532        if enumeration.complete {
533            Ok(enumeration)
534        } else {
535            Err(EditRefusal::NameNotFound)
536        }
537    }
538
539    /// The bytes from the start of the first line of `span` to the start of
540    /// the line after its last line, when the member and one comma after it
541    /// are the only text of these lines, apart from a `//` comment.
542    fn owned_lines(&self, span: MemberSpan) -> Option<(u32, u32)> {
543        let after = self.source.get(span.end as usize..)?;
544        let end = if after.starts_with(',') {
545            span.end + 1
546        } else {
547            span.end
548        };
549        let (first, last) = self.line_range(span.start, end);
550        let before = self
551            .source
552            .get(self.line_starts[first] as usize..span.start as usize)?;
553        let rest_of_line = self.source[end as usize..]
554            .split('\n')
555            .next()
556            .unwrap_or("")
557            .trim();
558        if !before.trim().is_empty() || !(rest_of_line.is_empty() || rest_of_line.starts_with("//"))
559        {
560            return None;
561        }
562        let start = self.line_starts[first];
563        let end = self
564            .line_starts
565            .get(last + 1)
566            .copied()
567            .unwrap_or_else(|| u32::try_from(self.source.len()).unwrap_or(u32::MAX));
568        Some((start, end))
569    }
570
571    /// The statement whose `export` keyword is at byte `start`.
572    #[must_use]
573    pub fn statement_at(&self, start: u32) -> Option<&ExportStatement> {
574        self.statements
575            .iter()
576            .find(|statement| statement.start == start)
577    }
578
579    /// The 0-based first and last line of the bytes `start..end`.
580    #[must_use]
581    pub fn line_range(&self, start: u32, end: u32) -> (usize, usize) {
582        (
583            self.line_of(start),
584            self.line_of(end.saturating_sub(1).max(start)),
585        )
586    }
587
588    fn line_of(&self, offset: u32) -> usize {
589        self.line_starts
590            .partition_point(|line_start| *line_start <= offset)
591            .saturating_sub(1)
592    }
593
594    /// True when no other text shares the lines of `start..end`: only white
595    /// space is before `start` on its line, and only white space and `;`
596    /// are after `end` on its line.
597    #[must_use]
598    pub fn owns_its_lines(&self, start: u32, end: u32) -> bool {
599        let (first, _) = self.line_range(start, end);
600        let line_start = self.line_starts[first] as usize;
601        let Some(before) = self.source.get(line_start..start as usize) else {
602            return false;
603        };
604        let Some(after) = self.source.get(end as usize..) else {
605            return false;
606        };
607        let after = after.split('\n').next().unwrap_or("");
608        before.trim().is_empty() && after.trim().trim_start_matches(';').trim().is_empty()
609    }
610}
611
612/// The statements and members of a file or of its script blocks.
613#[derive(Default)]
614struct Parsed {
615    statements: Vec<ExportStatement>,
616    members: Vec<MemberSpan>,
617    enums: Vec<EnumSpans>,
618}
619
620/// One script text of a file: the whole file, an inline `<script>` block of
621/// a Vue or Svelte file, or the frontmatter block of an Astro file.
622pub(crate) struct ScriptBlock<'s> {
623    /// The script text.
624    pub(crate) text: std::borrow::Cow<'s, str>,
625    /// The dialect of the script text.
626    pub(crate) source_type: SourceType,
627    /// The byte offset of the script text in the file.
628    pub(crate) offset: u32,
629}
630
631/// The script blocks of the file at `path`, or `None` for a file type that
632/// the engine does not parse here.
633pub(crate) fn script_blocks<'s>(path: &Path, source: &'s str) -> Option<Vec<ScriptBlock<'s>>> {
634    let owned = |script: &fallow_extract::sfc::SfcScript| {
635        let source_type = match (script.is_typescript, script.is_jsx) {
636            (true, true) => SourceType::tsx(),
637            (true, false) => SourceType::ts(),
638            (false, true) => SourceType::jsx(),
639            (false, false) => SourceType::mjs(),
640        };
641        Some(ScriptBlock {
642            text: std::borrow::Cow::Owned(script.body.clone()),
643            source_type,
644            offset: u32::try_from(script.byte_offset).ok()?,
645        })
646    };
647    if fallow_extract::is_sfc_file(path) {
648        let scripts = fallow_extract::extract_sfc_scripts(source);
649        return scripts
650            .iter()
651            .filter(|script| script.src.is_none())
652            .map(owned)
653            .collect();
654    }
655    if path
656        .extension()
657        .is_some_and(|extension| extension == "astro")
658    {
659        let frontmatter = fallow_extract::astro::extract_astro_frontmatter(source);
660        return frontmatter.iter().map(owned).collect();
661    }
662    let source_type = SourceType::from_path(path).ok()?;
663    Some(vec![ScriptBlock {
664        text: std::borrow::Cow::Borrowed(source),
665        source_type,
666        offset: 0,
667    }])
668}
669
670fn parse_file(path: &Path, source: &str) -> Option<Parsed> {
671    let mut parsed = Parsed::default();
672    for block in script_blocks(path, source)? {
673        let block = parse_block(source, &block.text, block.source_type, block.offset)?;
674        parsed.statements.extend(block.statements);
675        parsed.members.extend(block.members);
676        parsed.enums.extend(block.enums);
677    }
678    Some(parsed)
679}
680
681/// Parse one block of script text that starts at byte `offset` of `file`.
682fn parse_block(file: &str, source: &str, source_type: SourceType, offset: u32) -> Option<Parsed> {
683    fallow_extract::parse_bounded(source, || {
684        let allocator = oxc_allocator::Allocator::default();
685        let parsed = oxc_parser::Parser::new(&allocator, source, source_type).parse();
686        if parsed.fatal_error || parsed.diagnostics.has_errors() {
687            return None;
688        }
689        let mut members = MemberCollector {
690            offset,
691            members: Vec::new(),
692            enums: Vec::new(),
693            ambient_depth: usize::from(source_type.is_typescript_definition()),
694        };
695        members.visit_program(&parsed.program);
696        Some(Parsed {
697            statements: collect(&parsed.program, file, offset),
698            members: members.members,
699            enums: members.enums,
700        })
701    })
702    .flatten()
703}
704
705/// Collects the span of each class element and each enum member.
706struct MemberCollector {
707    offset: u32,
708    members: Vec<MemberSpan>,
709    enums: Vec<EnumSpans>,
710    /// The number of enclosing ambient contexts: a declaration file, and each
711    /// `declare` module, namespace or global block around the visit position.
712    ambient_depth: usize,
713}
714
715impl MemberCollector {
716    /// Visit `walk` inside one more ambient context when `declare` is true.
717    fn within(&mut self, declare: bool, walk: impl FnOnce(&mut Self)) {
718        let depth = usize::from(declare);
719        self.ambient_depth += depth;
720        walk(self);
721        self.ambient_depth -= depth;
722    }
723
724    fn push(&mut self, span: oxc_span::Span, shares_its_key: bool) {
725        self.members.push(MemberSpan {
726            start: span.start + self.offset,
727            end: span.end + self.offset,
728            shares_its_key,
729        });
730    }
731}
732
733impl<'a> Visit<'a> for MemberCollector {
734    fn visit_class_body(&mut self, it: &ClassBody<'a>) {
735        let names: Vec<_> = it
736            .body
737            .iter()
738            .map(|element| element.static_name())
739            .collect();
740        for (position, element) in it.body.iter().enumerate() {
741            let shares_its_key = names[position].as_ref().is_some_and(|name| {
742                names.iter().enumerate().any(|(other, other_name)| {
743                    other != position && other_name.as_ref() == Some(name)
744                })
745            });
746            self.push(element.span(), shares_its_key);
747        }
748        oxc_ast_visit::walk::walk_class_body(self, it);
749    }
750
751    fn visit_ts_enum_declaration(&mut self, it: &TSEnumDeclaration<'a>) {
752        let offset = self.offset;
753        let all_values = member_values(it, self.ambient_depth > 0);
754        let mut values = Vec::with_capacity(it.body.members.len());
755        let mut members = Vec::with_capacity(it.body.members.len());
756        for (position, member) in it.body.members.iter().enumerate() {
757            let name = match &member.id {
758                TSEnumMemberName::Identifier(id) => id.name.to_string(),
759                TSEnumMemberName::String(name) | TSEnumMemberName::ComputedString(name) => name
760                    .value
761                    .as_str()
762                    .map_or_else(|| name.value.display().to_string(), str::to_owned),
763                TSEnumMemberName::ComputedTemplateString(_) => continue,
764            };
765            values.push(all_values[position]);
766            members.push((
767                name,
768                MemberSpan {
769                    start: member.span.start + offset,
770                    end: member.span.end + offset,
771                    shares_its_key: false,
772                },
773            ));
774        }
775        self.enums.push(EnumSpans {
776            name: it.id.name.to_string(),
777            body_start: it.body.span.start + offset + 1,
778            body_end: it.body.span.end.saturating_sub(1) + offset,
779            complete: members.len() == it.body.members.len(),
780            members,
781            declaration: (it.span.start + offset, it.span.end + offset),
782            values,
783        });
784        oxc_ast_visit::walk::walk_ts_enum_declaration(self, it);
785    }
786
787    fn visit_ts_external_module_declaration(&mut self, it: &TSExternalModuleDeclaration<'a>) {
788        self.within(it.declare, |collector| {
789            oxc_ast_visit::walk::walk_ts_external_module_declaration(collector, it);
790        });
791    }
792
793    fn visit_ts_namespace_declaration(&mut self, it: &TSNamespaceDeclaration<'a>) {
794        self.within(it.declare, |collector| {
795            oxc_ast_visit::walk::walk_ts_namespace_declaration(collector, it);
796        });
797    }
798
799    fn visit_ts_global_declaration(&mut self, it: &TSGlobalDeclaration<'a>) {
800        self.within(it.declare, |collector| {
801            oxc_ast_visit::walk::walk_ts_global_declaration(collector, it);
802        });
803    }
804
805    fn visit_ts_enum_body(&mut self, it: &TSEnumBody<'a>) {
806        for member in &it.members {
807            self.push(member.span, false);
808        }
809        oxc_ast_visit::walk::walk_ts_enum_body(self, it);
810    }
811}
812
813fn collect(program: &Program<'_>, file: &str, offset: u32) -> Vec<ExportStatement> {
814    program
815        .body
816        .iter()
817        .filter_map(|statement| {
818            let (span, kind, names, merge) = match statement {
819                Statement::ExportDeclaration(export) => {
820                    let (kind, names) = declaration_names(&export.declaration)?;
821                    (
822                        export.span(),
823                        kind,
824                        names,
825                        MergeKind::of(&export.declaration),
826                    )
827                }
828                Statement::ExportDefaultDeclaration(export) => {
829                    let named = match &export.declaration {
830                        ExportDefaultDeclarationKind::FunctionDeclaration(function) => {
831                            function.id.is_some()
832                        }
833                        ExportDefaultDeclarationKind::ClassDeclaration(class) => class.id.is_some(),
834                        _ => false,
835                    };
836                    let kind = if named {
837                        ExportStatementKind::NamedDefault
838                    } else {
839                        ExportStatementKind::OtherDefault
840                    };
841                    (export.span(), kind, vec!["default".to_owned()], None)
842                }
843                _ => return None,
844            };
845            let start = span.start + offset;
846            let end = span.end + offset;
847            Some(ExportStatement {
848                start,
849                end,
850                kind,
851                names,
852                merge,
853                keyword_end: keyword_end(file, start, kind),
854            })
855        })
856        .collect()
857}
858
859/// The deletion of a run of neighbour members that share their lines.
860fn packed_run_edit(
861    enumeration: &EnumSpans,
862    removed: &[bool],
863    (first, last): (usize, usize),
864) -> SpanEdit {
865    let members = &enumeration.members;
866    let next = members.get(last + 1).map(|(_, span)| (last + 1, *span));
867    let previous = first
868        .checked_sub(1)
869        .map(|position| (position, members[position].1));
870    let kept = |neighbour: Option<(usize, MemberSpan)>| {
871        neighbour.filter(|(position, _)| !removed[*position])
872    };
873    let start = members[first].1.start;
874    let end = members[last].1.end;
875    if let Some((_, next)) = kept(next) {
876        return deletion(start, next.start);
877    }
878    if let Some((_, previous)) = kept(previous) {
879        return deletion(previous.end, end);
880    }
881    if let Some((_, next)) = next {
882        return deletion(start, next.start);
883    }
884    if let Some((_, previous)) = previous {
885        return deletion(previous.end, end);
886    }
887    deletion(enumeration.body_start, enumeration.body_end)
888}
889
890fn deletion(start: u32, end: u32) -> SpanEdit {
891    SpanEdit {
892        start,
893        end,
894        replacement: String::new(),
895    }
896}
897
898/// Each run of neighbour positions in the sorted `positions`, as the first
899/// and the last position of the run.
900fn neighbour_runs(positions: &[usize]) -> Vec<(usize, usize)> {
901    let mut runs: Vec<(usize, usize)> = Vec::new();
902    for &position in positions {
903        match runs.last_mut() {
904            Some((_, last)) if *last + 1 == position => *last = position,
905            _ => runs.push((position, position)),
906        }
907    }
908    runs
909}
910
911/// The kind and the exported names of an `export <declaration>`, or `None`
912/// for a declaration without a name.
913pub(crate) fn declaration_names(
914    declaration: &Declaration<'_>,
915) -> Option<(ExportStatementKind, Vec<String>)> {
916    let single = |name: &str| Some((ExportStatementKind::Declaration, vec![name.to_owned()]));
917    match declaration {
918        Declaration::VariableDeclaration(variables) => {
919            let names: Vec<String> = variables
920                .declarations
921                .iter()
922                .flat_map(|declarator| declarator.id.get_binding_identifiers())
923                .map(|identifier| identifier.name.to_string())
924                .collect();
925            (!names.is_empty()).then_some((ExportStatementKind::Variable, names))
926        }
927        Declaration::FunctionDeclaration(function) => single(function.id.as_ref()?.name.as_str()),
928        Declaration::ClassDeclaration(class) => single(class.id.as_ref()?.name.as_str()),
929        Declaration::TSTypeAliasDeclaration(alias) => single(alias.id.name.as_str()),
930        Declaration::TSInterfaceDeclaration(interface) => single(interface.id.name.as_str()),
931        Declaration::TSEnumDeclaration(enumeration) => Some((
932            ExportStatementKind::Enum,
933            vec![enumeration.id.name.to_string()],
934        )),
935        Declaration::TSNamespaceDeclaration(namespace) => single(namespace.id.name.as_str()),
936        Declaration::TSImportEqualsDeclaration(import) => single(import.id.name.as_str()),
937        Declaration::TSExternalModuleDeclaration(_) | Declaration::TSGlobalDeclaration(_) => None,
938    }
939}
940
941/// The end of the removable `export` prefix of the statement at `start`.
942fn keyword_end(file: &str, start: u32, kind: ExportStatementKind) -> Option<u32> {
943    let text = file.get(start as usize..)?.strip_prefix("export")?;
944    let after_export = skip_blank(text)?;
945    let removed = match kind {
946        ExportStatementKind::Variable
947        | ExportStatementKind::Enum
948        | ExportStatementKind::Declaration => text.len() - after_export.len(),
949        ExportStatementKind::NamedDefault => {
950            let after_default = skip_blank(after_export.strip_prefix("default")?)?;
951            text.len() - after_default.len()
952        }
953        ExportStatementKind::OtherDefault => return None,
954    };
955    let removed = u32::try_from("export".len() + removed).ok()?;
956    Some(start + removed)
957}
958
959/// `text` without its leading spaces and tabs, or `None` when it has none.
960fn skip_blank(text: &str) -> Option<&str> {
961    let rest = text.trim_start_matches([' ', '\t']);
962    (rest.len() < text.len()).then_some(rest)
963}
964
965#[cfg(test)]
966mod tests {
967    use super::*;
968
969    fn index(path: &str, source: &str) -> SourceEditIndex {
970        SourceEditIndex::parse(Path::new(path), source).expect("the source parses")
971    }
972
973    fn apply(source: &str, edit: &SpanEdit) -> String {
974        let mut result = source.to_owned();
975        result.replace_range(edit.start as usize..edit.end as usize, &edit.replacement);
976        result
977    }
978
979    fn summary(index: &SourceEditIndex) -> Vec<(ExportStatementKind, Vec<String>)> {
980        index
981            .statements
982            .iter()
983            .map(|statement| (statement.kind, statement.names.clone()))
984            .collect()
985    }
986
987    fn names(list: &[&str]) -> Vec<String> {
988        list.iter().map(|name| (*name).to_owned()).collect()
989    }
990
991    #[test]
992    fn finds_the_names_and_kind_of_each_statement_form() {
993        use ExportStatementKind::{Declaration, Enum, NamedDefault, Variable};
994        let source = "export const single = 1;\nexport var g = 1, h = 2;\nexport const { a = 1, b: { c }, ...rest } = x;\nexport let [d, , [e], ...f] = y;\nexport function fn1() {}\nexport async function fn2() {}\nexport class C1 {}\nexport abstract class C2 {}\nexport type T = 1;\nexport interface I {}\nexport enum E { A }\nexport const enum CE { A }\nexport namespace N {}\n";
995        assert_eq!(
996            summary(&index("store.ts", source)),
997            vec![
998                (Variable, names(&["single"])),
999                (Variable, names(&["g", "h"])),
1000                (Variable, names(&["a", "c", "rest"])),
1001                (Variable, names(&["d", "e", "f"])),
1002                (Declaration, names(&["fn1"])),
1003                (Declaration, names(&["fn2"])),
1004                (Declaration, names(&["C1"])),
1005                (Declaration, names(&["C2"])),
1006                (Declaration, names(&["T"])),
1007                (Declaration, names(&["I"])),
1008                (Enum, names(&["E"])),
1009                (Enum, names(&["CE"])),
1010                (Declaration, names(&["N"])),
1011            ]
1012        );
1013        let defaults = [
1014            ("export default function named() {}\n", NamedDefault),
1015            ("export default class Named {}\n", NamedDefault),
1016            (
1017                "export default function () {}\n",
1018                ExportStatementKind::OtherDefault,
1019            ),
1020            (
1021                "export default class {}\n",
1022                ExportStatementKind::OtherDefault,
1023            ),
1024            ("export default thing;\n", ExportStatementKind::OtherDefault),
1025            (
1026                "export default { a: 1, b: 2 };\n",
1027                ExportStatementKind::OtherDefault,
1028            ),
1029        ];
1030        for (source, kind) in defaults {
1031            assert_eq!(
1032                summary(&index("store.ts", source)),
1033                vec![(kind, names(&["default"]))],
1034                "{source}"
1035            );
1036        }
1037    }
1038
1039    #[test]
1040    fn skips_lists_re_exports_and_assignments() {
1041        let source =
1042            "const a = 1;\nexport { a };\nexport { b } from './b';\nexport * from './c';\n";
1043        assert!(index("store.ts", source).statements.is_empty());
1044        assert!(
1045            index("store.ts", "const a = 1;\nexport = a;\n")
1046                .statements
1047                .is_empty()
1048        );
1049    }
1050
1051    #[test]
1052    fn keyword_edit_keeps_the_declaration() {
1053        let cases = [
1054            ("export const a = 1;\n", "const a = 1;\n"),
1055            ("export\tconst a = 1, b = 2;\n", "const a = 1, b = 2;\n"),
1056            (
1057                "export /* values */ const a = 1;\n",
1058                "/* values */ const a = 1;\n",
1059            ),
1060            ("export async function f() {}\n", "async function f() {}\n"),
1061            ("export abstract class C {}\n", "abstract class C {}\n"),
1062            ("export enum E { A }\n", "enum E { A }\n"),
1063            (
1064                "export default function named() {}\n",
1065                "function named() {}\n",
1066            ),
1067            (
1068                "export default async function named() {}\n",
1069                "async function named() {}\n",
1070            ),
1071            ("export default class Named {}\n", "class Named {}\n"),
1072            (
1073                "export default abstract class Named {}\n",
1074                "abstract class Named {}\n",
1075            ),
1076        ];
1077        for (source, expected) in cases {
1078            let index = index("store.ts", source);
1079            let edit = index.statements[0].keyword_edit().expect(source);
1080            assert_eq!(apply(source, &edit), expected, "{source}");
1081        }
1082        for source in [
1083            "export default function () {}\n",
1084            "export default class {}\n",
1085            "export default thing;\n",
1086            "export default { a: 1, b: 2 };\n",
1087        ] {
1088            assert_eq!(index("store.ts", source).statements[0].keyword_edit(), None);
1089        }
1090    }
1091
1092    #[test]
1093    fn offsets_count_a_leading_byte_order_mark() {
1094        let source = "\u{feff}export const a = 1;\n";
1095        let index = index("store.ts", source);
1096        let statement = &index.statements[0];
1097        assert_eq!(statement.start, 3);
1098        assert_eq!(
1099            apply(source, &statement.keyword_edit().unwrap()),
1100            "\u{feff}const a = 1;\n"
1101        );
1102    }
1103
1104    #[test]
1105    fn export_statement_selects_by_line_and_column() {
1106        let source = "export function live() {} export function dead() {}\nexport const x = 1;\n";
1107        let index = index("store.ts", source);
1108        let dead = index.export_statement("dead", 1, 42).unwrap();
1109        assert_eq!(
1110            &source[dead.start as usize..dead.end as usize],
1111            "export function dead() {}"
1112        );
1113        let dead = index.export_statement("dead", 1, 0).unwrap();
1114        assert_eq!(dead.start, 26, "one candidate needs no column");
1115        assert_eq!(
1116            index.export_statement("x", 1, 0),
1117            Err(EditRefusal::NameNotFound)
1118        );
1119        assert_eq!(index.export_statement("x", 2, 13).unwrap().start, 52);
1120
1121        let twice = "export namespace N {} export namespace N {}\n";
1122        let index = super::tests::index("store.ts", twice);
1123        assert_eq!(index.export_statement("N", 1, 0).unwrap().start, 0);
1124        assert_eq!(index.export_statement("N", 1, 39).unwrap().start, 22);
1125    }
1126
1127    #[test]
1128    fn a_statement_over_several_lines_holds_each_of_its_lines() {
1129        let source = "const x = {};\nexport const {\n  a,\n} = x;\nexport function f() {}\n";
1130        let index = index("store.ts", source);
1131        let statement = index.export_statement("a", 3, 2).unwrap();
1132        assert_eq!(
1133            &source[statement.start as usize..statement.end as usize],
1134            "export const {\n  a,\n} = x;"
1135        );
1136        assert_eq!(index.line_range(statement.start, statement.end), (1, 3));
1137        assert!(index.owns_its_lines(statement.start, statement.end));
1138        let f = index.export_statement("f", 5, 16).unwrap();
1139        assert_eq!(index.line_range(f.start, f.end), (4, 4));
1140    }
1141
1142    #[test]
1143    fn owns_its_lines_sees_other_text_on_the_line() {
1144        let source =
1145            "export enum E { A };\nexport enum F { A } const x = 1;\n  export enum G {\n  A,\n}\n";
1146        let index = index("store.ts", source);
1147        let statements = &index.statements;
1148        assert!(index.owns_its_lines(statements[0].start, statements[0].end));
1149        assert!(!index.owns_its_lines(statements[1].start, statements[1].end));
1150        assert!(index.owns_its_lines(statements[2].start, statements[2].end));
1151    }
1152
1153    /// The text of each statement that `source` holds.
1154    fn texts(path: &str, source: &str) -> Vec<String> {
1155        index(path, source)
1156            .statements
1157            .into_iter()
1158            .map(|statement| source[statement.start as usize..statement.end as usize].to_owned())
1159            .collect()
1160    }
1161
1162    #[test]
1163    fn reads_each_script_block_of_a_vue_file() {
1164        let source = "<template><div /></template>\n<script lang=\"ts\">\nexport const c = 1, d = 2;\n</script>\n<script setup lang=\"ts\">\nconst e = 1;\n</script>\n";
1165        assert_eq!(
1166            texts("store.vue", source),
1167            vec!["export const c = 1, d = 2;"]
1168        );
1169    }
1170
1171    #[test]
1172    fn reads_the_module_script_of_a_svelte_file() {
1173        let source =
1174            "<script context=\"module\">\n  export const { a, b } = x;\n</script>\n<p>hi</p>\n";
1175        assert_eq!(
1176            texts("store.svelte", source),
1177            vec!["export const { a, b } = x;"]
1178        );
1179    }
1180
1181    #[test]
1182    fn reads_the_frontmatter_of_an_astro_file() {
1183        let source = "---\nexport const [a, b] = [1, 2];\n---\n<p>{a}</p>\n";
1184        assert_eq!(
1185            texts("page.astro", source),
1186            vec!["export const [a, b] = [1, 2];"]
1187        );
1188    }
1189
1190    /// The text of each member that starts on `line`.
1191    fn members(source: &str, line: u32) -> Vec<String> {
1192        let index = index("store.ts", source);
1193        index
1194            .members_on_line(line)
1195            .map(|member| source[member.start as usize..member.end as usize].to_owned())
1196            .collect()
1197    }
1198
1199    #[test]
1200    fn members_on_line_gives_class_and_enum_members() {
1201        let class = "class C {\n  one() { return 1; }\n  legacy() {\n    return null;\n  }\n  value = 1;\n}\n";
1202        assert_eq!(members(class, 2), vec!["one() { return 1; }"]);
1203        assert_eq!(members(class, 3), vec!["legacy() {\n    return null;\n  }"]);
1204        assert_eq!(members(class, 6), vec!["value = 1;"]);
1205        assert!(members(class, 4).is_empty());
1206
1207        let enumeration = "enum E {\n  A,\n  B, C,\n  D = \"x,y\"\n}\n";
1208        assert_eq!(members(enumeration, 2), vec!["A"]);
1209        assert_eq!(members(enumeration, 3), vec!["B", "C"]);
1210        assert_eq!(members(enumeration, 4), vec!["D = \"x,y\""]);
1211    }
1212
1213    #[test]
1214    fn a_class_element_knows_whether_it_shares_its_key() {
1215        let source = "class K {\n  m(a: string): void;\n  m(a: any) {}\n  get x() { return 1; }\n  set x(v) {}\n  only() {}\n}\n";
1216        let index = index("store.ts", source);
1217        let shares = |line| {
1218            index
1219                .members_on_line(line)
1220                .map(|member| member.shares_its_key)
1221                .collect::<Vec<_>>()
1222        };
1223        assert_eq!(shares(2), vec![true]);
1224        assert_eq!(shares(3), vec![true]);
1225        assert_eq!(shares(4), vec![true]);
1226        assert_eq!(shares(5), vec![true]);
1227        assert_eq!(shares(6), vec![false]);
1228    }
1229
1230    #[test]
1231    fn members_on_line_reads_a_nested_class() {
1232        let source = "export function f() {\n  return class {\n    inner() {}\n  };\n}\n";
1233        assert_eq!(members(source, 3), vec!["inner() {}"]);
1234    }
1235
1236    #[test]
1237    fn export_statements_on_line_gives_each_keyword_of_the_line() {
1238        let source = "export const a = 1; export const b = 2;\nexport function f() {\n}\n";
1239        let index = index("store.ts", source);
1240        assert_eq!(index.export_statements_on_line(1).count(), 2);
1241        assert_eq!(index.export_statements_on_line(2).count(), 1);
1242        assert_eq!(index.export_statements_on_line(3).count(), 0);
1243    }
1244
1245    /// `source` after the removal of `members` from the enum `name`.
1246    fn remove(
1247        source: &str,
1248        name: &str,
1249        members: &[&str],
1250        line: u32,
1251    ) -> Result<String, EditRefusal> {
1252        let index = index("store.ts", source);
1253        let edits = index.remove_enum_members(name, members, line)?;
1254        let mut result = source.to_owned();
1255        for edit in edits.iter().rev() {
1256            result.replace_range(edit.start as usize..edit.end as usize, &edit.replacement);
1257        }
1258        Ok(result)
1259    }
1260
1261    #[test]
1262    fn keeps_the_value_of_a_kept_member_that_counts_on() {
1263        let source = "export enum Level {\n  Low,\n  Medium,\n  High,\n}\n";
1264        assert_eq!(
1265            remove(source, "Level", &["Low"], 2).unwrap(),
1266            "export enum Level {\n  Medium = 1,\n  High,\n}\n"
1267        );
1268        let run = "enum E {\n  A,\n  B,\n  C,\n  D,\n}\n";
1269        assert_eq!(
1270            remove(run, "E", &["A", "B"], 2).unwrap(),
1271            "enum E {\n  C = 2,\n  D,\n}\n",
1272            "a run of removed members pins only the next kept member"
1273        );
1274        assert_eq!(
1275            remove(run, "E", &["B", "D"], 3).unwrap(),
1276            "enum E {\n  A,\n  C = 2,\n}\n"
1277        );
1278        let chained = "enum E { A = -3, B, C = 0x10, D, 'e-f' }\n";
1279        assert_eq!(
1280            remove(chained, "E", &["A"], 1).unwrap(),
1281            "enum E { B = -2, C = 0x10, D, 'e-f' }\n"
1282        );
1283        assert_eq!(
1284            remove(chained, "E", &["C", "D"], 1).unwrap(),
1285            "enum E { A = -3, B, 'e-f' = 18 }\n"
1286        );
1287        let initialized = "enum E {\n  A = 1,\n  B = 2,\n}\n";
1288        assert_eq!(
1289            remove(initialized, "E", &["A"], 2).unwrap(),
1290            "enum E {\n  B = 2,\n}\n",
1291            "a member with an initializer needs no pin"
1292        );
1293        let declared = "export declare const enum E {\n  A,\n  B,\n}\n";
1294        assert_eq!(
1295            remove(declared, "E", &["A"], 2).unwrap(),
1296            "export declare const enum E {\n  B = 1,\n}\n"
1297        );
1298    }
1299
1300    #[test]
1301    fn refuses_a_removal_that_shifts_an_unknown_value() {
1302        for source in [
1303            "enum E {\n  A = x,\n  B,\n}\n",
1304            "enum E {\n  A = 1.5,\n  B,\n}\n",
1305            "enum E {\n  A = \"a\".length,\n  B,\n}\n",
1306            "declare enum E {\n  A,\n  B,\n}\n",
1307        ] {
1308            assert_eq!(
1309                remove(source, "E", &["A"], 2),
1310                Err(EditRefusal::UnknownValue),
1311                "{source}"
1312            );
1313        }
1314        let ambient_last = "declare enum E {\n  A,\n  B,\n}\n";
1315        assert_eq!(
1316            remove(ambient_last, "E", &["B"], 3).unwrap(),
1317            "declare enum E {\n  A,\n}\n",
1318            "the removal of the last member shifts no value"
1319        );
1320    }
1321
1322    #[test]
1323    fn refuses_a_shift_in_an_ambient_context() {
1324        let namespace = "declare namespace N {\n  enum E {\n    A,\n    B,\n  }\n}\n";
1325        let module = "declare module 'm' {\n  export enum E {\n    A,\n    B,\n  }\n}\n";
1326        let nested = "declare namespace N {\n  namespace M {\n    enum E {\n      A,\n      B,\n    }\n  }\n}\n";
1327        let global = "export {};\ndeclare global {\n  enum E {\n    A,\n    B,\n  }\n}\n";
1328        for (source, line) in [(namespace, 3), (module, 3), (nested, 4), (global, 4)] {
1329            let index = index("store.ts", source);
1330            assert_eq!(
1331                index.remove_enum_members("E", &["A"], line),
1332                Err(EditRefusal::UnknownValue),
1333                "{source}"
1334            );
1335        }
1336        let definition = index("a.d.ts", "export enum E {\n  A,\n  B,\n}\n");
1337        assert_eq!(
1338            definition.remove_enum_members("E", &["A"], 2),
1339            Err(EditRefusal::UnknownValue),
1340            "a member of a declaration file is ambient"
1341        );
1342        let constant = "declare namespace N {\n  const enum E {\n    A,\n    B,\n  }\n}\n";
1343        assert_eq!(
1344            remove(constant, "E", &["A"], 3).unwrap(),
1345            "declare namespace N {\n  const enum E {\n    B = 1,\n  }\n}\n",
1346            "a const enum keeps known values in an ambient context"
1347        );
1348        let plain = "namespace N {\n  enum E {\n    A,\n    B,\n  }\n}\n";
1349        assert_eq!(
1350            remove(plain, "E", &["A"], 3).unwrap(),
1351            "namespace N {\n  enum E {\n    B = 1,\n  }\n}\n",
1352            "a namespace without declare is not ambient"
1353        );
1354    }
1355
1356    #[test]
1357    fn removes_a_member_on_its_own_line() {
1358        let source = "enum E {\n  A,\n  B,\n  C,\n}\n";
1359        assert_eq!(
1360            remove(source, "E", &["A"], 2).unwrap(),
1361            "enum E {\n  B = 1,\n  C,\n}\n"
1362        );
1363        assert_eq!(
1364            remove(source, "E", &["B"], 3).unwrap(),
1365            "enum E {\n  A,\n  C = 2,\n}\n"
1366        );
1367        assert_eq!(
1368            remove(source, "E", &["C"], 4).unwrap(),
1369            "enum E {\n  A,\n  B,\n}\n"
1370        );
1371        let no_comma = "enum E {\n  A,\n  B\n}\n";
1372        assert_eq!(
1373            remove(no_comma, "E", &["B"], 3).unwrap(),
1374            "enum E {\n  A,\n}\n"
1375        );
1376    }
1377
1378    #[test]
1379    fn removes_a_member_with_a_trailing_comment_or_a_long_initializer() {
1380        let comment = "enum E {\n  A, // }\n  B,\n}\n";
1381        assert_eq!(
1382            remove(comment, "E", &["A"], 2).unwrap(),
1383            "enum E {\n  B = 1,\n}\n"
1384        );
1385        let long = "enum E {\n  A = 1 +\n    2,\n  B,\n}\n";
1386        assert_eq!(
1387            remove(long, "E", &["A"], 2),
1388            Err(EditRefusal::UnknownValue),
1389            "B counts on from a computed value"
1390        );
1391        let long_kept = "enum E {\n  A = 1 +\n    2,\n  B = 5,\n}\n";
1392        assert_eq!(
1393            remove(long_kept, "E", &["A"], 2).unwrap(),
1394            "enum E {\n  B = 5,\n}\n"
1395        );
1396    }
1397
1398    #[test]
1399    fn removes_packed_members_and_keeps_each_other_byte() {
1400        let source = "enum E { A, B, C }\n";
1401        assert_eq!(
1402            remove(source, "E", &["A"], 1).unwrap(),
1403            "enum E { B = 1, C }\n"
1404        );
1405        assert_eq!(
1406            remove(source, "E", &["B"], 1).unwrap(),
1407            "enum E { A, C = 2 }\n"
1408        );
1409        assert_eq!(remove(source, "E", &["C"], 1).unwrap(), "enum E { A, B }\n");
1410        assert_eq!(
1411            remove(source, "E", &["A", "B"], 1).unwrap(),
1412            "enum E { C = 2 }\n"
1413        );
1414        assert_eq!(
1415            remove(source, "E", &["B", "C"], 1).unwrap(),
1416            "enum E { A }\n"
1417        );
1418        assert_eq!(
1419            remove(source, "E", &["A", "B", "C"], 1).unwrap(),
1420            "enum E {}\n"
1421        );
1422        let string_value = "enum E { A = \"x,y\", B }\n";
1423        assert_eq!(
1424            remove(string_value, "E", &["B"], 1).unwrap(),
1425            "enum E { A = \"x,y\" }\n"
1426        );
1427        let trailing = "enum Foo { A, B, }\n";
1428        assert_eq!(
1429            remove(trailing, "Foo", &["B"], 1).unwrap(),
1430            "enum Foo { A, }\n"
1431        );
1432    }
1433
1434    #[test]
1435    fn removes_a_mix_of_own_line_and_packed_members() {
1436        let source = "enum E {\n  A,\n  B, C,\n  D\n}\n";
1437        assert_eq!(
1438            remove(source, "E", &["A", "B"], 2).unwrap(),
1439            "enum E {\n  C = 2,\n  D\n}\n"
1440        );
1441        let packed_first = "enum E {\n  A, B,\n  C\n}\n";
1442        assert_eq!(
1443            remove(packed_first, "E", &["A"], 2).unwrap(),
1444            "enum E {\n  B = 1,\n  C\n}\n"
1445        );
1446    }
1447
1448    #[test]
1449    fn reads_a_string_member_name() {
1450        let source = "enum E {\n  'my-key' = 1,\n  B = 2,\n}\n";
1451        assert_eq!(
1452            remove(source, "E", &["my-key"], 2).unwrap(),
1453            "enum E {\n  B = 2,\n}\n"
1454        );
1455    }
1456
1457    #[test]
1458    fn selects_one_of_two_enums_with_the_same_name_by_line() {
1459        let source = "namespace N {\n  enum E {\n    A,\n    B,\n  }\n}\nnamespace M {\n  enum E {\n    A,\n    B,\n  }\n}\n";
1460        assert_eq!(
1461            remove(source, "E", &["A"], 9).unwrap(),
1462            "namespace N {\n  enum E {\n    A,\n    B,\n  }\n}\nnamespace M {\n  enum E {\n    B = 1,\n  }\n}\n"
1463        );
1464        assert_eq!(remove(source, "E", &["A"], 1), Err(EditRefusal::Ambiguous));
1465        assert_eq!(
1466            remove(source, "E", &["Z"], 3),
1467            Err(EditRefusal::NameNotFound)
1468        );
1469    }
1470
1471    #[test]
1472    fn keeps_a_comment_between_members() {
1473        let after_kept = "enum E {\n  A, // about A\n  B, C\n}\n";
1474        assert_eq!(
1475            remove(after_kept, "E", &["B", "C"], 3),
1476            Err(EditRefusal::Ambiguous)
1477        );
1478        let before_kept = "enum E {\n  A, B,\n  // about C\n  C,\n}\n";
1479        assert_eq!(
1480            remove(before_kept, "E", &["A", "B"], 2),
1481            Err(EditRefusal::Ambiguous)
1482        );
1483        let in_a_string = "enum E { A = \"http://x\", B = \"y\" }\n";
1484        assert_eq!(
1485            remove(in_a_string, "E", &["A"], 1).unwrap(),
1486            "enum E { B = \"y\" }\n"
1487        );
1488    }
1489
1490    #[test]
1491    fn removes_each_member_of_a_mixed_enum() {
1492        let source = "enum E {\n  A, B,\n  C\n}\n";
1493        assert_eq!(
1494            remove(source, "E", &["A", "B", "C"], 2).unwrap(),
1495            "enum E {}\n"
1496        );
1497    }
1498
1499    #[test]
1500    fn keeps_a_comment_of_an_enum_whose_members_are_all_removed() {
1501        let source = "enum E {\n  // keep this\n  A, B,\n}\n";
1502        assert_eq!(
1503            remove(source, "E", &["A", "B"], 3),
1504            Err(EditRefusal::Ambiguous)
1505        );
1506        let tail = "enum E { A, B /* tail */ }\n";
1507        assert_eq!(
1508            remove(tail, "E", &["A", "B"], 1),
1509            Err(EditRefusal::Ambiguous)
1510        );
1511    }
1512
1513    #[test]
1514    fn selects_one_of_two_one_line_enums_by_line() {
1515        let source = "namespace N {\n  export enum E { A, B }\n}\nnamespace M {\n  export enum E { A, B }\n}\n";
1516        assert_eq!(
1517            remove(source, "E", &["A"], 5).unwrap(),
1518            "namespace N {\n  export enum E { A, B }\n}\nnamespace M {\n  export enum E { B = 1 }\n}\n"
1519        );
1520    }
1521
1522    #[test]
1523    fn refuses_an_enum_with_a_computed_template_name() {
1524        let source = "enum E {\n  A = 1,\n  [`b`] = 2,\n}\n";
1525        if SourceEditIndex::parse(Path::new("store.ts"), source).is_some() {
1526            assert_eq!(
1527                remove(source, "E", &["A"], 2),
1528                Err(EditRefusal::NameNotFound)
1529            );
1530        }
1531    }
1532
1533    #[test]
1534    fn gives_none_for_another_file_type_or_a_syntax_error() {
1535        assert!(SourceEditIndex::parse(Path::new("notes.md"), "export const a = 1;\n").is_none());
1536        assert!(
1537            SourceEditIndex::parse(
1538                Path::new("store.ts"),
1539                "export const [a, b] = x;\nexport const = ;\n"
1540            )
1541            .is_none()
1542        );
1543    }
1544}