diff options
| author | Laurenz <laurmaedje@gmail.com> | 2020-01-24 12:44:04 +0100 |
|---|---|---|
| committer | Laurenz <laurmaedje@gmail.com> | 2020-01-24 12:44:04 +0100 |
| commit | 03fddaf3aea778057aedd74dbcb27bae971ec22f (patch) | |
| tree | 37e3136e29e0e5d69ec8f56e43d156739d2931ab /src/syntax | |
| parent | 78da2bdd5d77d1b8572e5e9da119bfa68127a3fa (diff) | |
Non-fatal argument parsing 🌋
Diffstat (limited to 'src/syntax')
| -rw-r--r-- | src/syntax/expr.rs | 230 | ||||
| -rw-r--r-- | src/syntax/func/keys.rs | 121 | ||||
| -rw-r--r-- | src/syntax/func/maps.rs | 211 | ||||
| -rw-r--r-- | src/syntax/func/mod.rs (renamed from src/syntax/func.rs) | 22 | ||||
| -rw-r--r-- | src/syntax/func/values.rs | 223 | ||||
| -rw-r--r-- | src/syntax/mod.rs | 2 | ||||
| -rw-r--r-- | src/syntax/parsing.rs | 8 | ||||
| -rw-r--r-- | src/syntax/tokens.rs | 9 |
8 files changed, 713 insertions, 113 deletions
diff --git a/src/syntax/expr.rs b/src/syntax/expr.rs index 34a1c6bf..fe24c655 100644 --- a/src/syntax/expr.rs +++ b/src/syntax/expr.rs @@ -1,4 +1,3 @@ -use crate::size::ScaleSize; use super::*; @@ -22,30 +21,13 @@ impl Expr { Str(_) => "string", Number(_) => "number", Size(_) => "size", - Bool(_) => "boolean", + Bool(_) => "bool", Tuple(_) => "tuple", Object(_) => "object", } } } -impl Display for Expr { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - use Expr::*; - match self { - Ident(i) => write!(f, "{}", i), - Str(s) => write!(f, "{:?}", s), - Number(n) => write!(f, "{}", n), - Size(s) => write!(f, "{}", s), - Bool(b) => write!(f, "{}", b), - Tuple(t) => write!(f, "{}", t), - Object(o) => write!(f, "{}", o), - } - } -} - -debug_display!(Expr); - /// An identifier. #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Ident(pub String); @@ -64,17 +46,6 @@ impl Ident { } } -impl Display for Ident { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - write!(f, "{}", self.0) - } -} - -debug_display!(Ident); - -#[derive(Debug, Clone, Eq, PartialEq)] -pub struct StringLike(pub String); - /// A sequence of expressions. #[derive(Clone, PartialEq)] pub struct Tuple { @@ -89,27 +60,31 @@ impl Tuple { pub fn add(&mut self, item: Spanned<Expr>) { self.items.push(item); } -} - -impl Display for Tuple { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - write!(f, "(")?; - let mut first = true; - for item in &self.items { - if !first { - write!(f, ", ")?; + pub fn get<V: Value>(&mut self, errors: &mut Errors) -> Option<V::Output> { + while !self.items.is_empty() { + let expr = self.items.remove(0); + let span = expr.span; + match V::parse(expr) { + Ok(output) => return Some(output), + Err(err) => errors.push(Spanned { v: err, span }), } - write!(f, "{}", item.v)?; - first = false; } + None + } - write!(f, ")") + pub fn get_all<'a, V: Value>(&'a mut self, errors: &'a mut Errors) + -> impl Iterator<Item=V::Output> + 'a { + self.items.drain(..).filter_map(move |expr| { + let span = expr.span; + match V::parse(expr) { + Ok(output) => Some(output), + Err(err) => { errors.push(Spanned { v: err, span }); None } + } + }) } } -debug_display!(Tuple); - /// A key-value collection of identifiers and associated expressions. #[derive(Clone, PartialEq)] pub struct Object { @@ -128,6 +103,108 @@ impl Object { pub fn add_pair(&mut self, pair: Pair) { self.pairs.push(pair); } + + pub fn get<V: Value>(&mut self, errors: &mut Errors, key: &str) -> Option<V::Output> { + let index = self.pairs.iter().position(|pair| pair.key.v.as_str() == key)?; + self.get_index::<V>(errors, index) + } + + pub fn get_with_key<K: Key, V: Value>( + &mut self, + errors: &mut Errors, + ) -> Option<(K::Output, V::Output)> { + for (index, pair) in self.pairs.iter().enumerate() { + let key = Spanned { v: pair.key.v.as_str(), span: pair.key.span }; + if let Some(key) = K::parse(key) { + return self.get_index::<V>(errors, index).map(|value| (key, value)); + } + } + None + } + + pub fn get_all<'a, K: Key, V: Value>( + &'a mut self, + errors: &'a mut Errors, + ) -> impl Iterator<Item=(K::Output, V::Output)> + 'a { + let mut index = 0; + std::iter::from_fn(move || { + if index < self.pairs.len() { + let key = &self.pairs[index].key; + let key = Spanned { v: key.v.as_str(), span: key.span }; + + Some(if let Some(key) = K::parse(key) { + self.get_index::<V>(errors, index).map(|v| (key, v)) + } else { + index += 1; + None + }) + } else { + None + } + }).filter_map(|x| x) + } + + pub fn get_all_spanned<'a, K: Key + 'a, V: Value + 'a>( + &'a mut self, + errors: &'a mut Errors, + ) -> impl Iterator<Item=Spanned<(K::Output, V::Output)>> + 'a { + self.get_all::<Spanned<K>, Spanned<V>>(errors) + .map(|(k, v)| Spanned::new((k.v, v.v), Span::merge(k.span, v.span))) + } + + fn get_index<V: Value>(&mut self, errors: &mut Errors, index: usize) -> Option<V::Output> { + let expr = self.pairs.remove(index).value; + let span = expr.span; + match V::parse(expr) { + Ok(output) => Some(output), + Err(err) => { errors.push(Spanned { v: err, span }); None } + } + } +} + +/// A key-value pair in an object. +#[derive(Clone, PartialEq)] +pub struct Pair { + pub key: Spanned<Ident>, + pub value: Spanned<Expr>, +} + +impl Display for Expr { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + use Expr::*; + match self { + Ident(i) => write!(f, "{}", i), + Str(s) => write!(f, "{:?}", s), + Number(n) => write!(f, "{}", n), + Size(s) => write!(f, "{}", s), + Bool(b) => write!(f, "{}", b), + Tuple(t) => write!(f, "{}", t), + Object(o) => write!(f, "{}", o), + } + } +} + +impl Display for Ident { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} + +impl Display for Tuple { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "(")?; + + let mut first = true; + for item in &self.items { + if !first { + write!(f, ", ")?; + } + write!(f, "{}", item.v)?; + first = false; + } + + write!(f, ")") + } } impl Display for Object { @@ -151,71 +228,14 @@ impl Display for Object { } } -debug_display!(Object); - -/// A key-value pair in an object. -#[derive(Clone, PartialEq)] -pub struct Pair { - pub key: Spanned<Ident>, - pub value: Spanned<Expr>, -} - impl Display for Pair { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}: {}", self.key.v, self.value.v) } } +debug_display!(Expr); +debug_display!(Ident); +debug_display!(Tuple); +debug_display!(Object); debug_display!(Pair); - -pub trait ExprKind: Sized { - /// The name of the expression in an `expected <name>` error. - const NAME: &'static str; - - /// Create from expression. - fn from_expr(expr: Spanned<Expr>) -> Result<Self, Error>; -} - -impl<T> ExprKind for Spanned<T> where T: ExprKind { - const NAME: &'static str = T::NAME; - - fn from_expr(expr: Spanned<Expr>) -> Result<Self, Error> { - let span = expr.span; - T::from_expr(expr).map(|v| Spanned { v, span }) - } -} -/// Implements the expression kind trait for a type. -macro_rules! kind { - ($type:ty, $name:expr, $($p:pat => $r:expr),* $(,)?) => { - impl ExprKind for $type { - const NAME: &'static str = $name; - - fn from_expr(expr: Spanned<Expr>) -> Result<Self, Error> { - #[allow(unreachable_patterns)] - Ok(match expr.v { - $($p => $r),*, - _ => return Err( - err!("expected {}, found {}", Self::NAME, expr.v.name()) - ), - }) - } - } - }; -} - -kind!(Expr, "expression", e => e); -kind!(Ident, "identifier", Expr::Ident(i) => i); -kind!(String, "string", Expr::Str(s) => s); -kind!(f64, "number", Expr::Number(n) => n); -kind!(bool, "boolean", Expr::Bool(b) => b); -kind!(Size, "size", Expr::Size(s) => s); -kind!(Tuple, "tuple", Expr::Tuple(t) => t); -kind!(Object, "object", Expr::Object(o) => o); -kind!(ScaleSize, "number or size", - Expr::Size(size) => ScaleSize::Absolute(size), - Expr::Number(scale) => ScaleSize::Scaled(scale as f32), -); -kind!(StringLike, "identifier or string", - Expr::Ident(Ident(s)) => StringLike(s), - Expr::Str(s) => StringLike(s), -); diff --git a/src/syntax/func/keys.rs b/src/syntax/func/keys.rs new file mode 100644 index 00000000..dff97bde --- /dev/null +++ b/src/syntax/func/keys.rs @@ -0,0 +1,121 @@ +use crate::layout::prelude::*; +use super::*; + +use AxisKey::*; +use PaddingKey::*; +use AlignmentValue::*; + + +pub trait Key { + type Output: Eq; + + fn parse(key: Spanned<&str>) -> Option<Self::Output>; +} + +impl<K: Key> Key for Spanned<K> { + type Output = Spanned<K::Output>; + + fn parse(key: Spanned<&str>) -> Option<Self::Output> { + K::parse(key).map(|v| Spanned { v, span: key.span }) + } +} + +macro_rules! key { + ($type:ty, $output:ty, $($($p:pat)|* => $r:expr),* $(,)?) => { + impl Key for $type { + type Output = $output; + + fn parse(key: Spanned<&str>) -> Option<Self::Output> { + match key.v { + $($($p)|* => Some($r)),*, + other => None, + } + } + } + }; +} + +/// An argument key which identifies a layouting axis. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub enum AxisKey { + Generic(GenericAxis), + Specific(SpecificAxis), +} + +impl AxisKey { + /// The generic version of this axis key in the given system of axes. + pub fn to_generic(self, axes: LayoutAxes) -> GenericAxis { + match self { + Generic(axis) => axis, + Specific(axis) => axis.to_generic(axes), + } + } + + /// The specific version of this axis key in the given system of axes. + pub fn to_specific(self, axes: LayoutAxes) -> SpecificAxis { + match self { + Generic(axis) => axis.to_specific(axes), + Specific(axis) => axis, + } + } +} + +key!(AxisKey, Self, + "horizontal" | "h" => Specific(Horizontal), + "vertical" | "v" => Specific(Vertical), + "primary" | "p" => Generic(Primary), + "secondary" | "s" => Generic(Secondary), +); + +pub struct ExtentKey; + +key!(ExtentKey, AxisKey, + "width" | "w" => Specific(Horizontal), + "height" | "h" => Specific(Vertical), + "primary-size" | "ps" => Generic(Primary), + "secondary-size" | "ss" => Generic(Secondary), +); + +/// An argument key which identifies an axis, but allows for positional +/// arguments with unspecified axes. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub enum PosAxisKey { + /// The first positional argument. + First, + /// The second positional argument. + Second, + /// An axis keyword argument. + Keyword(AxisKey), +} + +/// An argument key which identifies a margin or padding target. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub enum PaddingKey<Axis> { + /// All four sides should have the specified padding. + All, + /// Both sides of the given axis should have the specified padding. + Both(Axis), + /// Only the given side of the given axis should have the specified padding. + Side(Axis, AlignmentValue), +} + +key!(PaddingKey<AxisKey>, Self, + "horizontal" | "h" => Both(Specific(Horizontal)), + "vertical" | "v" => Both(Specific(Vertical)), + "primary" | "p" => Both(Generic(Primary)), + "secondary" | "s" => Both(Generic(Secondary)), + + "left" => Side(Specific(Horizontal), Left), + "right" => Side(Specific(Horizontal), Right), + "top" => Side(Specific(Vertical), Top), + "bottom" => Side(Specific(Vertical), Bottom), + + "primary-origin" => Side(Generic(Primary), Align(Origin)), + "primary-end" => Side(Generic(Primary), Align(End)), + "secondary-origin" => Side(Generic(Secondary), Align(Origin)), + "secondary-end" => Side(Generic(Secondary), Align(End)), + "horizontal-origin" => Side(Specific(Horizontal), Align(Origin)), + "horizontal-end" => Side(Specific(Horizontal), Align(End)), + "vertical-origin" => Side(Specific(Vertical), Align(Origin)), + "vertical-end" => Side(Specific(Vertical), Align(End)), +); diff --git a/src/syntax/func/maps.rs b/src/syntax/func/maps.rs new file mode 100644 index 00000000..452c8ab1 --- /dev/null +++ b/src/syntax/func/maps.rs @@ -0,0 +1,211 @@ +//! Deduplicating maps and keys for argument parsing. + +use std::collections::HashMap; +use std::hash::Hash; +use crate::layout::{LayoutAxes, SpecificAxis, GenericAxis}; +use crate::size::{PSize, ValueBox}; +use super::*; + + +/// A deduplicating map type useful for storing possibly redundant arguments. +#[derive(Debug, Clone, PartialEq)] +pub struct DedupMap<K, V> where K: Eq { + map: Vec<Spanned<(K, V)>>, +} + +impl<K, V> DedupMap<K, V> where K: Eq { + pub fn new() -> DedupMap<K, V> { + DedupMap { map: vec![] } + } + + pub fn from_iter<I>(errors: &mut Errors, iter: I) -> DedupMap<K, V> + where I: IntoIterator<Item=Spanned<(K, V)>> { + let mut map = DedupMap::new(); + for Spanned { v: (key, value), span } in iter.into_iter() { + map.insert(errors, key, value, span); + } + map + } + + /// Add a key-value pair. + pub fn insert(&mut self, errors: &mut Errors, key: K, value: V, span: Span) { + if self.map.iter().any(|e| e.v.0 == key) { + errors.push(err!(span; "duplicate argument")); + } else { + self.map.push(Spanned { v: (key, value), span }); + } + } + + /// Add multiple key-value pairs. + pub fn extend<I>(&mut self, errors: &mut Errors, items: I) + where I: IntoIterator<Item=Spanned<(K, V)>> { + for Spanned { v: (k, v), span } in items.into_iter() { + self.insert(errors, k, v, span); + } + } + + /// Get the value corresponding to a key if it is present. + pub fn get(&self, key: K) -> Option<&V> { + self.map.iter().find(|e| e.v.0 == key).map(|e| &e.v.1) + } + + /// Get the value and its span corresponding to a key if it is present. + pub fn get_spanned(&self, key: K) -> Option<Spanned<&V>> { + self.map.iter().find(|e| e.v.0 == key) + .map(|e| Spanned { v: &e.v.1, span: e.span }) + } + + /// Call a function with the value if the key is present. + pub fn with<F>(&self, key: K, callback: F) where F: FnOnce(&V) { + if let Some(value) = self.get(key) { + callback(value); + } + } + + /// Create a new map where keys and values are mapped to new keys and + /// values. + /// + /// Returns an error if a new key is duplicate. + pub fn dedup<F, K2, V2>(&self, errors: &mut Errors, mut f: F) -> DedupMap<K2, V2> + where F: FnMut(&K, &V) -> (K2, V2), K2: Eq { + let mut map = DedupMap::new(); + + for Spanned { v: (key, value), span } in self.map.iter() { + let (key, value) = f(key, value); + map.insert(errors, key, value, *span); + } + + map + } + + /// Iterate over the (key, value) pairs. + pub fn iter(&self) -> impl Iterator<Item=&(K, V)> { + self.map.iter().map(|e| &e.v) + } +} + +/// A map for storing a value for two axes given by keyword arguments. +#[derive(Debug, Clone, PartialEq)] +pub struct AxisMap<V>(DedupMap<AxisKey, V>); + +impl<V: Clone> AxisMap<V> { + pub fn parse<KT: Key<Output=AxisKey>, VT: Value<Output=V>>( + errors: &mut Errors, + object: &mut Object, + ) -> AxisMap<V> { + let values: Vec<_> = object.get_all_spanned::<KT, VT>(errors).collect(); + AxisMap(DedupMap::from_iter(errors, values)) + } + + /// Deduplicate from specific or generic to just specific axes. + pub fn dedup(&self, errors: &mut Errors, axes: LayoutAxes) -> DedupMap<SpecificAxis, V> { + self.0.dedup(errors, |key, val| (key.to_specific(axes), val.clone())) + } +} + +/// A map for extracting values for two axes that are given through two +/// positional or keyword arguments. +#[derive(Debug, Clone, PartialEq)] +pub struct PosAxisMap<V>(DedupMap<PosAxisKey, V>); + +impl<V: Clone> PosAxisMap<V> { + pub fn parse<KT: Key<Output=AxisKey>, VT: Value<Output=V>>( + errors: &mut Errors, + args: &mut FuncArgs, + ) -> PosAxisMap<V> { + let mut map = DedupMap::new(); + + for &key in &[PosAxisKey::First, PosAxisKey::Second] { + if let Some(value) = args.pos.get::<Spanned<VT>>(errors) { + map.insert(errors, key, value.v, value.span); + } + } + + let keywords: Vec<_> = args.key + .get_all_spanned::<KT, VT>(errors) + .map(|s| s.map(|(k, v)| (PosAxisKey::Keyword(k), v))) + .collect(); + + map.extend(errors, keywords); + + PosAxisMap(map) + } + + /// Deduplicate from positional or specific to generic axes. + pub fn dedup<F>( + &self, + errors: &mut Errors, + axes: LayoutAxes, + mut f: F, + ) -> DedupMap<GenericAxis, V> where F: FnMut(&V) -> Option<GenericAxis> { + self.0.dedup(errors, |key, val| { + (match key { + PosAxisKey::First => f(val).unwrap_or(GenericAxis::Primary), + PosAxisKey::Second => f(val).unwrap_or(GenericAxis::Secondary), + PosAxisKey::Keyword(AxisKey::Specific(axis)) => axis.to_generic(axes), + PosAxisKey::Keyword(AxisKey::Generic(axis)) => *axis, + }, val.clone()) + }) + } +} + +/// A map for extracting padding for a set of specifications given for all +/// sides, opposing sides or single sides. +#[derive(Debug, Clone, PartialEq)] +pub struct PaddingMap(DedupMap<PaddingKey<AxisKey>, Option<PSize>>); + +impl PaddingMap { + pub fn parse(errors: &mut Errors, args: &mut FuncArgs) -> PaddingMap { + let mut map = DedupMap::new(); + + if let Some(psize) = args.pos.get::<Spanned<Defaultable<PSize>>>(errors) { + map.insert(errors, PaddingKey::All, psize.v, psize.span); + } + + let paddings: Vec<_> = args.key + .get_all_spanned::<PaddingKey<AxisKey>, Defaultable<PSize>>(errors) + .collect(); + + map.extend(errors, paddings); + + PaddingMap(map) + } + + /// Apply the specified padding on a value box of optional, scalable sizes. + pub fn apply( + &self, + errors: &mut Errors, + axes: LayoutAxes, + padding: &mut ValueBox<Option<PSize>> + ) { + use PaddingKey::*; + use SpecificAxis::*; + + let map = self.0.dedup(errors, |key, &val| { + (match key { + All => All, + Both(axis) => Both(axis.to_specific(axes)), + Side(axis, alignment) => { + let axis = axis.to_specific(axes); + Side(axis, alignment.to_specific(axes, axis)) + } + }, val) + }); + + map.with(All, |&val| padding.set_all(val)); + map.with(Both(Horizontal), |&val| padding.set_horizontal(val)); + map.with(Both(Vertical), |&val| padding.set_vertical(val)); + + for &(key, val) in map.iter() { + if let Side(_, alignment) = key { + match alignment { + AlignmentValue::Left => padding.left = val, + AlignmentValue::Right => padding.right = val, + AlignmentValue::Top => padding.top = val, + AlignmentValue::Bottom => padding.bottom = val, + _ => {}, + } + } + } + } +} diff --git a/src/syntax/func.rs b/src/syntax/func/mod.rs index abc8c431..b6691ab5 100644 --- a/src/syntax/func.rs +++ b/src/syntax/func/mod.rs @@ -1,5 +1,9 @@ use super::*; +pub_use_mod!(maps); +pub_use_mod!(keys); +pub_use_mod!(values); + #[derive(Debug, Clone, PartialEq)] pub struct FuncHeader { @@ -60,6 +64,11 @@ impl FuncArgs { self.key.add_pair(pair); } + pub fn into_iter(self) -> impl Iterator<Item=Arg> { + self.pos.items.into_iter().map(|item| Arg::Pos(item)) + .chain(self.key.pairs.into_iter().map(|pair| Arg::Key(pair))) + } + // /// Force-extract the first positional argument. // pub fn get_pos<E: ExpressionKind>(&mut self) -> ParseResult<E> { // expect(self.get_pos_opt()) @@ -123,3 +132,16 @@ impl FuncArgs { // Err(e) => Err(e), // } // } + +pub trait OptionExt: Sized { + fn or_missing(self, errors: &mut Errors, span: Span, what: &str) -> Self; +} + +impl<T> OptionExt for Option<T> { + fn or_missing(self, errors: &mut Errors, span: Span, what: &str) -> Self { + if self.is_none() { + errors.push(err!(span; "missing argument: {}", what)); + } + self + } +} diff --git a/src/syntax/func/values.rs b/src/syntax/func/values.rs new file mode 100644 index 00000000..b29b9726 --- /dev/null +++ b/src/syntax/func/values.rs @@ -0,0 +1,223 @@ +use std::marker::PhantomData; +use toddle::query::{FontStyle, FontWeight}; + +use crate::layout::prelude::*; +use crate::size::ScaleSize; +use crate::style::Paper; +use super::*; + +use AlignmentValue::*; + + +pub trait Value { + type Output; + + fn parse(expr: Spanned<Expr>) -> Result<Self::Output, Error>; +} + +impl<V: Value> Value for Spanned<V> { + type Output = Spanned<V::Output>; + + fn parse(expr: Spanned<Expr>) -> Result<Self::Output, Error> { + let span = expr.span; + V::parse(expr).map(|v| Spanned { v, span }) + } +} + +macro_rules! value { + ($type:ty, $output:ty, $name:expr, $($p:pat => $r:expr),* $(,)?) => { + impl Value for $type { + type Output = $output; + + fn parse(expr: Spanned<Expr>) -> Result<Self::Output, Error> { + #[allow(unreachable_patterns)] + match expr.v { + $($p => Ok($r)),*, + other => Err(err!("expected {}, found {}", + $name, other.name())), + } + } + } + }; +} + +value!(Expr, Self, "expression", e => e); + +value!(Ident, Self, "identifier", Expr::Ident(i) => i); +value!(String, Self, "string", Expr::Str(s) => s); +value!(f64, Self, "number", Expr::Number(n) => n); +value!(bool, Self, "bool", Expr::Bool(b) => b); +value!(Size, Self, "size", Expr::Size(s) => s); +value!(Tuple, Self, "tuple", Expr::Tuple(t) => t); +value!(Object, Self, "object", Expr::Object(o) => o); + +value!(ScaleSize, Self, "number or size", + Expr::Size(size) => ScaleSize::Absolute(size), + Expr::Number(scale) => ScaleSize::Scaled(scale as f32), +); + +pub struct StringLike; + +value!(StringLike, String, "identifier or string", + Expr::Ident(Ident(s)) => s, + Expr::Str(s) => s, +); + +pub struct Defaultable<T>(PhantomData<T>); + +impl<T: Value> Value for Defaultable<T> { + type Output = Option<T::Output>; + + fn parse(expr: Spanned<Expr>) -> Result<Self::Output, Error> { + match expr.v { + Expr::Ident(ident) if ident.as_str() == "default" => Ok(None), + _ => T::parse(expr).map(Some) + } + } +} + +impl Value for Direction { + type Output = Self; + + fn parse(expr: Spanned<Expr>) -> Result<Self::Output, Error> { + Ok(match Ident::parse(expr)?.as_str() { + "left-to-right" | "ltr" | "LTR" => Direction::LeftToRight, + "right-to-left" | "rtl" | "RTL" => Direction::RightToLeft, + "top-to-bottom" | "ttb" | "TTB" => Direction::TopToBottom, + "bottom-to-top" | "btt" | "BTT" => Direction::BottomToTop, + other => return Err(err!("invalid direction")) + }) + } +} + +impl Value for FontStyle { + type Output = Self; + + fn parse(expr: Spanned<Expr>) -> Result<Self::Output, Error> { + FontStyle::from_str(Ident::parse(expr)?.as_str()) + .ok_or_else(|| err!("invalid font style")) + } +} + +impl Value for FontWeight { + type Output = (Self, bool); + + fn parse(expr: Spanned<Expr>) -> Result<Self::Output, Error> { + match expr.v { + Expr::Number(weight) => { + let weight = weight.round(); + + if weight >= 100.0 && weight <= 900.0 { + Ok((FontWeight(weight as i16), false)) + } else { + let clamped = weight.min(900.0).max(100.0) as i16; + Ok((FontWeight(clamped), true)) + } + } + Expr::Ident(id) => { + FontWeight::from_str(id.as_str()) + .ok_or_else(|| err!("invalid font weight")) + .map(|weight| (weight, false)) + } + other => Err(err!("expected identifier or number, \ + found {}", other.name())), + } + } +} + +impl Value for Paper { + type Output = Self; + + fn parse(expr: Spanned<Expr>) -> Result<Self::Output, Error> { + Paper::from_str(Ident::parse(expr)?.as_str()) + .ok_or_else(|| err!("invalid paper type")) + } +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub enum AlignmentValue { + Align(Alignment), + Left, + Top, + Right, + Bottom, +} + +impl AlignmentValue { + /// The generic axis this alignment corresponds to in the given system of + /// layouting axes. `None` if the alignment is generic. + pub fn axis(self, axes: LayoutAxes) -> Option<GenericAxis> { + match self { + Left | Right => Some(Horizontal.to_generic(axes)), + Top | Bottom => Some(Vertical.to_generic(axes)), + Align(_) => None, + } + } + + /// The generic version of this alignment in the given system of layouting + /// axes. + /// + /// Returns `None` if the alignment is invalid for the given axis. + pub fn to_generic(self, axes: LayoutAxes, axis: GenericAxis) -> Option<Alignment> { + let specific = axis.to_specific(axes); + let start = match axes.get(axis).is_positive() { + true => Origin, + false => End, + }; + + match (self, specific) { + (Align(alignment), _) => Some(alignment), + (Left, Horizontal) | (Top, Vertical) => Some(start), + (Right, Horizontal) | (Bottom, Vertical) => Some(start.inv()), + _ => None + } + } + + /// The specific version of this alignment in the given system of layouting + /// axes. + pub fn to_specific(self, axes: LayoutAxes, axis: SpecificAxis) -> AlignmentValue { + let direction = axes.get_specific(axis); + if let Align(alignment) = self { + match (direction, alignment) { + (LeftToRight, Origin) | (RightToLeft, End) => Left, + (LeftToRight, End) | (RightToLeft, Origin) => Right, + (TopToBottom, Origin) | (BottomToTop, End) => Top, + (TopToBottom, End) | (BottomToTop, Origin) => Bottom, + (_, Center) => self, + } + } else { + self + } + } +} + +impl Value for AlignmentValue { + type Output = Self; + + fn parse(expr: Spanned<Expr>) -> Result<Self::Output, Error> { + Ok(match Ident::parse(expr)?.as_str() { + "origin" => Align(Origin), + "center" => Align(Center), + "end" => Align(End), + "left" => Left, + "top" => Top, + "right" => Right, + "bottom" => Bottom, + other => return Err(err!("invalid alignment")) + }) + } +} + +impl Display for AlignmentValue { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self { + Align(Origin) => write!(f, "origin"), + Align(Center) => write!(f, "center"), + Align(End) => write!(f, "end"), + Left => write!(f, "left"), + Top => write!(f, "top"), + Right => write!(f, "right"), + Bottom => write!(f, "bottom"), + } + } +} diff --git a/src/syntax/mod.rs b/src/syntax/mod.rs index a77c764e..356535ae 100644 --- a/src/syntax/mod.rs +++ b/src/syntax/mod.rs @@ -6,7 +6,7 @@ use std::future::Future; use std::pin::Pin; use serde::Serialize; -use crate::error::Error; +use crate::error::{Error, Errors}; use crate::func::{Commands, Command}; use crate::layout::{Layouted, LayoutContext}; use crate::size::Size; diff --git a/src/syntax/parsing.rs b/src/syntax/parsing.rs index ed343050..e726a2e0 100644 --- a/src/syntax/parsing.rs +++ b/src/syntax/parsing.rs @@ -12,7 +12,7 @@ pub struct ParseContext<'a> { pub struct Parsed<T> { pub output: T, - pub errors: SpanVec<Error>, + pub errors: Errors, pub decorations: SpanVec<Decoration>, } @@ -77,17 +77,17 @@ pub fn parse(start: Position, src: &str, ctx: ParseContext) -> Parsed<SyntaxMode struct FuncParser<'s> { ctx: ParseContext<'s>, - errors: SpanVec<Error>, + errors: Errors, decorations: SpanVec<Decoration>, tokens: Tokens<'s>, peeked: Option<Option<Spanned<Token<'s>>>>, - body: Option<(Position, &'s str)>, + body: Option<Spanned<&'s str>>, } impl<'s> FuncParser<'s> { fn new( header: &'s str, - body: Option<(Position, &'s str)>, + body: Option<Spanned<&'s str>>, ctx: ParseContext<'s> ) -> FuncParser<'s> { FuncParser { diff --git a/src/syntax/tokens.rs b/src/syntax/tokens.rs index 6c8e736c..d0adbf60 100644 --- a/src/syntax/tokens.rs +++ b/src/syntax/tokens.rs @@ -23,7 +23,7 @@ pub enum Token<'s> { /// A function invocation `[<header>][<body>]`. Function { header: &'s str, - body: Option<(Position, &'s str)>, + body: Option<Spanned<&'s str>>, terminated: bool, }, @@ -222,13 +222,16 @@ impl<'s> Tokens<'s> { return Function { header, body: None, terminated }; } + let body_start = self.pos() - start; self.eat(); - let offset = self.pos() - start; let (body, terminated) = self.read_function_part(); self.eat(); - Function { header, body: Some((offset, body)), terminated } + let body_end = self.pos(); + let span = Span::new(body_start, body_end); + + Function { header, body: Some(Spanned { v: body, span }), terminated } } fn read_function_part(&mut self) -> (&'s str, bool) { |
