summaryrefslogtreecommitdiff
path: root/src/eval
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2022-06-13 23:16:40 +0200
committerLaurenz <laurmaedje@gmail.com>2022-06-14 13:53:02 +0200
commitc81e2a5f56eb262663f292578c683fba7f18251f (patch)
tree6c045a8dcbec5e75e01a15f970ef8cee6ff042d0 /src/eval
parent891af17260a6750a74a102388a05e59cf1ffc3c1 (diff)
Many fixes
Diffstat (limited to 'src/eval')
-rw-r--r--src/eval/array.rs4
-rw-r--r--src/eval/capture.rs6
-rw-r--r--src/eval/dict.rs14
-rw-r--r--src/eval/func.rs14
-rw-r--r--src/eval/machine.rs2
-rw-r--r--src/eval/methods.rs4
-rw-r--r--src/eval/ops.rs4
-rw-r--r--src/eval/raw.rs2
-rw-r--r--src/eval/scope.rs8
-rw-r--r--src/eval/str.rs7
-rw-r--r--src/eval/value.rs31
11 files changed, 45 insertions, 51 deletions
diff --git a/src/eval/array.rs b/src/eval/array.rs
index fda6f390..aea1b0be 100644
--- a/src/eval/array.rs
+++ b/src/eval/array.rs
@@ -137,7 +137,7 @@ impl Array {
}
/// Return a new array with only those elements for which the function
- /// return true.
+ /// returns true.
pub fn filter(&self, vm: &mut Machine, f: Spanned<Func>) -> TypResult<Self> {
let mut kept = vec![];
for item in self.iter() {
@@ -154,7 +154,7 @@ impl Array {
/// Return a new array with all items from this and nested arrays.
pub fn flatten(&self) -> Self {
- let mut flat = vec![];
+ let mut flat = Vec::with_capacity(self.0.len());
for item in self.iter() {
if let Value::Array(nested) = item {
flat.extend(nested.flatten().into_iter());
diff --git a/src/eval/capture.rs b/src/eval/capture.rs
index 252e9b71..bbda96ad 100644
--- a/src/eval/capture.rs
+++ b/src/eval/capture.rs
@@ -43,8 +43,8 @@ impl<'a> CapturesVisitor<'a> {
match node.cast() {
// Every identifier is a potential variable that we need to capture.
// Identifiers that shouldn't count as captures because they
- // actually bind a new name are handled further below (individually
- // through the expressions that contain them).
+ // actually bind a new name are handled below (individually through
+ // the expressions that contain them).
Some(Expr::Ident(ident)) => self.capture(ident),
// Code and content blocks create a scope.
@@ -179,7 +179,7 @@ mod tests {
test("#import x, y from z", &["z"]);
test("#import x, y, z from x + y", &["x", "y"]);
- // Scoping.
+ // Blocks.
test("{ let x = 1; { let y = 2; y }; x + y }", &["y"]);
test("[#let x = 1]#x", &["x"]);
}
diff --git a/src/eval/dict.rs b/src/eval/dict.rs
index 35bd75d5..8893ce48 100644
--- a/src/eval/dict.rs
+++ b/src/eval/dict.rs
@@ -46,7 +46,7 @@ impl Dict {
}
/// Borrow the value the given `key` maps to.
- pub fn get(&self, key: &EcoString) -> StrResult<&Value> {
+ pub fn get(&self, key: &str) -> StrResult<&Value> {
self.0.get(key).ok_or_else(|| missing_key(key))
}
@@ -59,7 +59,7 @@ impl Dict {
}
/// Whether the dictionary contains a specific key.
- pub fn contains(&self, key: &EcoString) -> bool {
+ pub fn contains(&self, key: &str) -> bool {
self.0.contains_key(key)
}
@@ -69,7 +69,7 @@ impl Dict {
}
/// Remove a mapping by `key`.
- pub fn remove(&mut self, key: &EcoString) -> StrResult<()> {
+ pub fn remove(&mut self, key: &str) -> StrResult<()> {
match Arc::make_mut(&mut self.0).remove(key) {
Some(_) => Ok(()),
None => Err(missing_key(key)),
@@ -87,12 +87,12 @@ impl Dict {
/// Return the keys of the dictionary as an array.
pub fn keys(&self) -> Array {
- self.iter().map(|(key, _)| Value::Str(key.clone())).collect()
+ self.0.keys().cloned().map(Value::Str).collect()
}
/// Return the values of the dictionary as an array.
pub fn values(&self) -> Array {
- self.iter().map(|(_, value)| value.clone()).collect()
+ self.0.values().cloned().collect()
}
/// Transform each pair in the array with a function.
@@ -114,8 +114,8 @@ impl Dict {
/// The missing key access error message.
#[cold]
-fn missing_key(key: &EcoString) -> String {
- format!("dictionary does not contain key {:?}", key)
+fn missing_key(key: &str) -> String {
+ format!("dictionary does not contain key {:?}", EcoString::from(key))
}
impl Debug for Dict {
diff --git a/src/eval/func.rs b/src/eval/func.rs
index 12dbfb2e..7ab03b6a 100644
--- a/src/eval/func.rs
+++ b/src/eval/func.rs
@@ -105,7 +105,7 @@ impl Func {
self.call(&mut vm, args)
}
- /// Execute the function's set rule.
+ /// Execute the function's set rule and return the resulting style map.
pub fn set(&self, mut args: Args) -> TypResult<StyleMap> {
let styles = match self.0.as_ref() {
Repr::Native(Native { set: Some(set), .. }) => set(&mut args)?,
@@ -139,7 +139,7 @@ impl PartialEq for Func {
}
}
-/// A native rust function.
+/// A function defined by a native rust function or node.
struct Native {
/// The name of the function.
pub name: &'static str,
@@ -171,17 +171,17 @@ pub trait Node: 'static {
/// node's set rule.
fn construct(vm: &mut Machine, args: &mut Args) -> TypResult<Content>;
- /// Parse the arguments into style properties for this node.
+ /// Parse relevant arguments into style properties for this node.
///
/// When `constructor` is true, [`construct`](Self::construct) will run
- /// after this invocation of `set`.
+ /// after this invocation of `set` with the remaining arguments.
fn set(args: &mut Args, constructor: bool) -> TypResult<StyleMap>;
}
/// A user-defined closure.
#[derive(Hash)]
pub struct Closure {
- /// The location where the closure was defined.
+ /// The source file where the closure was defined.
pub location: Option<SourceId>,
/// The name of the closure.
pub name: Option<EcoString>,
@@ -199,8 +199,8 @@ pub struct Closure {
impl Closure {
/// Call the function in the context with the arguments.
pub fn call(&self, vm: &mut Machine, args: &mut Args) -> TypResult<Value> {
- // Don't leak the scopes from the call site. Instead, we use the
- // scope of captured variables we collected earlier.
+ // Don't leak the scopes from the call site. Instead, we use the scope
+ // of captured variables we collected earlier.
let mut scopes = Scopes::new(None);
scopes.top = self.captured.clone();
diff --git a/src/eval/machine.rs b/src/eval/machine.rs
index 904a64c8..9c58c659 100644
--- a/src/eval/machine.rs
+++ b/src/eval/machine.rs
@@ -11,7 +11,7 @@ use crate::Context;
pub struct Machine<'a> {
/// The core context.
pub ctx: &'a mut Context,
- /// The route of source ids at which the machine is located.
+ /// The route of source ids the machine took to reach its current location.
pub route: Vec<SourceId>,
/// The dependencies of the current evaluation process.
pub deps: Vec<(SourceId, usize)>,
diff --git a/src/eval/methods.rs b/src/eval/methods.rs
index d425e007..1ac0ce61 100644
--- a/src/eval/methods.rs
+++ b/src/eval/methods.rs
@@ -72,7 +72,7 @@ pub fn call(
Value::Dyn(dynamic) => match method {
"matches" => {
if let Some(regex) = dynamic.downcast::<Regex>() {
- Value::Bool(regex.matches(&args.expect::<EcoString>("text")?))
+ Value::Bool(regex.is_match(&args.expect::<EcoString>("text")?))
} else {
missing()?
}
@@ -125,7 +125,7 @@ pub fn call_mut(
},
Value::Dict(dict) => match method {
- "remove" => dict.remove(&args.expect("key")?).at(span)?,
+ "remove" => dict.remove(&args.expect::<EcoString>("key")?).at(span)?,
_ => missing()?,
},
diff --git a/src/eval/ops.rs b/src/eval/ops.rs
index f88f3cee..95c3c9eb 100644
--- a/src/eval/ops.rs
+++ b/src/eval/ops.rs
@@ -30,7 +30,7 @@ pub fn join(lhs: Value, rhs: Value) -> StrResult<Value> {
})
}
-/// Apply the plus operator to a value.
+/// Apply the unary plus operator to a value.
pub fn pos(value: Value) -> StrResult<Value> {
Ok(match value {
Int(v) => Int(v),
@@ -281,7 +281,7 @@ pub fn eq(lhs: Value, rhs: Value) -> StrResult<Value> {
Ok(Bool(equal(&lhs, &rhs)))
}
-/// Compute whether two values are equal.
+/// Compute whether two values are unequal.
pub fn neq(lhs: Value, rhs: Value) -> StrResult<Value> {
Ok(Bool(!equal(&lhs, &rhs)))
}
diff --git a/src/eval/raw.rs b/src/eval/raw.rs
index ee64b8c4..9cf346b1 100644
--- a/src/eval/raw.rs
+++ b/src/eval/raw.rs
@@ -92,7 +92,7 @@ pub struct RawStroke<T = RawLength> {
}
impl RawStroke<Length> {
- /// Unpack the stroke, filling missing fields with `default`.
+ /// Unpack the stroke, filling missing fields from the `default`.
pub fn unwrap_or(self, default: Stroke) -> Stroke {
Stroke {
paint: self.paint.unwrap_or(default.paint),
diff --git a/src/eval/scope.rs b/src/eval/scope.rs
index 29778a90..7c624de0 100644
--- a/src/eval/scope.rs
+++ b/src/eval/scope.rs
@@ -122,7 +122,7 @@ impl Debug for Scope {
}
}
-/// A slot where a variable is stored.
+/// A slot where a value is stored.
#[derive(Clone, Hash)]
struct Slot {
/// The stored value.
@@ -141,17 +141,17 @@ enum Kind {
}
impl Slot {
- /// Create a new constant slot.
+ /// Create a new slot.
fn new(value: Value, kind: Kind) -> Self {
Self { value, kind }
}
- /// Read the variable.
+ /// Read the value.
fn read(&self) -> &Value {
&self.value
}
- /// Try to write to the variable.
+ /// Try to write to the value.
fn write(&mut self) -> StrResult<&mut Value> {
match self.kind {
Kind::Normal => Ok(&mut self.value),
diff --git a/src/eval/str.rs b/src/eval/str.rs
index 514bf318..a0345312 100644
--- a/src/eval/str.rs
+++ b/src/eval/str.rs
@@ -45,15 +45,10 @@ impl StrExt for EcoString {
pub struct Regex(regex::Regex);
impl Regex {
- /// Create a new regex.
+ /// Create a new regular expression.
pub fn new(re: &str) -> StrResult<Self> {
regex::Regex::new(re).map(Self).map_err(|err| err.to_string())
}
-
- /// Whether the regex matches the given `text`.
- pub fn matches(&self, text: &str) -> bool {
- self.0.is_match(text)
- }
}
impl Deref for Regex {
diff --git a/src/eval/value.rs b/src/eval/value.rs
index 22f8d3cf..a7da99c9 100644
--- a/src/eval/value.rs
+++ b/src/eval/value.rs
@@ -28,7 +28,7 @@ pub enum Value {
Int(i64),
/// A floating-point number: `1.2`, `10e-4`.
Float(f64),
- /// A length: `12pt`, `3cm`.
+ /// A length: `12pt`, `3cm`, `1.5em`.
Length(RawLength),
/// An angle: `1.5rad`, `90deg`.
Angle(Angle),
@@ -532,10 +532,9 @@ impl<T: Cast> Cast for Option<T> {
/// A value that can be automatically determined.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Smart<T> {
- /// The value should be determined smartly based on the
- /// circumstances.
+ /// The value should be determined smartly based on the circumstances.
Auto,
- /// A forced, specific value.
+ /// A specific value.
Custom(T),
}
@@ -629,23 +628,23 @@ where
}
let sides = Sides {
- left: dict.get(&"left".into()).or_else(|_| dict.get(&"x".into())),
- top: dict.get(&"top".into()).or_else(|_| dict.get(&"y".into())),
- right: dict.get(&"right".into()).or_else(|_| dict.get(&"x".into())),
- bottom: dict.get(&"bottom".into()).or_else(|_| dict.get(&"y".into())),
- }
- .map(|side| {
- side.or_else(|_| dict.get(&"rest".into()))
- .and_then(|v| T::cast(v.clone()))
- .unwrap_or_default()
- });
+ left: dict.get("left").or(dict.get("x")),
+ top: dict.get("top").or(dict.get("y")),
+ right: dict.get("right").or(dict.get("x")),
+ bottom: dict.get("bottom").or(dict.get("y")),
+ };
- Ok(sides)
+ Ok(sides.map(|side| {
+ side.or(dict.get("rest"))
+ .cloned()
+ .and_then(T::cast)
+ .unwrap_or_default()
+ }))
}
v => T::cast(v).map(Sides::splat).map_err(|msg| {
with_alternative(
msg,
- "dictionary with any of `left`, `top`, `right`, `bottom`,\
+ "dictionary with any of `left`, `top`, `right`, `bottom`, \
`x`, `y`, or `rest` as keys",
)
}),