Skip to main content

parsec_js/
reparse.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Parsing again after an edit: [`Ast::reparse`] parses only the
5//! smallest function body or statement around the edit, and keeps the
6//! rest of the tree.
7//!
8//! The piece parsed again starts and ends where it did, at the same
9//! characters, so nothing before it reads differently and the text after
10//! it is the same text, read from the same place. What the parser knew
11//! when it got there (strict code or not, the function it's in, the
12//! loops and labels around it, the depth) comes from the nodes on the
13//! way down. Where that isn't enough to be sure, the source is parsed
14//! whole: an edit in a directive prologue or a parameter list, a
15//! statement that starts with `import` or `export`, a piece that ends
16//! anywhere but where it did, and a step limit, which counts the whole
17//! source.
18//!
19//! The tree is the same as [`parse`] gives for the new source, node for
20//! node; `tests/reparse.rs` checks that on random edits.
21
22use parsec_base::{Diagnostic, Span};
23
24use crate::ast::{
25    Ast, CommentKind, FunctionKind, List, MethodKind, Node, NodeId, PropertyKind, Ref, refs,
26};
27use crate::lexer::{Goal, Lexer, SourceType};
28use crate::parser::{Ctx, DEFAULT_MAX_DEPTH, Options, Resume, parse, parse_piece};
29use crate::text;
30use crate::token::{Keyword, Kind};
31
32/// A change to a source: the bytes in `range` replaced by `text`.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct Edit<'a> {
35    pub range: Span,
36    pub text: &'a str,
37}
38
39/// What [`Ast::reparse`] did.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct Reparsed {
42    /// The source with the edit made, which the tree is now of.
43    pub source: String,
44    /// The part of it parsed again, or `None` if it was parsed whole.
45    pub reparsed: Option<Span>,
46}
47
48/// How many pieces, from the smallest out, are tried before parsing the
49/// whole source.
50const TRIES: usize = 3;
51
52impl Ast {
53    /// Makes `edit` to `src`, the source this tree was parsed from, and
54    /// brings the tree up to date with it: the smallest function body or
55    /// statement around the edit is parsed again and the rest kept, or
56    /// where that can't be sure to give what [`parse`] would, the new
57    /// source is parsed whole. The tree's source type is kept, and
58    /// `options` gives the limits.
59    ///
60    /// A syntax error in the new source is the `Err`, and the tree is
61    /// left as it was, of `src`.
62    ///
63    /// ```
64    /// use parsec_js::{Edit, Options, Span, parse_script};
65    ///
66    /// let src = "function f() {\n  return 1;\n}\nf();\n";
67    /// let mut ast = parse_script(src).unwrap();
68    /// let edit = Edit { range: Span::new(24, 25), text: "42" };
69    /// let done = ast.reparse(src, &edit, &Options::default()).unwrap();
70    /// assert_eq!(done.source, "function f() {\n  return 42;\n}\nf();\n");
71    /// // Only the `return` was parsed again.
72    /// assert_eq!(done.reparsed, Some(Span::new(17, 27)));
73    /// assert_eq!(ast.to_estree(&done.source), parse_script(&done.source).unwrap().to_estree(&done.source));
74    /// ```
75    pub fn reparse(
76        &mut self,
77        src: &str,
78        edit: &Edit<'_>,
79        options: &Options,
80    ) -> Result<Reparsed, Diagnostic> {
81        let (a, b) = (edit.range.start as usize, edit.range.end as usize);
82        if a > b || b > src.len() || !src.is_char_boundary(a) || !src.is_char_boundary(b) {
83            return Err(Diagnostic::error(
84                "edit-out-of-range",
85                edit.range,
86                "the edit's range isn't whole characters of the source",
87            ));
88        }
89        let mut source = String::with_capacity(src.len() - (b - a) + edit.text.len());
90        source.push_str(&src[..a]);
91        source.push_str(edit.text);
92        source.push_str(&src[b..]);
93        let Node::Program { source_type, .. } = *self.node(self.root()) else {
94            unreachable!("the root is a program")
95        };
96        let options = Options {
97            source_type,
98            ..*options
99        };
100        // shortcut: a step limit counts the whole source's tokens, which a
101        // piece can't, so with one it's always parsed whole.
102        if options.limits.max_steps.is_none() && options.limits.check_input(source.len()).is_ok() {
103            let delta = source.len() as i64 - src.len() as i64;
104            if let Some(span) = self.try_pieces(src, &source, a as u32, b as u32, delta, &options) {
105                return Ok(Reparsed {
106                    source,
107                    reparsed: Some(span),
108                });
109            }
110        }
111        *self = parse(&source, &options)?;
112        Ok(Reparsed {
113            source,
114            reparsed: None,
115        })
116    }
117
118    /// Parses the pieces around `a..b` again, the smallest first, and
119    /// puts the first that works in place: the span it has now.
120    fn try_pieces(
121        &mut self,
122        old: &str,
123        new: &str,
124        a: u32,
125        b: u32,
126        delta: i64,
127        options: &Options,
128    ) -> Option<Span> {
129        if let Some(span) = self.edit_in_comment(old, new, a, b, delta, options.source_type) {
130            return Some(span);
131        }
132        let path = self.path(a, b);
133        let mut tries = 0;
134        for k in (1..path.len()).rev() {
135            let Some(body) = self.piece_kind(path[k - 1], path[k]) else {
136                continue;
137            };
138            let span = self.span(path[k]);
139            // The piece's first and last characters stay, so what's
140            // before it and after it reads the same.
141            if !(span.start < a && b < span.end) {
142                continue;
143            }
144            tries += 1;
145            if tries > TRIES {
146                return None;
147            }
148            if let Some(s) = self.try_piece(old, new, &path[..=k], body, delta, options) {
149                return Some(s);
150            }
151        }
152        None
153    }
154
155    /// An edit inside a comment that leaves it one comment, ending where
156    /// it did, with a line break in it only if it had one, changes no
157    /// token: only the spans after it move. The comment's span now.
158    fn edit_in_comment(
159        &mut self,
160        old: &str,
161        new: &str,
162        a: u32,
163        b: u32,
164        delta: i64,
165        source: SourceType,
166    ) -> Option<Span> {
167        let i = self.comments.partition_point(|c| c.span.end <= a);
168        let c = *self.comments.get(i)?;
169        let close = match c.kind {
170            CommentKind::Block => 2,
171            CommentKind::Line => 0,
172            _ => return None,
173        };
174        if !(c.span.start + 2 <= a && b + close <= c.span.end) {
175            return None;
176        }
177        let t = Lexer::new(new, source)
178            .starting_at(c.span.start, false)
179            .next_token(Goal::Div);
180        let end = u32::try_from(c.span.end as i64 + delta).ok()?;
181        let breaks = |s: &str| s.contains(['\n', '\r', '\u{2028}', '\u{2029}']);
182        if t.span != Span::new(c.span.start, end)
183            || breaks(t.span.text(new)) != breaks(c.span.text(old))
184        {
185            return None;
186        }
187        let moved = |x: u32| {
188            if x >= c.span.end {
189                (x as i64 + delta) as u32
190            } else {
191                x
192            }
193        };
194        for (_, s) in &mut self.nodes[1..] {
195            *s = Span::new(moved(s.start), moved(s.end));
196        }
197        self.comments[i].span = t.span;
198        for c in &mut self.comments[i + 1..] {
199            c.span = Span::new(moved(c.span.start), moved(c.span.end));
200        }
201        for d in &mut self.warnings {
202            d.span = Span::new(moved(d.span.start), moved(d.span.end));
203        }
204        Some(t.span)
205    }
206
207    /// The nodes from the root down to the smallest that holds `a..b`.
208    fn path(&self, a: u32, b: u32) -> Vec<NodeId> {
209        let mut path = vec![self.root()];
210        loop {
211            let id = *path.last().expect("the root is there");
212            let mut next = None;
213            self.each_child(id, &mut |c| {
214                let s = self.span(c);
215                if next.is_none() && s.start <= a && b <= s.end && c != id {
216                    next = Some(c);
217                }
218            });
219            match next {
220                Some(c) => path.push(c),
221                None => return path,
222            }
223        }
224    }
225
226    fn each_child(&self, id: NodeId, f: &mut dyn FnMut(NodeId)) {
227        let mut node = *self.node(id);
228        refs(&mut node, &mut |r| match r {
229            Ref::Node(c) => f(*c),
230            Ref::List(l) => {
231                for &c in self.get(*l) {
232                    f(c);
233                }
234            }
235        });
236    }
237
238    /// Whether `child` of `parent` is a piece that can be parsed alone:
239    /// `Some(true)` for a function body, `Some(false)` for an item of a
240    /// statement list.
241    fn piece_kind(&self, parent: NodeId, child: NodeId) -> Option<bool> {
242        match *self.node(parent) {
243            Node::Function(f) if f.body == child && !f.expression => Some(true),
244            Node::Program { .. } | Node::Block { .. } | Node::StaticBlock { .. } => Some(false),
245            Node::SwitchCase { test, .. } if test != Some(child) => Some(false),
246            _ => None,
247        }
248    }
249
250    /// Parses `path`'s last node again from `new` and puts it in place.
251    fn try_piece(
252        &mut self,
253        old: &str,
254        new: &str,
255        path: &[NodeId],
256        body: bool,
257        delta: i64,
258        options: &Options,
259    ) -> Option<Span> {
260        let unit = *path.last()?;
261        let parent = path[path.len() - 2];
262        let span = self.span(unit);
263        let end = u32::try_from(span.end as i64 + delta).ok()?;
264        let walk = self.walk(old, path)?;
265        if !body {
266            // The statement before looked at this one's first token to
267            // decide where it ends: it has to be the same kind of token,
268            // and the same token unless it's a name.
269            let st = options.source_type;
270            let (o, n) = (
271                first_token(old, st, span.start),
272                first_token(new, st, span.start),
273            );
274            let same = o.kind == n.kind
275                && o.flags == n.flags
276                && (o.kind == Kind::Ident || o.text(old) == n.text(new));
277            let module_item = matches!(o.kind, Kind::Keyword(Keyword::Import | Keyword::Export));
278            if !same || module_item {
279                return None;
280            }
281            // A string that starts a statement in a directive prologue
282            // may be a directive, which changes what's strict after it.
283            if o.kind == Kind::String && self.prologue_parent(path) {
284                let items = self.list_of(parent);
285                let at = items.iter().position(|&i| i == unit)?;
286                if items[..at].iter().all(|&i| self.is_directive(i)) {
287                    return None;
288                }
289            }
290        }
291        let Extent { n0, n1, lists } = self.extent(unit)?;
292        let max_depth = options.limits.max_depth.unwrap_or(DEFAULT_MAX_DEPTH);
293        // Each node above takes at most two levels: an expression, and
294        // the statement, function or class it is.
295        let bound = 2 * path.len() as u32;
296        if bound >= max_depth {
297            return None;
298        }
299        let top = matches!(self.node(parent), Node::Program { .. });
300        let piece = parse_piece(
301            new,
302            options,
303            Resume {
304                start: span.start,
305                body,
306                ctx: walk.ctx,
307                labels: walk.labels,
308                classes: walk.classes.len(),
309                depth: if top { 0 } else { bound },
310                max_depth,
311            },
312        )?;
313        if piece.end != end {
314            return None;
315        }
316        // A private name the piece uses is declared by a class around it.
317        let declared = |n: &String| walk.classes.iter().any(|c| c.contains(n));
318        if !piece.private_names.iter().all(declared) {
319            return None;
320        }
321        if body && self.directives(old, unit) != piece_directives(&piece.ast, new) {
322            return None;
323        }
324        let (l0, l1) = match lists {
325            Some(l) => l,
326            // Neither has a list of its own: none move, though ids in
327            // them may.
328            None if !has_lists(&piece.ast) => (0, 0),
329            None if !body => {
330                let p = self.list_point(path)?;
331                (p, p)
332            }
333            None => return None,
334        };
335        // With no entries before, an empty list elsewhere at the same
336        // place could have been made before the piece or after it, and
337        // only one of those moves.
338        if l0 == l1 && piece.ast.lists.len() > 1 && self.empty_list_at(n1 + 1, l0) {
339            return None;
340        }
341        self.splice(piece.ast, (n0, n1, l0, l1), span, end, delta);
342        Some(Span::new(span.start, end))
343    }
344
345    /// The statements in a list-holding node.
346    fn list_of(&self, id: NodeId) -> &[NodeId] {
347        match *self.node(id) {
348            Node::Program { body, .. } | Node::Block { body } | Node::StaticBlock { body } => {
349                self.get(body)
350            }
351            Node::SwitchCase { consequent, .. } => self.get(consequent),
352            _ => &[],
353        }
354    }
355
356    /// Whether `path`'s last node is in a list that has a directive
357    /// prologue: the program's, or a function body's.
358    fn prologue_parent(&self, path: &[NodeId]) -> bool {
359        let parent = path[path.len() - 2];
360        match self.node(parent) {
361            Node::Program { .. } => true,
362            Node::Block { .. } => {
363                path.len() >= 3
364                    && matches!(self.node(path[path.len() - 3]), Node::Function(f) if f.body == parent)
365            }
366            _ => false,
367        }
368    }
369
370    fn is_directive(&self, id: NodeId) -> bool {
371        matches!(
372            self.node(id),
373            Node::Expression {
374                directive: true,
375                ..
376            }
377        )
378    }
379
380    /// The text of the directives a body or program starts with.
381    fn directives<'s>(&self, src: &'s str, id: NodeId) -> Vec<&'s str> {
382        self.list_of(id)
383            .iter()
384            .take_while(|&&i| self.is_directive(i))
385            .map(|&i| self.span(i).text(src))
386            .collect()
387    }
388
389    /// Whether the directives at the start of `id`'s statements say
390    /// `"use strict"`.
391    fn says_use_strict(&self, src: &str, id: NodeId) -> bool {
392        self.list_of(id)
393            .iter()
394            .take_while(|&&i| self.is_directive(i))
395            .any(|&i| match *self.node(i) {
396                Node::Expression { expression, .. } => {
397                    let s = self.span(expression);
398                    s.len() >= 2 && Span::new(s.start + 1, s.end - 1).text(src) == "use strict"
399                }
400                _ => false,
401            })
402    }
403
404    /// What the parser knew on its way down `path` to its last node.
405    fn walk(&self, src: &str, path: &[NodeId]) -> Option<Walk> {
406        let module = matches!(
407            self.node(path[0]),
408            Node::Program {
409                source_type: SourceType::Module,
410                ..
411            }
412        );
413        let mut w = Walk {
414            ctx: Ctx {
415                strict: module,
416                await_: module,
417                ..Ctx::default()
418            },
419            labels: Vec::new(),
420            classes: Vec::new(),
421        };
422        for i in 0..path.len() - 1 {
423            let (p, c) = (path[i], path[i + 1]);
424            match *self.node(p) {
425                Node::Program { .. } => {
426                    if self.says_use_strict(src, p) {
427                        w.ctx.strict = true;
428                    }
429                }
430                Node::Block { .. } => {
431                    let is_body =
432                        i > 0 && matches!(self.node(path[i - 1]), Node::Function(f) if f.body == p);
433                    if is_body && self.says_use_strict(src, p) {
434                        w.ctx.strict = true;
435                    }
436                }
437                Node::Function(f) => {
438                    // A parameter list is checked with what follows it.
439                    if c != f.body {
440                        return None;
441                    }
442                    w.labels.clear();
443                    if f.kind == FunctionKind::Arrow {
444                        w.ctx = Ctx {
445                            yield_: false,
446                            await_: f.is_async,
447                            ret: true,
448                            static_block: false,
449                            loops: 0,
450                            breakable: 0,
451                            labels: 0,
452                            ..w.ctx
453                        };
454                    } else {
455                        let mut ctx = Ctx {
456                            strict: w.ctx.strict,
457                            yield_: f.generator,
458                            await_: f.is_async,
459                            ret: true,
460                            new_target: true,
461                            ..Ctx::default()
462                        };
463                        if let Some(super_call) = self.method_of(&path[..=i]) {
464                            ctx.super_prop = true;
465                            ctx.super_call = super_call;
466                        }
467                        w.ctx = ctx;
468                    }
469                }
470                Node::Class(class) => {
471                    w.ctx.strict = true;
472                    if c == class.body {
473                        w.classes.push(self.private_names(src, class.body));
474                    }
475                }
476                Node::Field { value, .. } if value == Some(c) => {
477                    w.labels.clear();
478                    w.ctx = Ctx {
479                        yield_: false,
480                        await_: false,
481                        ret: false,
482                        new_target: true,
483                        super_prop: true,
484                        super_call: false,
485                        no_arguments: true,
486                        static_block: false,
487                        loops: 0,
488                        breakable: 0,
489                        labels: 0,
490                        ..w.ctx
491                    };
492                }
493                Node::StaticBlock { .. } => {
494                    w.labels.clear();
495                    w.ctx = Ctx {
496                        strict: true,
497                        new_target: true,
498                        super_prop: true,
499                        no_arguments: true,
500                        static_block: true,
501                        ..Ctx::default()
502                    };
503                }
504                Node::While { body, .. }
505                | Node::DoWhile { body, .. }
506                | Node::For { body, .. }
507                | Node::ForIn { body, .. }
508                | Node::ForOf { body, .. }
509                    if body == c =>
510                {
511                    w.ctx.loops += 1;
512                    w.ctx.breakable += 1;
513                }
514                Node::Switch { discriminant, .. } if discriminant != c => w.ctx.breakable += 1,
515                Node::Labeled { label, body } if body == c => {
516                    let span = self.span(label);
517                    let name = text::ident_name(span.text(src)).into_owned();
518                    w.labels.push((name, span, self.labels_loop(body)));
519                }
520                _ => {}
521            }
522        }
523        Some(w)
524    }
525
526    /// Whether a label on `id` labels a loop: `id` is one, or more labels
527    /// on one.
528    fn labels_loop(&self, mut id: NodeId) -> bool {
529        loop {
530            match *self.node(id) {
531                Node::Labeled { body, .. } => id = body,
532                Node::While { .. }
533                | Node::DoWhile { .. }
534                | Node::For { .. }
535                | Node::ForIn { .. }
536                | Node::ForOf { .. } => return true,
537                _ => return false,
538            }
539        }
540    }
541
542    /// If the function at the end of `path` is a method, whether it may
543    /// call `super()`: a derived class's constructor.
544    fn method_of(&self, path: &[NodeId]) -> Option<bool> {
545        let f = path[path.len() - 1];
546        let parent = *path.get(path.len().checked_sub(2)?)?;
547        match *self.node(parent) {
548            Node::Method { value, kind, .. } if value == f => {
549                let class = path.get(path.len().checked_sub(4)?)?;
550                let derived =
551                    matches!(self.node(*class), Node::Class(c) if c.super_class.is_some());
552                Some(kind == MethodKind::Constructor && derived)
553            }
554            Node::Property {
555                value,
556                kind,
557                method,
558                ..
559            } if value == f && (method || kind != PropertyKind::Init) => Some(false),
560            _ => None,
561        }
562    }
563
564    /// The private names a class body declares, without their `#`.
565    fn private_names(&self, src: &str, body: NodeId) -> Vec<String> {
566        let mut names = Vec::new();
567        if let Node::ClassBody { body } = *self.node(body) {
568            for &e in self.get(body) {
569                let key = match *self.node(e) {
570                    Node::Method { key, .. } | Node::Field { key, .. } => key,
571                    _ => continue,
572                };
573                if let Node::PrivateIdentifier = self.node(key) {
574                    let s = self.span(key);
575                    let raw = Span::new(s.start + 1, s.end).text(src);
576                    names.push(text::ident_name(raw).into_owned());
577                }
578            }
579        }
580        names
581    }
582
583    /// The nodes and list entries the subtree at `root` was made of, as
584    /// ranges of the arena: `n0..=root`, and `l0..l1` if it has entries,
585    /// or else where its empty lists say they'd have gone. `None` if
586    /// they aren't ranges of its own alone.
587    fn extent(&self, root: NodeId) -> Option<Extent> {
588        let mut ids = Vec::new();
589        let mut stack = vec![root];
590        while let Some(id) = stack.pop() {
591            ids.push(id.index());
592            self.each_child(id, &mut |c| stack.push(c));
593        }
594        ids.sort_unstable();
595        ids.dedup();
596        let (n0, n1) = (ids[0], root.index());
597        if *ids.last()? != n1 || ids.len() != n1 - n0 + 1 {
598            return None;
599        }
600        let (mut l0, mut l1, mut total) = (usize::MAX, 0, 0);
601        // An empty list's start is where the next entry would have gone;
602        // one at 0 may be `List::default()` instead.
603        let mut empty = None;
604        for &i in &ids {
605            let mut node = self.nodes[i].0;
606            refs(&mut node, &mut |r| {
607                if let Ref::List(l) = r {
608                    if l.len > 0 {
609                        l0 = l0.min(l.start as usize);
610                        l1 = l1.max((l.start + l.len) as usize);
611                        total += l.len as usize;
612                    } else if l.start > 0 {
613                        empty = Some(l.start as usize);
614                    }
615                }
616            });
617        }
618        if total == 0 {
619            let lists = empty.map(|e| (e, e));
620            return Some(Extent { n0, n1, lists });
621        }
622        let lists = Some((l0, l1));
623        (total == l1 - l0).then_some(Extent { n0, n1, lists })
624    }
625
626    /// Whether a node from `from` on has an empty list starting at `at`.
627    fn empty_list_at(&self, from: usize, at: usize) -> bool {
628        let mut found = false;
629        for (node, _) in &self.nodes[from..] {
630            let mut node = *node;
631            refs(&mut node, &mut |r| {
632                if let Ref::List(l) = r {
633                    found |= l.len == 0 && l.start as usize == at;
634                }
635            });
636            if found {
637                return true;
638            }
639        }
640        false
641    }
642
643    /// Where the list entries of `path`'s last node, a statement with
644    /// none, would go: before those of the first statement after it that
645    /// has some, or else before its list's own.
646    fn list_point(&self, path: &[NodeId]) -> Option<usize> {
647        let unit = path[path.len() - 1];
648        let parent = path[path.len() - 2];
649        let items = self.list_of(parent);
650        let at = items.iter().position(|&i| i == unit)?;
651        for &next in &items[at + 1..] {
652            if let Some((l0, l1)) = self.extent(next)?.lists
653                && l1 > l0
654            {
655                return Some(l0);
656            }
657        }
658        let list = match *self.node(parent) {
659            Node::Program { body, .. } | Node::Block { body } | Node::StaticBlock { body } => body,
660            Node::SwitchCase { consequent, .. } => consequent,
661            _ => return None,
662        };
663        Some(list.start as usize)
664    }
665
666    /// Puts `piece`'s nodes in place of `n0..=n1` and its lists in place
667    /// of `l0..l1`, renumbering what comes after, and moves every span,
668    /// comment and warning after the old piece's `span` by `delta`.
669    fn splice(
670        &mut self,
671        piece: Ast,
672        (n0, n1, l0, l1): (usize, usize, usize, usize),
673        span: Span,
674        end: u32,
675        delta: i64,
676    ) {
677        let dn = (piece.nodes.len() - 1) as i64 - (n1 - n0 + 1) as i64;
678        let dl = (piece.lists.len() - 1) as i64 - (l1 - l0) as i64;
679        let moved = |x: u32| {
680            if x >= span.end {
681                (x as i64 + delta) as u32
682            } else {
683                x
684            }
685        };
686        let old_id = |id: NodeId| {
687            if id.index() >= n1 {
688                NodeId::new((id.index() as i64 + dn) as usize)
689            } else {
690                id
691            }
692        };
693        let new_id = |id: NodeId| NodeId::new(id.index() - 1 + n0);
694        // Nodes made before the piece refer to nothing after it, and are
695        // all before it in the source: only those after it change.
696        for (node, s) in &mut self.nodes[n1 + 1..] {
697            *s = Span::new(moved(s.start), moved(s.end));
698            refs(node, &mut |r| match r {
699                Ref::Node(id) => *id = old_id(*id),
700                Ref::List(l) => {
701                    if l.start as usize >= l1 && (l.len > 0 || l.start > 0) {
702                        l.start = (l.start as i64 + dl) as u32;
703                    }
704                }
705            });
706        }
707        // Entries before the piece's hold only ids before it, so this is
708        // all of them that change, wherever the piece's entries go.
709        for id in &mut self.lists[l1.min(l0)..] {
710            *id = old_id(*id);
711        }
712        let mut nodes = piece.nodes;
713        for (node, _) in &mut nodes[1..] {
714            refs(node, &mut |r| match r {
715                Ref::Node(id) => *id = new_id(*id),
716                Ref::List(l) => {
717                    if l.len > 0 || l.start > 0 {
718                        *l = List {
719                            start: l.start - 1 + l0 as u32,
720                            len: l.len,
721                        };
722                    }
723                }
724            });
725        }
726        self.nodes.splice(n0..=n1, nodes.into_iter().skip(1));
727        self.lists
728            .splice(l0..l1, piece.lists.into_iter().skip(1).map(new_id));
729        self.root = self.root.map(old_id);
730        let keep = |s: Span| s.end <= span.start || s.start >= span.end;
731        splice_sorted(
732            &mut self.comments,
733            piece.comments,
734            |c| c.span,
735            |c, s| c.span = s,
736            span,
737            keep,
738            moved,
739        );
740        splice_sorted(
741            &mut self.warnings,
742            piece.warnings,
743            |d| d.span,
744            |d, s| d.span = s,
745            span,
746            keep,
747            moved,
748        );
749        debug_assert!(end >= span.start);
750    }
751}
752
753/// Whether a piece made any list, empty or not.
754fn has_lists(piece: &Ast) -> bool {
755    piece.nodes[1..].iter().any(|(node, _)| {
756        let mut node = *node;
757        let mut any = false;
758        refs(&mut node, &mut |r| {
759            if let Ref::List(l) = r {
760                any |= l.len > 0 || l.start > 0;
761            }
762        });
763        any
764    })
765}
766
767/// The arena ranges a subtree was made of: nodes `n0..=n1`, and list
768/// entries `lists`, empty where its empty lists put it, or `None` if it
769/// has no list.
770struct Extent {
771    n0: usize,
772    n1: usize,
773    lists: Option<(usize, usize)>,
774}
775
776/// What [`Ast::walk`] found.
777struct Walk {
778    ctx: Ctx,
779    labels: Vec<(String, Span, bool)>,
780    /// The private names each class body around declares.
781    classes: Vec<Vec<String>>,
782}
783
784/// The directives a parsed function body starts with.
785fn piece_directives<'s>(piece: &Ast, src: &'s str) -> Vec<&'s str> {
786    piece.directives(src, piece.root())
787}
788
789/// The token at `start`, read as the parser first reads a token.
790fn first_token(src: &str, source: SourceType, start: u32) -> crate::token::Token {
791    Lexer::new(src, source)
792        .starting_at(start, false)
793        .next_token(Goal::Div)
794}
795
796/// Replaces the items of sorted `old` inside `span` with `new`'s, and
797/// moves those after it.
798fn splice_sorted<T>(
799    old: &mut Vec<T>,
800    new: Vec<T>,
801    span_of: impl Fn(&T) -> Span,
802    set: impl Fn(&mut T, Span),
803    span: Span,
804    keep: impl Fn(Span) -> bool,
805    moved: impl Fn(u32) -> u32,
806) {
807    let from = old.partition_point(|t| span_of(t).start < span.start);
808    let to = from + old[from..].iter().take_while(|t| !keep(span_of(t))).count();
809    for t in &mut old[to..] {
810        let s = span_of(t);
811        set(t, Span::new(moved(s.start), moved(s.end)));
812    }
813    old.splice(from..to, new);
814}
815
816#[cfg(test)]
817mod tests {
818    use super::*;
819    use crate::parse_script;
820
821    /// The tree after `edit`, and the one a parse of the new source
822    /// gives, are the same arena, node for node and list for list.
823    fn same(src: &str, at: u32, remove: u32, text: &str) -> Option<(Span, String)> {
824        let options = Options::default();
825        let mut ast = parse_script(src).unwrap();
826        let edit = Edit {
827            range: Span::new(at, at + remove),
828            text,
829        };
830        let done = ast.reparse(src, &edit, &options).unwrap();
831        let full = parse(&done.source, &options).unwrap();
832        assert_eq!(ast.nodes, full.nodes, "{:?}", done.source);
833        assert_eq!(ast.lists, full.lists, "{:?}", done.source);
834        assert_eq!(ast.comments, full.comments);
835        assert_eq!(ast.warnings, full.warnings);
836        assert_eq!(ast.root, full.root);
837        done.reparsed.map(|s| (s, done.source))
838    }
839
840    const SRC: &str = "var a = 1; // one\nfunction f(x) {\n  if (x) { g(x, [1, 2]); }\n  /* two */ return new Foo;\n}\nclass C extends B { #p = 1; constructor() { super(); this.#p++; } }\nlabel: for (;;) { while (a) { continue label; } }\nf(() => { return a ? 010 : b; });\n";
841
842    #[test]
843    fn a_statement_is_parsed_again_in_place() {
844        // Inside `g(x, [1, 2])`: the call's statement, in the block, is
845        // the piece.
846        let at = SRC.find("[1, 2]").unwrap() as u32 + 1;
847        let (span, new) = same(SRC, at, 1, "100, h(3)").unwrap();
848        assert_eq!(span.text(&new), "g(x, [100, h(3), 2]);");
849        // A comment added and one taken away.
850        let at = SRC.find("/* two */").unwrap() as u32;
851        assert!(same(SRC, at + 3, 3, "three").is_some());
852        assert!(same(SRC, at + 2, 0, "*/ /*").is_some());
853    }
854
855    #[test]
856    fn what_was_known_there_is_known_again() {
857        // `super()`, a private name, a labelled `continue` and a legacy
858        // octal in sloppy code, each parsed again where they're allowed.
859        for needle in ["super();", "this.#p++", "continue label", "010"] {
860            let at = SRC.find(needle).unwrap() as u32;
861            assert!(same(SRC, at, 0, " ").is_some(), "{needle}");
862        }
863        // A private name no class declares: the whole source decides, and
864        // it's an error.
865        let mut ast = parse_script(SRC).unwrap();
866        let at = SRC.find("this.#p").unwrap() as u32 + 6;
867        let edit = Edit {
868            range: Span::new(at, at + 1),
869            text: "q",
870        };
871        let err = ast.reparse(SRC, &edit, &Options::default()).unwrap_err();
872        assert_eq!(err.code, "undeclared-private-name");
873        assert_eq!(
874            ast.to_estree(SRC),
875            parse_script(SRC).unwrap().to_estree(SRC)
876        );
877    }
878
879    #[test]
880    fn edits_that_reach_outside_fall_back() {
881        // Opening a comment, a template or a string: the piece no longer
882        // ends where it did.
883        for text in ["/*", "`", "'"] {
884            let at = SRC.find("g(x").unwrap() as u32;
885            let mut ast = parse_script(SRC).unwrap();
886            let edit = Edit {
887                range: Span::new(at, at),
888                text,
889            };
890            if let Ok(done) = ast.reparse(SRC, &edit, &Options::default()) {
891                assert_eq!(done.reparsed, None);
892            }
893        }
894        // `"use strict"` in a prologue changes everything after it.
895        let src = "function f() {\n  'use stric';\n  with (a) {}\n}\n";
896        let mut ast = parse_script(src).unwrap();
897        let edit = Edit {
898            range: Span::new(27, 27),
899            text: "t",
900        };
901        let err = ast.reparse(src, &edit, &Options::default()).unwrap_err();
902        assert_eq!(err.code, "with-in-strict");
903        // An edit that joins two statements.
904        assert_eq!(same("a = b\n;(c)\n", 6, 1, ""), None);
905    }
906
907    #[test]
908    fn a_bad_range_is_refused() {
909        let mut ast = parse_script("é").unwrap();
910        for range in [Span::new(1, 2), Span::new(0, 3)] {
911            let edit = Edit { range, text: "" };
912            let err = ast.reparse("é", &edit, &Options::default()).unwrap_err();
913            assert_eq!(err.code, "edit-out-of-range");
914        }
915    }
916
917    #[test]
918    fn random_edits_keep_the_arena_exact() {
919        let mut seed = 0x9E37_79B9_7F4A_7C15u64;
920        let mut rand = move |n: usize| {
921            seed ^= seed << 13;
922            seed ^= seed >> 7;
923            seed ^= seed << 17;
924            (seed % n as u64) as usize
925        };
926        let pieces = [
927            " ", "\n", "x", "1", ";", "{", "}", "(", ")", "/", "'", "`", "${", "a.b", "f()", "=>",
928        ];
929        let mut reused = 0;
930        for _ in 0..3000 {
931            let at = rand(SRC.len()) as u32;
932            let remove = rand(3).min(SRC.len() - at as usize) as u32;
933            let text = pieces[rand(pieces.len())];
934            let options = Options::default();
935            let mut ast = parse_script(SRC).unwrap();
936            let edit = Edit {
937                range: Span::new(at, at + remove),
938                text,
939            };
940            if !SRC.is_char_boundary((at + remove) as usize) {
941                continue;
942            }
943            match (
944                ast.reparse(SRC, &edit, &options),
945                parse(&edit_src(SRC, &edit), &options),
946            ) {
947                (Ok(done), Ok(full)) => {
948                    assert_eq!(ast.nodes, full.nodes, "{:?}", done.source);
949                    assert_eq!(ast.lists, full.lists, "{:?}", done.source);
950                    assert_eq!(ast.comments, full.comments, "{:?}", done.source);
951                    assert_eq!(ast.root, full.root);
952                    reused += usize::from(done.reparsed.is_some());
953                }
954                (Err(a), Err(b)) => assert_eq!(a, b),
955                (r, f) => panic!(
956                    "{edit:?}: {:?} but {:?}",
957                    r.map(|d| d.reparsed),
958                    f.map(|_| ())
959                ),
960            }
961        }
962        assert!(reused > 300, "{reused}");
963    }
964
965    fn edit_src(src: &str, e: &Edit<'_>) -> String {
966        format!(
967            "{}{}{}",
968            &src[..e.range.start as usize],
969            e.text,
970            &src[e.range.end as usize..]
971        )
972    }
973}