summaryrefslogtreecommitdiff
path: root/src/eval
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2021-01-15 16:53:02 +0100
committerLaurenz <laurmaedje@gmail.com>2021-01-15 16:53:02 +0100
commitd763f0f5a6a700352ee8926c15c8e58624f705c9 (patch)
treed287edfdab9793a796404516c7313689e4e69964 /src/eval
parent0f0416054f263b80ccec1a463ce4ab20913bdf71 (diff)
Split state and scopes, less ref-counting 🔀
Diffstat (limited to 'src/eval')
-rw-r--r--src/eval/call.rs15
-rw-r--r--src/eval/context.rs14
-rw-r--r--src/eval/mod.rs22
-rw-r--r--src/eval/scope.rs41
-rw-r--r--src/eval/state.rs37
5 files changed, 88 insertions, 41 deletions
diff --git a/src/eval/call.rs b/src/eval/call.rs
index f47ee847..8e75f17c 100644
--- a/src/eval/call.rs
+++ b/src/eval/call.rs
@@ -8,7 +8,7 @@ impl Eval for Spanned<&ExprCall> {
let name = &self.v.name.v;
let span = self.v.name.span;
- if let Some(value) = ctx.state.scope.get(name) {
+ if let Some(value) = ctx.scopes.get(name) {
if let Value::Func(func) = value {
let func = func.clone();
ctx.deco(Deco::Resolved.with_span(span));
@@ -90,10 +90,10 @@ impl Args {
}
/// Filter out and remove all convertible positional arguments.
- pub fn filter<'a, T>(
+ pub fn filter<'a, 'b: 'a, T>(
&'a mut self,
- ctx: &'a mut EvalContext,
- ) -> impl Iterator<Item = T> + 'a
+ ctx: &'a mut EvalContext<'b>,
+ ) -> impl Iterator<Item = T> + Captures<'a> + Captures<'b>
where
T: Cast<Spanned<Value>>,
{
@@ -130,6 +130,13 @@ impl Args {
}
}
+// This is a workaround because `-> impl Trait + 'a + 'b` does not work.
+//
+// See also: https://github.com/rust-lang/rust/issues/49431
+#[doc(hidden)]
+pub trait Captures<'a> {}
+impl<'a, T: ?Sized> Captures<'a> for T {}
+
/// Cast the value into `T`, generating an error if the conversion fails.
fn cast<T>(ctx: &mut EvalContext, value: Spanned<Value>) -> Option<T>
where
diff --git a/src/eval/context.rs b/src/eval/context.rs
index 1e09aaaf..a998bbdc 100644
--- a/src/eval/context.rs
+++ b/src/eval/context.rs
@@ -6,7 +6,6 @@ use fontdock::FontStyle;
use super::*;
use crate::diag::Diag;
use crate::diag::{Deco, Feedback, Pass};
-use crate::env::SharedEnv;
use crate::geom::{ChildAlign, Dir, Gen, LayoutDirs, Length, Linear, Sides, Size};
use crate::layout::{
Expansion, Node, NodePad, NodePages, NodePar, NodeSpacing, NodeStack, NodeText, Tree,
@@ -14,9 +13,11 @@ use crate::layout::{
/// The context for evaluation.
#[derive(Debug)]
-pub struct EvalContext {
+pub struct EvalContext<'a> {
/// The environment from which resources are gathered.
- pub env: SharedEnv,
+ pub env: &'a mut Env,
+ /// The active scopes.
+ pub scopes: Scopes<'a>,
/// The active evaluation state.
pub state: State,
/// The accumulated feedback.
@@ -34,11 +35,12 @@ pub struct EvalContext {
inner: Vec<Node>,
}
-impl EvalContext {
- /// Create a new evaluation context with a base state.
- pub fn new(env: SharedEnv, state: State) -> Self {
+impl<'a> EvalContext<'a> {
+ /// Create a new evaluation context with a base state and scope.
+ pub fn new(env: &'a mut Env, scope: &'a Scope, state: State) -> Self {
Self {
env,
+ scopes: Scopes::new(scope),
state,
groups: vec![],
inner: vec![],
diff --git a/src/eval/mod.rs b/src/eval/mod.rs
index 9abc1074..efc77f69 100644
--- a/src/eval/mod.rs
+++ b/src/eval/mod.rs
@@ -18,17 +18,23 @@ use std::rc::Rc;
use crate::color::Color;
use crate::diag::Pass;
-use crate::env::SharedEnv;
+use crate::env::Env;
use crate::geom::{Angle, Length, Relative, Spec};
use crate::layout::{self, Expansion, NodeSpacing, NodeStack};
use crate::syntax::*;
/// Evaluate a syntax tree into a layout tree.
///
-/// The given `state` is the base state that may be updated over the course of
-/// evaluation.
-pub fn eval(tree: &Tree, env: SharedEnv, state: State) -> Pass<layout::Tree> {
- let mut ctx = EvalContext::new(env, state);
+/// The `state` is the base state that may be updated over the course of
+/// evaluation. The `scope` similarly consists of the base definitions that are
+/// present from the beginning (typically, the standard library).
+pub fn eval(
+ tree: &Tree,
+ env: &mut Env,
+ scope: &Scope,
+ state: State,
+) -> Pass<layout::Tree> {
+ let mut ctx = EvalContext::new(env, scope, state);
ctx.start_page_group(Softness::Hard);
tree.eval(&mut ctx);
ctx.end_page_group(|s| s == Softness::Hard);
@@ -118,7 +124,7 @@ impl Eval for Spanned<&NodeRaw> {
fn eval(self, ctx: &mut EvalContext) -> Self::Output {
let prev = Rc::clone(&ctx.state.font.families);
- let families = Rc::make_mut(&mut ctx.state.font.families);
+ let families = ctx.state.font.families_mut();
families.list.insert(0, "monospace".to_string());
families.flatten();
@@ -151,7 +157,7 @@ impl Eval for Spanned<&Expr> {
fn eval(self, ctx: &mut EvalContext) -> Self::Output {
match self.v {
Expr::None => Value::None,
- Expr::Ident(v) => match ctx.state.scope.get(v) {
+ Expr::Ident(v) => match ctx.scopes.get(v) {
Some(value) => value.clone(),
None => {
ctx.diag(error!(self.span, "unknown variable"));
@@ -179,7 +185,7 @@ impl Eval for Spanned<&Expr> {
Some(expr) => expr.as_ref().eval(ctx),
None => Value::None,
};
- Rc::make_mut(&mut ctx.state.scope).set(v.pat.v.as_str(), value);
+ ctx.scopes.define(v.pat.v.as_str(), value);
Value::None
}
}
diff --git a/src/eval/scope.rs b/src/eval/scope.rs
index dd7cc1da..62ee7e40 100644
--- a/src/eval/scope.rs
+++ b/src/eval/scope.rs
@@ -1,27 +1,58 @@
use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter};
+use std::iter;
use super::Value;
-/// A map from identifiers to values.
+/// A hierarchy of scopes.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Scopes<'a> {
+ /// The active scope.
+ top: Scope,
+ /// The stack of lower scopes.
+ scopes: Vec<Scope>,
+ /// The base scope.
+ base: &'a Scope,
+}
+
+impl<'a> Scopes<'a> {
+ /// Create a new hierarchy of scopes.
+ pub fn new(base: &'a Scope) -> Self {
+ Self { top: Scope::new(), scopes: vec![], base }
+ }
+
+ /// Look up the value of a variable in the scopes.
+ pub fn get(&self, var: &str) -> Option<&Value> {
+ iter::once(&self.top)
+ .chain(&self.scopes)
+ .chain(iter::once(self.base))
+ .find_map(|scope| scope.get(var))
+ }
+
+ /// Define a variable in the active scope.
+ pub fn define(&mut self, var: impl Into<String>, value: impl Into<Value>) {
+ self.top.set(var, value);
+ }
+}
+
+/// A map from variable names to values.
#[derive(Default, Clone, PartialEq)]
pub struct Scope {
values: HashMap<String, Value>,
}
impl Scope {
- // Create a new empty scope with a fallback function that is invoked when no
- // match is found.
+ // Create a new empty scope.
pub fn new() -> Self {
Self::default()
}
- /// Return the value of the given variable.
+ /// Look up the value of a variable.
pub fn get(&self, var: &str) -> Option<&Value> {
self.values.get(var)
}
- /// Store the value for the given variable.
+ /// Store the value for a variable.
pub fn set(&mut self, var: impl Into<String>, value: impl Into<Value>) {
self.values.insert(var.into(), value.into());
}
diff --git a/src/eval/state.rs b/src/eval/state.rs
index ce6bd009..a88dfd07 100644
--- a/src/eval/state.rs
+++ b/src/eval/state.rs
@@ -2,7 +2,6 @@ use std::rc::Rc;
use fontdock::{fallback, FallbackTree, FontStretch, FontStyle, FontVariant, FontWeight};
-use super::Scope;
use crate::geom::{
Align, ChildAlign, Dir, LayoutDirs, Length, Linear, Relative, Sides, Size, Spec,
};
@@ -12,14 +11,12 @@ use crate::paper::{Paper, PaperClass, PAPER_A4};
/// The evaluation state.
#[derive(Debug, Clone, PartialEq)]
pub struct State {
- /// The scope that contains variable definitions.
- pub scope: Rc<Scope>,
/// The current page state.
- pub page: StatePage,
+ pub page: PageSettings,
/// The current paragraph state.
- pub par: StatePar,
+ pub par: ParSettings,
/// The current font state.
- pub font: StateFont,
+ pub font: FontSettings,
/// The current directions.
pub dirs: LayoutDirs,
/// The current alignments.
@@ -29,10 +26,9 @@ pub struct State {
impl Default for State {
fn default() -> Self {
Self {
- scope: Rc::new(crate::library::_std()),
- page: StatePage::default(),
- par: StatePar::default(),
- font: StateFont::default(),
+ page: PageSettings::default(),
+ par: ParSettings::default(),
+ font: FontSettings::default(),
dirs: LayoutDirs::new(Dir::TTB, Dir::LTR),
align: ChildAlign::new(Align::Start, Align::Start),
}
@@ -41,7 +37,7 @@ impl Default for State {
/// Defines page properties.
#[derive(Debug, Copy, Clone, PartialEq)]
-pub struct StatePage {
+pub struct PageSettings {
/// The class of this page.
pub class: PaperClass,
/// The width and height of the page.
@@ -53,7 +49,7 @@ pub struct StatePage {
pub margins: Sides<Option<Linear>>,
}
-impl StatePage {
+impl PageSettings {
/// The default page style for the given paper.
pub fn new(paper: Paper) -> Self {
Self {
@@ -76,7 +72,7 @@ impl StatePage {
}
}
-impl Default for StatePage {
+impl Default for PageSettings {
fn default() -> Self {
Self::new(PAPER_A4)
}
@@ -84,7 +80,7 @@ impl Default for StatePage {
/// Defines paragraph properties.
#[derive(Debug, Copy, Clone, PartialEq)]
-pub struct StatePar {
+pub struct ParSettings {
/// The spacing between words (dependent on scaled font size).
pub word_spacing: Linear,
/// The spacing between lines (dependent on scaled font size).
@@ -93,7 +89,7 @@ pub struct StatePar {
pub par_spacing: Linear,
}
-impl Default for StatePar {
+impl Default for ParSettings {
fn default() -> Self {
Self {
word_spacing: Relative::new(0.25).into(),
@@ -105,7 +101,7 @@ impl Default for StatePar {
/// Defines font properties.
#[derive(Debug, Clone, PartialEq)]
-pub struct StateFont {
+pub struct FontSettings {
/// A tree of font family names and generic class names.
pub families: Rc<FallbackTree>,
/// The selected font variant.
@@ -122,14 +118,19 @@ pub struct StateFont {
pub emph: bool,
}
-impl StateFont {
+impl FontSettings {
+ /// Access the `families` mutably.
+ pub fn families_mut(&mut self) -> &mut FallbackTree {
+ Rc::make_mut(&mut self.families)
+ }
+
/// The absolute font size.
pub fn font_size(&self) -> Length {
self.scale.resolve(self.size)
}
}
-impl Default for StateFont {
+impl Default for FontSettings {
fn default() -> Self {
Self {
/// The default tree of font fallbacks.