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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
|
use std::fmt::{self, Debug, Formatter, Write};
use std::rc::Rc;
use super::{Cast, EvalContext, Str, Value};
use crate::diag::{At, TypResult};
use crate::syntax::{Span, Spanned};
use crate::util::EcoString;
/// An evaluatable function.
#[derive(Clone)]
pub struct Function(Rc<Inner<Func>>);
/// The unsized structure behind the [`Rc`].
struct Inner<T: ?Sized> {
name: Option<EcoString>,
func: T,
}
type Func = dyn Fn(&mut EvalContext, &mut Args) -> TypResult<Value>;
impl Function {
/// Create a new function from a rust closure.
pub fn new<F>(name: Option<EcoString>, func: F) -> Self
where
F: Fn(&mut EvalContext, &mut Args) -> TypResult<Value> + 'static,
{
Self(Rc::new(Inner { name, func }))
}
/// The name of the function.
pub fn name(&self) -> Option<&EcoString> {
self.0.name.as_ref()
}
/// Call the function in the context with the arguments.
pub fn call(&self, ctx: &mut EvalContext, args: &mut Args) -> TypResult<Value> {
(&self.0.func)(ctx, args)
}
}
impl Debug for Function {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("<function")?;
if let Some(name) = self.name() {
f.write_char(' ')?;
f.write_str(name)?;
}
f.write_char('>')
}
}
impl PartialEq for Function {
fn eq(&self, other: &Self) -> bool {
// We cast to thin pointers for comparison.
Rc::as_ptr(&self.0) as *const () == Rc::as_ptr(&other.0) as *const ()
}
}
/// Evaluated arguments to a function.
#[derive(Clone, PartialEq)]
pub struct Args {
/// The span of the whole argument list.
pub span: Span,
/// The positional and named arguments.
pub items: Vec<Arg>,
}
/// An argument to a function call: `12` or `draw: false`.
#[derive(Clone, PartialEq)]
pub struct Arg {
/// The span of the whole argument.
pub span: Span,
/// The name of the argument (`None` for positional arguments).
pub name: Option<Str>,
/// The value of the argument.
pub value: Spanned<Value>,
}
impl Args {
/// Find and consume the first castable positional argument.
pub fn eat<T>(&mut self) -> Option<T>
where
T: Cast<Spanned<Value>>,
{
for (i, slot) in self.items.iter().enumerate() {
if slot.name.is_none() {
if T::is(&slot.value) {
let value = self.items.remove(i).value;
return T::cast(value).ok();
}
}
}
None
}
/// Find and consume the first castable positional argument, returning a
/// `missing argument: {what}` error if no match was found.
pub fn expect<T>(&mut self, what: &str) -> TypResult<T>
where
T: Cast<Spanned<Value>>,
{
match self.eat() {
Some(found) => Ok(found),
None => bail!(self.span, "missing argument: {}", what),
}
}
/// Find and consume all castable positional arguments.
pub fn all<T>(&mut self) -> impl Iterator<Item = T> + '_
where
T: Cast<Spanned<Value>>,
{
std::iter::from_fn(move || self.eat())
}
/// Cast and remove the value for the given named argument, returning an
/// error if the conversion fails.
pub fn named<T>(&mut self, name: &str) -> TypResult<Option<T>>
where
T: Cast<Spanned<Value>>,
{
// We don't quit once we have a match because when multiple matches
// exist, we want to remove all of them and use the last one.
let mut i = 0;
let mut found = None;
while i < self.items.len() {
if self.items[i].name.as_deref() == Some(name) {
let value = self.items.remove(i).value;
let span = value.span;
found = Some(T::cast(value).at(span)?);
} else {
i += 1;
}
}
Ok(found)
}
/// Take out all arguments into a new instance.
pub fn take(&mut self) -> Self {
Self {
span: self.span,
items: std::mem::take(&mut self.items),
}
}
/// Return an "unexpected argument" error if there is any remaining
/// argument.
pub fn finish(self) -> TypResult<()> {
if let Some(arg) = self.items.first() {
bail!(arg.span, "unexpected argument");
}
Ok(())
}
/// Reinterpret these arguments as actually being an array index.
pub fn into_index(self) -> TypResult<i64> {
self.into_castable("index")
}
/// Reinterpret these arguments as actually being a dictionary key.
pub fn into_key(self) -> TypResult<Str> {
self.into_castable("key")
}
/// Reinterpret these arguments as actually being a single castable thing.
fn into_castable<T>(self, what: &str) -> TypResult<T>
where
T: Cast<Value>,
{
let mut iter = self.items.into_iter();
let value = match iter.next() {
Some(Arg { name: None, value, .. }) => value.v.cast().at(value.span)?,
None => {
bail!(self.span, "missing {}", what);
}
Some(Arg { name: Some(_), span, .. }) => {
bail!(span, "named pair is not allowed here");
}
};
if let Some(arg) = iter.next() {
bail!(arg.span, "only one {} is allowed", what);
}
Ok(value)
}
}
impl Debug for Args {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_char('(')?;
for (i, arg) in self.items.iter().enumerate() {
arg.fmt(f)?;
if i + 1 < self.items.len() {
f.write_str(", ")?;
}
}
f.write_char(')')
}
}
impl Debug for Arg {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if let Some(name) = &self.name {
f.write_str(name)?;
f.write_str(": ")?;
}
Debug::fmt(&self.value.v, f)
}
}
dynamic! {
Args: "arguments",
}
|