summaryrefslogtreecommitdiff
path: root/src/func/mod.rs
blob: c8cf23c65cdb4bd34038a21966542420a24c8fd7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
//! Dynamic typesetting functions.

use std::any::Any;
use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter};

use self::prelude::*;

#[macro_use]
mod macros;

/// Useful imports for creating your own functions.
pub mod prelude {
    pub use crate::func::{Scope, ParseFunc, LayoutFunc, Command, Commands};
    pub use crate::layout::{
        layout_tree, Layout, MultiLayout,
        LayoutContext, LayoutSpace, LayoutSpaces, LayoutExpansion,
        LayoutAxes, Axis, GenericAxisKind, SpecificAxisKind,
        LayoutAlignment, Alignment,
        SpacingKind, LayoutResult,
    };
    pub use crate::syntax::{
        parse, ParseContext, ParseResult,
        SyntaxTree, FuncCall, FuncArgs, PosArg, KeyArg,
        Expression, Ident, ExpressionKind,
        Spanned, Span
    };
    pub use crate::size::{Size, Size2D, SizeBox, ScaleSize, FSize, PSize};
    pub use crate::style::{LayoutStyle, PageStyle, TextStyle};
    pub use Command::*;
}

/// Types representing functions that are parsed from source code.
pub trait ParseFunc {
    type Meta: Clone;

    /// Parse the header and body into this function given a context.
    fn parse(
        args: FuncArgs,
        body: Option<Spanned<&str>>,
        ctx: ParseContext,
        metadata: Self::Meta,
    ) -> ParseResult<Self> where Self: Sized;
}

/// Types representing functions which can be laid out in a layout context.
///
/// This trait is a supertrait of `[LayoutFuncBounds]` for technical reasons.
/// The trait `[LayoutFuncBounds]` is automatically implemented for types which
/// can be used as functions, that is, all types which fulfill the bounds `Debug
/// + PartialEq + 'static`.
pub trait LayoutFunc: LayoutFuncBounds {
    /// Layout this function in a given context.
    ///
    /// Returns a sequence of layouting commands which describe what the
    /// function is doing.
    fn layout(&self, ctx: LayoutContext) -> LayoutResult<Commands>;
}

impl dyn LayoutFunc {
    /// Downcast a function trait object to a concrete function type.
    pub fn downcast<F>(&self) -> Option<&F> where F: LayoutFunc + 'static {
        self.help_cast_as_any().downcast_ref::<F>()
    }
}

impl PartialEq for dyn LayoutFunc {
    fn eq(&self, other: &dyn LayoutFunc) -> bool {
        self.help_eq(other)
    }
}

/// A helper trait that describes requirements for types that can implement
/// [`Function`].
///
/// Automatically implemented for all types which fulfill to the bounds `Debug +
/// PartialEq + 'static`. There should be no need to implement this manually.
pub trait LayoutFuncBounds: Debug {
    /// Cast self into `Any`.
    fn help_cast_as_any(&self) -> &dyn Any;

    /// Compare self with another function trait object.
    fn help_eq(&self, other: &dyn LayoutFunc) -> bool;
}

impl<T> LayoutFuncBounds for T where T: Debug + PartialEq + 'static {
    fn help_cast_as_any(&self) -> &dyn Any {
        self
    }

    fn help_eq(&self, other: &dyn LayoutFunc) -> bool {
        if let Some(other) = other.help_cast_as_any().downcast_ref::<Self>() {
            self == other
        } else {
            false
        }
    }
}

/// A sequence of layouting commands.
pub type Commands<'a> = Vec<Command<'a>>;

/// Layouting commands from functions to the typesetting engine.
#[derive(Debug)]
pub enum Command<'a> {
    LayoutTree(&'a SyntaxTree),

    Add(Layout),
    AddMultiple(MultiLayout),
    AddSpacing(Size, SpacingKind, GenericAxisKind),

    FinishLine,
    FinishRun,
    FinishSpace,
    BreakParagraph,

    SetTextStyle(TextStyle),
    SetPageStyle(PageStyle),
    SetAlignment(LayoutAlignment),
    SetAxes(LayoutAxes),
}

/// A map from identifiers to function parsers.
pub struct Scope {
    parsers: HashMap<String, Box<Parser>>,
}

/// A function which parses the source of a function into a function type which
/// implements [`LayoutFunc`].
type Parser = dyn Fn(
    FuncArgs,
    Option<Spanned<&str>>,
    ParseContext
) -> ParseResult<Box<dyn LayoutFunc>>;

impl Scope {
    /// Create a new empty scope.
    pub fn new() -> Scope {
        Scope {
            parsers: HashMap::new(),
        }
    }

    /// Create a new scope with the standard functions contained.
    pub fn with_std() -> Scope {
        crate::library::std()
    }

    /// Associate the given name with a type that is parseable into a function.
    pub fn add<F>(&mut self, name: &str)
    where F: ParseFunc<Meta=()> + LayoutFunc + 'static {
        self.add_with_metadata::<F, ()>(name, ());
    }

    /// Add a parseable type with additional metadata  that is given to the
    /// parser (other than the default of `()`).
    pub fn add_with_metadata<F, T>(&mut self, name: &str, metadata: T)
    where F: ParseFunc<Meta=T> + LayoutFunc + 'static, T: 'static + Clone {
        self.parsers.insert(
            name.to_owned(),
            Box::new(move |a, b, c| {
                F::parse(a, b, c, metadata.clone())
                    .map(|f| Box::new(f) as Box<dyn LayoutFunc>)
            })
        );
    }

    /// Return the parser with the given name if there is one.
    pub(crate) fn get_parser(&self, name: &str) -> Option<&Parser> {
        self.parsers.get(name).map(|x| &**x)
    }
}

impl Debug for Scope {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Scope ")?;
        write!(f, "{:?}", self.parsers.keys())
    }
}