Use Scope::flatten_clone for capturing.

This commit is contained in:
Stephen Chung
2020-07-30 23:29:30 +08:00
parent 7d4620d0d9
commit a7ff207636
3 changed files with 34 additions and 18 deletions

View File

@@ -4,7 +4,9 @@ use crate::any::{Dynamic, Variant};
use crate::parser::{map_dynamic_to_expr, Expr};
use crate::token::Position;
use crate::stdlib::{borrow::Cow, boxed::Box, iter, string::String, vec::Vec};
use crate::stdlib::{
borrow::Cow, boxed::Box, collections::HashMap, iter, string::String, vec::Vec,
};
/// Type of an entry in the Scope.
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
@@ -389,13 +391,28 @@ impl<'a> Scope<'a> {
self
}
/// Clone the Scope, keeping only the last instances of each variable name.
/// Shadowed variables are omitted in the copy.
#[cfg(not(feature = "no_capture"))]
pub(crate) fn flatten_clone(&self) -> Self {
let mut entries: HashMap<&str, Entry> = Default::default();
self.0.iter().rev().for_each(|entry| {
entries
.entry(entry.name.as_ref())
.or_insert_with(|| entry.clone());
});
Self(entries.into_iter().map(|(_, v)| v).collect())
}
/// Get an iterator to entries in the Scope.
#[cfg(not(feature = "no_module"))]
pub(crate) fn into_iter(self) -> impl Iterator<Item = Entry<'a>> {
self.0.into_iter()
}
/// Get an iterator to entries in the Scope.
/// Get an iterator to entries in the Scope in reverse order.
pub(crate) fn to_iter(&self) -> impl Iterator<Item = &Entry> {
self.0.iter().rev() // Always search a Scope in reverse order
}