summaryrefslogtreecommitdiff
path: root/src/syntax/func/mod.rs
blob: 0c5b4447e6e79ef0677f5f30fbe5adde22e806fd (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
//! Primitives for argument parsing in library functions.

use crate::error::{Error, Errors};
use super::expr::{Expr, Ident, Tuple, Object, Pair};
use super::span::{Span, Spanned};

pub_use_mod!(maps);
pub_use_mod!(keys);
pub_use_mod!(values);


/// The parsed header of a function.
#[derive(Debug, Clone, PartialEq)]
pub struct FuncHeader {
    /// The function name, that is:
    /// ```typst
    /// [box: w=5cm]
    ///  ^^^
    /// ```
    pub name: Spanned<Ident>,
    /// The arguments passed to the function.
    pub args: FuncArgs,
}

/// The positional and keyword arguments passed to a function.
#[derive(Debug, Clone, PartialEq)]
pub struct FuncArgs {
    /// The positional arguments.
    pub pos: Tuple,
    /// They keyword arguments.
    pub key: Object,
}

impl FuncArgs {
    /// Create new empty function arguments.
    pub fn new() -> FuncArgs {
        FuncArgs {
            pos: Tuple::new(),
            key: Object::new(),
        }
    }

    /// Add an argument.
    pub fn add(&mut self, arg: FuncArg) {
        match arg {
            FuncArg::Pos(item) => self.pos.add(item),
            FuncArg::Key(pair) => self.key.add(pair),
        }
    }

    /// Iterate over all arguments.
    pub fn into_iter(self) -> impl Iterator<Item=FuncArg> {
        self.pos.items.into_iter().map(|item| FuncArg::Pos(item))
            .chain(self.key.pairs.into_iter().map(|pair| FuncArg::Key(pair)))
    }
}

/// Either a positional or keyword argument.
#[derive(Debug, Clone, PartialEq)]
pub enum FuncArg {
    /// A positional argument.
    Pos(Spanned<Expr>),
    /// A keyword argument.
    Key(Pair),
}

impl FuncArg {
    /// The full span of this argument.
    ///
    /// In case of a positional argument this is just the span of the expression
    /// and in case of a keyword argument the combined span of key and value.
    pub fn span(&self) -> Span {
        match self {
            FuncArg::Pos(item) => item.span,
            FuncArg::Key(Pair { key, value }) => Span::merge(key.span, value.span),
        }
    }
}

/// Extra methods on [`Options`](Option) used for argument parsing.
pub trait OptionExt: Sized {
    /// Add an error about a missing argument `arg` with the given span if the
    /// option is `None`.
    fn or_missing(self, errors: &mut Errors, span: Span, arg: &str) -> Self;
}

impl<T> OptionExt for Option<T> {
    fn or_missing(self, errors: &mut Errors, span: Span, arg: &str) -> Self {
        if self.is_none() {
            errors.push(err!(span; "missing argument: {}", arg));
        }
        self
    }
}