Refine flatten clone for scope.

This commit is contained in:
Stephen Chung 2020-08-03 23:13:09 +08:00
parent 2aa08c0dd9
commit 4a7bf893e6

View File

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