Add a Snapshot abstraction for deferring and restoring visitor context (#4353)

This commit is contained in:
Charlie Marsh 2023-05-10 12:50:47 -04:00 committed by GitHub
parent fd34797d0f
commit ea3d3a655d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 81 additions and 84 deletions

View file

@ -19,6 +19,15 @@ use crate::binding::{
use crate::node::{NodeId, Nodes};
use crate::scope::{Scope, ScopeId, ScopeKind, Scopes};
/// A snapshot of the [`Context`] at a given point in the AST traversal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Snapshot {
scope_id: ScopeId,
stmt_id: Option<NodeId>,
in_annotation: bool,
in_type_checking_block: bool,
}
#[allow(clippy::struct_excessive_bools)]
pub struct Context<'a> {
pub typing_modules: &'a [String],
@ -435,4 +444,22 @@ impl<'a> Context<'a> {
}
exceptions
}
/// Generate a [`Snapshot`] of the current context.
pub fn snapshot(&self) -> Snapshot {
Snapshot {
scope_id: self.scope_id,
stmt_id: self.stmt_id,
in_annotation: self.in_annotation,
in_type_checking_block: self.in_type_checking_block,
}
}
/// Restore the context to the given [`Snapshot`].
pub fn restore(&mut self, snapshot: Snapshot) {
self.scope_id = snapshot.scope_id;
self.stmt_id = snapshot.stmt_id;
self.in_annotation = snapshot.in_annotation;
self.in_type_checking_block = snapshot.in_type_checking_block;
}
}

View file

@ -30,6 +30,7 @@ impl From<NodeId> for usize {
}
}
/// A [`Node`] represents a statement in a program, along with a pointer to its parent (if any).
#[derive(Debug)]
struct Node<'a> {
/// The statement this node represents.