git.delta.rocks / jrsonnet / refs/commits / ff3e2c836938

difftreelog

source

crates/jrsonnet-evaluator/src/ctx.rs4.1 KiBsourcehistory
1use std::fmt::Debug;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;56use crate::{7	error::Error::*, gc::GcHashMap, map::LayeredHashMap, ObjValue, Pending, Result, Thunk, Val,8};910#[derive(Trace)]11struct ContextInternals {12	dollar: Option<ObjValue>,13	sup: Option<ObjValue>,14	this: Option<ObjValue>,15	bindings: LayeredHashMap,16}17impl Debug for ContextInternals {18	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {19		f.debug_struct("Context").finish()20	}21}2223/// Context keeps information about current lexical code location24///25/// This information includes local variables, top-level object (`$`), current object (`this`), and super object (`super`)26#[derive(Debug, Clone, Trace)]27pub struct Context(Cc<ContextInternals>);28impl Context {29	pub fn new_future() -> Pending<Self> {30		Pending::new()31	}3233	pub fn dollar(&self) -> &Option<ObjValue> {34		&self.0.dollar35	}3637	pub fn this(&self) -> &Option<ObjValue> {38		&self.0.this39	}4041	pub fn super_obj(&self) -> &Option<ObjValue> {42		&self.0.sup43	}4445	pub fn new() -> Self {46		Self(Cc::new(ContextInternals {47			dollar: None,48			this: None,49			sup: None,50			bindings: LayeredHashMap::default(),51		}))52	}5354	#[cfg(not(feature = "friendly-errors"))]55	pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {56		Ok(self57			.058			.bindings59			.get(&name)60			.cloned()61			.ok_or(VariableIsNotDefined(name, vec![]))?)62	}6364	#[cfg(feature = "friendly-errors")]65	pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {66		use std::cmp::Ordering;6768		use crate::throw;6970		if let Some(val) = self.0.bindings.get(&name).cloned() {71			return Ok(val);72		}7374		let mut heap = Vec::new();75		self.0.bindings.clone().iter_keys(|k| {76			let conf = strsim::jaro_winkler(&k as &str, &name as &str);77			if conf < 0.8 {78				return;79			}80			heap.push((conf, k));81		});82		heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));8384		throw!(VariableIsNotDefined(85			name,86			heap.into_iter().map(|(_, k)| k).collect()87		))88	}89	pub fn contains_binding(&self, name: IStr) -> bool {90		self.0.bindings.contains_key(&name)91	}92	#[must_use]93	pub fn into_future(self, ctx: Pending<Self>) -> Self {94		{95			ctx.0.borrow_mut().replace(self);96		}97		ctx.unwrap()98	}99100	#[must_use]101	pub fn with_var(self, name: IStr, value: Val) -> Self {102		let mut new_bindings = GcHashMap::with_capacity(1);103		new_bindings.insert(name, Thunk::evaluated(value));104		self.extend(new_bindings, None, None, None)105	}106107	#[must_use]108	pub fn extend(109		self,110		new_bindings: GcHashMap<IStr, Thunk<Val>>,111		new_dollar: Option<ObjValue>,112		new_sup: Option<ObjValue>,113		new_this: Option<ObjValue>,114	) -> Self {115		let ctx = &self.0;116		let dollar = new_dollar.or_else(|| ctx.dollar.clone());117		let this = new_this.or_else(|| ctx.this.clone());118		let sup = new_sup.or_else(|| ctx.sup.clone());119		let bindings = if new_bindings.is_empty() {120			ctx.bindings.clone()121		} else {122			ctx.bindings.clone().extend(new_bindings)123		};124		Self(Cc::new(ContextInternals {125			dollar,126			sup,127			this,128			bindings,129		}))130	}131}132133impl Default for Context {134	fn default() -> Self {135		Self::new()136	}137}138139impl PartialEq for Context {140	fn eq(&self, other: &Self) -> bool {141		Cc::ptr_eq(&self.0, &other.0)142	}143}144145pub struct ContextBuilder {146	bindings: GcHashMap<IStr, Thunk<Val>>,147	extend: Option<Context>,148}149150impl ContextBuilder {151	pub fn new() -> Self {152		Self::with_capacity(0)153	}154	pub fn with_capacity(capacity: usize) -> Self {155		Self {156			bindings: GcHashMap::with_capacity(capacity),157			extend: None,158		}159	}160	pub fn extend(parent: Context) -> Self {161		Self {162			bindings: GcHashMap::new(),163			extend: Some(parent),164		}165	}166	/// # Panics167	/// If `name` is already bound168	pub fn bind(&mut self, name: IStr, value: Thunk<Val>) -> &mut Self {169		let old = self.bindings.insert(name, value);170		assert!(old.is_none(), "variable bound twice in single context call");171		self172	}173	pub fn build(self) -> Context {174		if let Some(parent) = self.extend {175			parent.extend(self.bindings, None, None, None)176		} else {177			Context(Cc::new(ContextInternals {178				bindings: LayeredHashMap::new(self.bindings),179				dollar: None,180				sup: None,181				this: None,182			}))183		}184	}185}186187impl Default for ContextBuilder {188	fn default() -> Self {189		Self::new()190	}191}