summaryrefslogtreecommitdiff
path: root/src/eval
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2021-08-16 18:52:26 +0200
committerLaurenz <laurmaedje@gmail.com>2021-08-16 19:15:03 +0200
commit9462fb17b390c57846b9215217ca7c32b649f0a5 (patch)
treebd6f96fea83c5e757c8f0eefefe5c0347784f00b /src/eval
parentcb0aab3cfab2122a87d1d221290f7178b4291758 (diff)
Convert single-field structs to tuple structs
Diffstat (limited to 'src/eval')
-rw-r--r--src/eval/array.rs40
-rw-r--r--src/eval/dict.rs36
-rw-r--r--src/eval/function.rs18
-rw-r--r--src/eval/mod.rs2
-rw-r--r--src/eval/str.rs46
-rw-r--r--src/eval/template.rs38
6 files changed, 85 insertions, 95 deletions
diff --git a/src/eval/array.rs b/src/eval/array.rs
index ec8f46d3..e554b11e 100644
--- a/src/eval/array.rs
+++ b/src/eval/array.rs
@@ -11,19 +11,17 @@ use crate::diag::StrResult;
#[allow(unused_macros)]
macro_rules! array {
($value:expr; $count:expr) => {
- $crate::eval::Array::from_vec(vec![$crate::eval::Value::from($value); $count])
+ $crate::eval::Array::from_vec(vec![$value.into(); $count])
};
($($value:expr),* $(,)?) => {
- $crate::eval::Array::from_vec(vec![$($crate::eval::Value::from($value)),*])
+ $crate::eval::Array::from_vec(vec![$($value.into()),*])
};
}
/// An array of values with clone-on-write value semantics.
#[derive(Default, Clone, PartialEq)]
-pub struct Array {
- vec: Rc<Vec<Value>>,
-}
+pub struct Array(Rc<Vec<Value>>);
impl Array {
/// Create a new, empty array.
@@ -33,24 +31,24 @@ impl Array {
/// Create a new array from a vector of values.
pub fn from_vec(vec: Vec<Value>) -> Self {
- Self { vec: Rc::new(vec) }
+ Self(Rc::new(vec))
}
/// Whether the array is empty.
pub fn is_empty(&self) -> bool {
- self.vec.is_empty()
+ self.0.is_empty()
}
/// The length of the array.
pub fn len(&self) -> i64 {
- self.vec.len() as i64
+ self.0.len() as i64
}
/// Borrow the value at the given index.
pub fn get(&self, index: i64) -> StrResult<&Value> {
usize::try_from(index)
.ok()
- .and_then(|i| self.vec.get(i))
+ .and_then(|i| self.0.get(i))
.ok_or_else(|| out_of_bounds(index, self.len()))
}
@@ -59,19 +57,19 @@ impl Array {
let len = self.len();
usize::try_from(index)
.ok()
- .and_then(move |i| Rc::make_mut(&mut self.vec).get_mut(i))
+ .and_then(move |i| Rc::make_mut(&mut self.0).get_mut(i))
.ok_or_else(|| out_of_bounds(index, len))
}
/// Push a value to the end of the array.
pub fn push(&mut self, value: Value) {
- Rc::make_mut(&mut self.vec).push(value);
+ Rc::make_mut(&mut self.0).push(value);
}
/// Clear the array.
pub fn clear(&mut self) {
- if Rc::strong_count(&mut self.vec) == 1 {
- Rc::make_mut(&mut self.vec).clear();
+ if Rc::strong_count(&mut self.0) == 1 {
+ Rc::make_mut(&mut self.0).clear();
} else {
*self = Self::new();
}
@@ -79,14 +77,14 @@ impl Array {
/// Iterate over references to the contained values.
pub fn iter(&self) -> std::slice::Iter<Value> {
- self.vec.iter()
+ self.0.iter()
}
/// Repeat this array `n` times.
pub fn repeat(&self, n: i64) -> StrResult<Self> {
let count = usize::try_from(n)
.ok()
- .and_then(|n| self.vec.len().checked_mul(n))
+ .and_then(|n| self.0.len().checked_mul(n))
.ok_or_else(|| format!("cannot repeat this array {} times", n))?;
Ok(self.iter().cloned().cycle().take(count).collect())
@@ -101,7 +99,7 @@ fn out_of_bounds(index: i64, len: i64) -> String {
impl Debug for Array {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- f.debug_list().entries(self.vec.iter()).finish()
+ f.debug_list().entries(self.0.iter()).finish()
}
}
@@ -110,7 +108,7 @@ impl Display for Array {
f.write_char('(')?;
for (i, value) in self.iter().enumerate() {
Display::fmt(value, f)?;
- if i + 1 < self.vec.len() {
+ if i + 1 < self.0.len() {
f.write_str(", ")?;
}
}
@@ -132,7 +130,7 @@ impl Add for Array {
impl AddAssign for Array {
fn add_assign(&mut self, rhs: Array) {
- match Rc::try_unwrap(rhs.vec) {
+ match Rc::try_unwrap(rhs.0) {
Ok(vec) => self.extend(vec),
Err(rc) => self.extend(rc.iter().cloned()),
}
@@ -141,13 +139,13 @@ impl AddAssign for Array {
impl FromIterator<Value> for Array {
fn from_iter<T: IntoIterator<Item = Value>>(iter: T) -> Self {
- Array { vec: Rc::new(iter.into_iter().collect()) }
+ Self(Rc::new(iter.into_iter().collect()))
}
}
impl Extend<Value> for Array {
fn extend<T: IntoIterator<Item = Value>>(&mut self, iter: T) {
- Rc::make_mut(&mut self.vec).extend(iter);
+ Rc::make_mut(&mut self.0).extend(iter);
}
}
@@ -156,7 +154,7 @@ impl IntoIterator for Array {
type IntoIter = std::vec::IntoIter<Value>;
fn into_iter(self) -> Self::IntoIter {
- match Rc::try_unwrap(self.vec) {
+ match Rc::try_unwrap(self.0) {
Ok(vec) => vec.into_iter(),
Err(rc) => (*rc).clone().into_iter(),
}
diff --git a/src/eval/dict.rs b/src/eval/dict.rs
index e71d0c6a..66baaec0 100644
--- a/src/eval/dict.rs
+++ b/src/eval/dict.rs
@@ -13,16 +13,14 @@ macro_rules! dict {
($($key:expr => $value:expr),* $(,)?) => {{
#[allow(unused_mut)]
let mut map = std::collections::BTreeMap::new();
- $(map.insert($crate::eval::Str::from($key), $crate::eval::Value::from($value));)*
+ $(map.insert($key.into(), $value.into());)*
$crate::eval::Dict::from_map(map)
}};
}
/// A dictionary from strings to values with clone-on-write value semantics.
#[derive(Default, Clone, PartialEq)]
-pub struct Dict {
- map: Rc<BTreeMap<Str, Value>>,
-}
+pub struct Dict(Rc<BTreeMap<Str, Value>>);
impl Dict {
/// Create a new, empty dictionary.
@@ -32,22 +30,22 @@ impl Dict {
/// Create a new dictionary from a mapping of strings to values.
pub fn from_map(map: BTreeMap<Str, Value>) -> Self {
- Self { map: Rc::new(map) }
+ Self(Rc::new(map))
}
/// Whether the dictionary is empty.
pub fn is_empty(&self) -> bool {
- self.map.is_empty()
+ self.0.is_empty()
}
/// The number of pairs in the dictionary.
pub fn len(&self) -> i64 {
- self.map.len() as i64
+ self.0.len() as i64
}
/// Borrow the value the given `key` maps to.
pub fn get(&self, key: Str) -> StrResult<&Value> {
- self.map.get(&key).ok_or_else(|| missing_key(&key))
+ self.0.get(&key).ok_or_else(|| missing_key(&key))
}
/// Mutably borrow the value the given `key` maps to.
@@ -55,18 +53,18 @@ impl Dict {
/// This inserts the key with [`None`](Value::None) as the value if not
/// present so far.
pub fn get_mut(&mut self, key: Str) -> &mut Value {
- Rc::make_mut(&mut self.map).entry(key.into()).or_default()
+ Rc::make_mut(&mut self.0).entry(key.into()).or_default()
}
/// Insert a mapping from the given `key` to the given `value`.
pub fn insert(&mut self, key: Str, value: Value) {
- Rc::make_mut(&mut self.map).insert(key.into(), value);
+ Rc::make_mut(&mut self.0).insert(key.into(), value);
}
/// Clear the dictionary.
pub fn clear(&mut self) {
- if Rc::strong_count(&mut self.map) == 1 {
- Rc::make_mut(&mut self.map).clear();
+ if Rc::strong_count(&mut self.0) == 1 {
+ Rc::make_mut(&mut self.0).clear();
} else {
*self = Self::new();
}
@@ -74,7 +72,7 @@ impl Dict {
/// Iterate over pairs of references to the contained keys and values.
pub fn iter(&self) -> std::collections::btree_map::Iter<Str, Value> {
- self.map.iter()
+ self.0.iter()
}
}
@@ -94,7 +92,7 @@ impl Display for Dict {
f.write_str(key)?;
f.write_str(": ")?;
Display::fmt(value, f)?;
- if i + 1 < self.map.len() {
+ if i + 1 < self.0.len() {
f.write_str(", ")?;
}
}
@@ -104,7 +102,7 @@ impl Display for Dict {
impl Debug for Dict {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- f.debug_map().entries(self.map.iter()).finish()
+ f.debug_map().entries(self.0.iter()).finish()
}
}
@@ -119,7 +117,7 @@ impl Add for Dict {
impl AddAssign for Dict {
fn add_assign(&mut self, rhs: Dict) {
- match Rc::try_unwrap(rhs.map) {
+ match Rc::try_unwrap(rhs.0) {
Ok(map) => self.extend(map),
Err(rc) => self.extend(rc.iter().map(|(k, v)| (k.clone(), v.clone()))),
}
@@ -128,13 +126,13 @@ impl AddAssign for Dict {
impl FromIterator<(Str, Value)> for Dict {
fn from_iter<T: IntoIterator<Item = (Str, Value)>>(iter: T) -> Self {
- Dict { map: Rc::new(iter.into_iter().collect()) }
+ Self(Rc::new(iter.into_iter().collect()))
}
}
impl Extend<(Str, Value)> for Dict {
fn extend<T: IntoIterator<Item = (Str, Value)>>(&mut self, iter: T) {
- Rc::make_mut(&mut self.map).extend(iter);
+ Rc::make_mut(&mut self.0).extend(iter);
}
}
@@ -143,7 +141,7 @@ impl IntoIterator for Dict {
type IntoIter = std::collections::btree_map::IntoIter<Str, Value>;
fn into_iter(self) -> Self::IntoIter {
- match Rc::try_unwrap(self.map) {
+ match Rc::try_unwrap(self.0) {
Ok(map) => map.into_iter(),
Err(rc) => (*rc).clone().into_iter(),
}
diff --git a/src/eval/function.rs b/src/eval/function.rs
index 85608ca1..7967090b 100644
--- a/src/eval/function.rs
+++ b/src/eval/function.rs
@@ -8,12 +8,10 @@ use crate::util::EcoString;
/// An evaluatable function.
#[derive(Clone)]
-pub struct Function {
- repr: Rc<Repr<Func>>,
-}
+pub struct Function(Rc<Inner<Func>>);
-/// The unsized representation behind the [`Rc`].
-struct Repr<T: ?Sized> {
+/// The unsized structure behind the [`Rc`].
+struct Inner<T: ?Sized> {
name: Option<EcoString>,
func: T,
}
@@ -26,17 +24,17 @@ impl Function {
where
F: Fn(&mut EvalContext, &mut Arguments) -> TypResult<Value> + 'static,
{
- Self { repr: Rc::new(Repr { name, func }) }
+ Self(Rc::new(Inner { name, func }))
}
/// The name of the function.
pub fn name(&self) -> Option<&EcoString> {
- self.repr.name.as_ref()
+ self.0.name.as_ref()
}
/// Call the function in the context with the arguments.
pub fn call(&self, ctx: &mut EvalContext, args: &mut Arguments) -> TypResult<Value> {
- (&self.repr.func)(ctx, args)
+ (&self.0.func)(ctx, args)
}
}
@@ -53,14 +51,14 @@ impl Display for Function {
impl Debug for Function {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- f.debug_struct("Function").field("name", &self.repr.name).finish()
+ f.debug_struct("Function").field("name", &self.0.name).finish()
}
}
impl PartialEq for Function {
fn eq(&self, other: &Self) -> bool {
// We cast to thin pointers for comparison.
- Rc::as_ptr(&self.repr) as *const () == Rc::as_ptr(&other.repr) as *const ()
+ Rc::as_ptr(&self.0) as *const () == Rc::as_ptr(&other.0) as *const ()
}
}
diff --git a/src/eval/mod.rs b/src/eval/mod.rs
index a03c83b6..d8ce7884 100644
--- a/src/eval/mod.rs
+++ b/src/eval/mod.rs
@@ -376,7 +376,7 @@ impl Eval for CallExpr {
}
Value::Func(func) => {
- let point = || Tracepoint::Call(func.name().map(Into::into));
+ let point = || Tracepoint::Call(func.name().map(ToString::to_string));
let value = func.call(ctx, &mut args).trace(point, self.span)?;
args.finish()?;
Ok(value)
diff --git a/src/eval/str.rs b/src/eval/str.rs
index 7f84f80f..1a0e3e1f 100644
--- a/src/eval/str.rs
+++ b/src/eval/str.rs
@@ -7,9 +7,7 @@ use crate::util::EcoString;
/// A string value with inline storage and clone-on-write semantics.
#[derive(Default, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
-pub struct Str {
- string: EcoString,
-}
+pub struct Str(EcoString);
impl Str {
/// Create a new, empty string.
@@ -19,17 +17,17 @@ impl Str {
/// Whether the string is empty.
pub fn is_empty(&self) -> bool {
- self.string.is_empty()
+ self.0.is_empty()
}
/// The length of the string in bytes.
pub fn len(&self) -> i64 {
- self.string.len() as i64
+ self.0.len() as i64
}
/// Borrow this as a string slice.
pub fn as_str(&self) -> &str {
- self.string.as_str()
+ self.0.as_str()
}
/// Return an iterator over the chars as strings.
@@ -41,10 +39,10 @@ impl Str {
pub fn repeat(&self, n: i64) -> StrResult<Self> {
let n = usize::try_from(n)
.ok()
- .and_then(|n| self.string.len().checked_mul(n).map(|_| n))
+ .and_then(|n| self.0.len().checked_mul(n).map(|_| n))
.ok_or_else(|| format!("cannot repeat this string {} times", n))?;
- Ok(self.string.repeat(n).into())
+ Ok(self.0.repeat(n).into())
}
}
@@ -67,7 +65,7 @@ impl Display for Str {
impl Debug for Str {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- Debug::fmt(&self.string, f)
+ Debug::fmt(&self.0, f)
}
}
@@ -75,7 +73,7 @@ impl Deref for Str {
type Target = str;
fn deref(&self) -> &str {
- self.string.deref()
+ self.0.deref()
}
}
@@ -90,48 +88,48 @@ impl Add for Str {
impl AddAssign for Str {
fn add_assign(&mut self, rhs: Self) {
- self.string.push_str(rhs.as_str());
+ self.0.push_str(rhs.as_str());
}
}
impl From<char> for Str {
fn from(c: char) -> Self {
- Self { string: c.into() }
+ Self(c.into())
}
}
impl From<&str> for Str {
- fn from(string: &str) -> Self {
- Self { string: string.into() }
+ fn from(s: &str) -> Self {
+ Self(s.into())
}
}
impl From<String> for Str {
- fn from(string: String) -> Self {
- Self { string: string.into() }
+ fn from(s: String) -> Self {
+ Self(s.into())
}
}
impl From<EcoString> for Str {
- fn from(string: EcoString) -> Self {
- Self { string }
+ fn from(s: EcoString) -> Self {
+ Self(s)
}
}
impl From<&EcoString> for Str {
- fn from(string: &EcoString) -> Self {
- Self { string: string.clone() }
+ fn from(s: &EcoString) -> Self {
+ Self(s.clone())
}
}
impl From<Str> for EcoString {
- fn from(string: Str) -> Self {
- string.string
+ fn from(s: Str) -> Self {
+ s.0
}
}
impl From<&Str> for EcoString {
- fn from(string: &Str) -> Self {
- string.string.clone()
+ fn from(s: &Str) -> Self {
+ s.0.clone()
}
}
diff --git a/src/eval/template.rs b/src/eval/template.rs
index 594036af..96aa8a86 100644
--- a/src/eval/template.rs
+++ b/src/eval/template.rs
@@ -12,31 +12,29 @@ use crate::util::EcoString;
/// A template value: `[*Hi* there]`.
#[derive(Debug, Default, Clone)]
-pub struct Template {
- nodes: Rc<Vec<TemplateNode>>,
-}
+pub struct Template(Rc<Vec<TemplateNode>>);
impl Template {
/// Create a new template from a vector of nodes.
pub fn new(nodes: Vec<TemplateNode>) -> Self {
- Self { nodes: Rc::new(nodes) }
+ Self(Rc::new(nodes))
}
/// Iterate over the contained template nodes.
pub fn iter(&self) -> std::slice::Iter<TemplateNode> {
- self.nodes.iter()
+ self.0.iter()
}
/// Repeat this template `n` times.
pub fn repeat(&self, n: i64) -> StrResult<Self> {
let count = usize::try_from(n)
.ok()
- .and_then(|n| self.nodes.len().checked_mul(n))
+ .and_then(|n| self.0.len().checked_mul(n))
.ok_or_else(|| format!("cannot repeat this template {} times", n))?;
- Ok(Self {
- nodes: Rc::new(self.iter().cloned().cycle().take(count).collect()),
- })
+ Ok(Self(Rc::new(
+ self.iter().cloned().cycle().take(count).collect(),
+ )))
}
}
@@ -48,7 +46,7 @@ impl Display for Template {
impl PartialEq for Template {
fn eq(&self, other: &Self) -> bool {
- Rc::ptr_eq(&self.nodes, &other.nodes)
+ Rc::ptr_eq(&self.0, &other.0)
}
}
@@ -63,8 +61,8 @@ impl Add for Template {
impl AddAssign for Template {
fn add_assign(&mut self, rhs: Template) {
- let sink = Rc::make_mut(&mut self.nodes);
- match Rc::try_unwrap(rhs.nodes) {
+ let sink = Rc::make_mut(&mut self.0);
+ match Rc::try_unwrap(rhs.0) {
Ok(source) => sink.extend(source),
Err(rc) => sink.extend(rc.iter().cloned()),
}
@@ -75,7 +73,7 @@ impl Add<Str> for Template {
type Output = Self;
fn add(mut self, rhs: Str) -> Self::Output {
- Rc::make_mut(&mut self.nodes).push(TemplateNode::Str(rhs.into()));
+ Rc::make_mut(&mut self.0).push(TemplateNode::Str(rhs.into()));
self
}
}
@@ -84,7 +82,7 @@ impl Add<Template> for Str {
type Output = Template;
fn add(self, mut rhs: Template) -> Self::Output {
- Rc::make_mut(&mut rhs.nodes).insert(0, TemplateNode::Str(self.into()));
+ Rc::make_mut(&mut rhs.0).insert(0, TemplateNode::Str(self.into()));
rhs
}
}
@@ -154,6 +152,12 @@ impl TemplateFunc {
}
}
+impl Debug for TemplateFunc {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ f.debug_struct("TemplateFunc").finish()
+ }
+}
+
impl Deref for TemplateFunc {
type Target = dyn Fn(&mut ExecContext);
@@ -161,9 +165,3 @@ impl Deref for TemplateFunc {
self.0.as_ref()
}
}
-
-impl Debug for TemplateFunc {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- f.debug_struct("TemplateFunc").finish()
- }
-}