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