Skip to main content

mln_expression/
compound_expression.rs

1// The compound expressions: calls of the functions (crate::functions) that
2// parsing resolves by name. A compound expression keeps the overload its
3// arguments matched and evaluates through its evaluator.
4
5use std::borrow::Cow;
6use std::sync::Arc;
7
8use feature::Value as MbglValue;
9use mln_conversion::Convertible;
10use mln_util::Color;
11
12use crate::check_subtype::check_subtype;
13use crate::expression::{EvalResult, EvaluationContext, EvaluationResult, Expr, Node, Output};
14use crate::functions::{Eval, FunctionDef, Overload, Params, Role, decoding_overload};
15use crate::parsing_context::{ParseResult, ParsingContext};
16use crate::type_;
17use crate::value::Value;
18
19/// A call of a function with typed arguments.
20#[derive(Clone)]
21pub(crate) struct CompoundExpression {
22    overload: Arc<Overload>,
23    args: Box<[Expr]>,
24}
25
26/// A compound expression crosses as its function's name, the overload's
27/// position among the name's and its arguments. Reading resolves the name
28/// against the functions in the reader's context.
29impl mln_wire::Wire for CompoundExpression {
30    fn write(&self, w: &mut mln_wire::Writer) {
31        mln_wire::write_str(w, &self.overload.name);
32        self.overload.index.write(w);
33        self.args.write(w);
34    }
35
36    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
37        let name = mln_wire::read_str(r)?;
38        let index = u8::read(r)?;
39        let overload = match decoding_overload(r, name, index) {
40            Ok(overload) => overload,
41            Err(message) => return r.fail(message),
42        };
43        let args = Box::<[Expr]>::read(r)?;
44        Some(CompoundExpression { overload, args })
45    }
46}
47
48/// Equal when they call the same overload of the same name with equal
49/// arguments, so that a decoded copy equals its original.
50impl PartialEq for CompoundExpression {
51    fn eq(&self, other: &Self) -> bool {
52        self.overload.index == other.overload.index
53            && self.overload.name == other.overload.name
54            && self.args == other.args
55    }
56}
57
58impl CompoundExpression {
59    /// The overload the arguments matched.
60    #[must_use]
61    pub(crate) fn overload(&self) -> &Overload {
62        &self.overload
63    }
64
65    #[must_use]
66    pub(crate) fn args(&self) -> &[Expr] {
67        &self.args
68    }
69
70    pub(crate) fn serialize(&self) -> MbglValue {
71        let mut serialized = vec![MbglValue::String(self.overload.name().to_owned())];
72        serialized.extend(self.args.iter().map(Expr::serialize));
73        MbglValue::Array(serialized)
74    }
75
76    pub(crate) fn eval_num(&self, cx: &EvaluationContext<'_>) -> EvalResult<f64> {
77        match self.overload.eval {
78            Eval::Number(f) => f(&self.args, cx),
79            _ => f64::from_value(self.evaluate(cx)?),
80        }
81    }
82
83    pub(crate) fn eval_bool(&self, cx: &EvaluationContext<'_>) -> EvalResult<bool> {
84        match self.overload.eval {
85            Eval::Boolean(f) => f(&self.args, cx),
86            _ => bool::from_value(self.evaluate(cx)?),
87        }
88    }
89
90    pub(crate) fn eval_str<'e>(&'e self, cx: &EvaluationContext<'_>) -> EvalResult<Cow<'e, str>> {
91        match self.overload.eval {
92            Eval::String(f) => f(&self.args, cx),
93            _ => Cow::from_value(self.evaluate(cx)?),
94        }
95    }
96
97    pub(crate) fn eval_color(&self, cx: &EvaluationContext<'_>) -> EvalResult<Color> {
98        match self.overload.eval {
99            Eval::Color(f) => f(&self.args, cx),
100            _ => Color::from_value(self.evaluate(cx)?),
101        }
102    }
103
104    pub(crate) fn evaluate(&self, cx: &EvaluationContext<'_>) -> EvaluationResult {
105        match self.overload.eval {
106            Eval::Number(f) => f(&self.args, cx).map(Value::Number),
107            Eval::Boolean(f) => f(&self.args, cx).map(Value::Bool),
108            Eval::String(f) => f(&self.args, cx).map(|s| Value::String(s.into_owned())),
109            Eval::Color(f) => f(&self.args, cx).map(Value::Color),
110            Eval::Value(f) => f(&self.args, cx),
111        }
112    }
113}
114
115fn expected_types_error(overloads: &[Arc<Overload>], args: &[Expr]) -> String {
116    // Only used if there are no overloads with matching number of args
117    let mut available: Vec<String> = Vec::new();
118    let mut matching: Vec<String> = Vec::new();
119    for overload in overloads {
120        match &overload.params {
121            Params::Varargs(t) => {
122                matching.push(format!("({})", type_::to_string(t)));
123            }
124            Params::Fixed(params) => {
125                let types = format!("({})", params.iter().map(type_::to_string).collect::<Vec<_>>().join(", "));
126                if params.len() == args.len() {
127                    matching.push(types);
128                } else {
129                    available.push(types);
130                }
131            }
132        }
133    }
134
135    let signatures = if matching.is_empty() { available.join(" | ") } else { matching.join(" | ") };
136
137    let actual_types = args.iter().map(|arg| type_::to_string(&arg.get_type())).collect::<Vec<_>>().join(", ");
138
139    format!("Expected arguments of type {signatures}, but found ({actual_types}) instead.")
140}
141
142fn create_compound_expression_from(
143    overloads: &[Arc<Overload>],
144    args: Vec<Expr>,
145    ctx: &mut ParsingContext,
146) -> ParseResult {
147    let mut signature_context = ctx.detached();
148
149    for overload in overloads {
150        signature_context.clear_errors();
151
152        match &overload.params {
153            Params::Fixed(params) => {
154                if params.len() != args.len() {
155                    signature_context.error(format!(
156                        "Expected {} arguments, but found {} instead.",
157                        params.len(),
158                        args.len()
159                    ));
160                    continue;
161                }
162
163                for (i, arg) in args.iter().enumerate() {
164                    if let Some(err) = check_subtype(&params[i], &arg.get_type()) {
165                        signature_context.error_at(err, i + 1);
166                    }
167                }
168            }
169            Params::Varargs(param_type) => {
170                for (i, arg) in args.iter().enumerate() {
171                    if let Some(err) = check_subtype(param_type, &arg.get_type()) {
172                        signature_context.error_at(err, i + 1);
173                    }
174                }
175            }
176        }
177
178        if !signature_context.has_errors() {
179            return Some(Expr::new(Node::Compound(Box::new(CompoundExpression {
180                overload: Arc::clone(overload),
181                args: args.into(),
182            }))));
183        }
184    }
185
186    if overloads.len() == 1 {
187        ctx.append_errors(&signature_context);
188    } else {
189        ctx.error(expected_types_error(overloads, &args));
190    }
191
192    None
193}
194
195pub(crate) fn parse_compound_expression(name: &str, value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
196    debug_assert!(value.is_array() && value.array_length() > 0);
197
198    let functions = Arc::clone(ctx.functions());
199    let Some(function) = functions.get(name) else {
200        ctx.error_at(
201            format!(r#"Unknown expression "{name}". If you wanted a literal array, use ["literal", [...]]."#),
202            0,
203        );
204        return None;
205    };
206    let overloads = function.overloads();
207
208    let length = value.array_length();
209
210    // Per the style specification, the "global-state" property name must be
211    // a string literal, not the result of a sub-expression.
212    if overloads.iter().any(|overload| overload.role == Role::GlobalState)
213        && length == 2
214        && value.array_member(1).to_string().is_none()
215    {
216        ctx.error_at("Global state property must be a string literal.".to_owned(), 1);
217        return None;
218    }
219
220    // Each failed overload parses its arguments, so two overloads of one arity
221    // would make parsing a nested chain of them exponential in its depth.
222    let mut overload_matched_arity = false;
223    for overload in overloads {
224        let matches = match &overload.params {
225            Params::Varargs(_) => true,
226            Params::Fixed(p) => p.len() == length - 1,
227        };
228        if matches {
229            debug_assert!(!overload_matched_arity);
230            overload_matched_arity = true;
231
232            // First parse all the args, potentially coercing to the types
233            // expected by this overload.
234            ctx.clear_errors();
235            let mut arg_parse_failed = false;
236            let mut args = Vec::with_capacity(length - 1);
237
238            for i in 1..length {
239                let expected = match &overload.params {
240                    Params::Varargs(t) => t.clone(),
241                    Params::Fixed(params) => params[i - 1].clone(),
242                };
243
244                let Some(parsed) = ctx.parse(&value.array_member(i), i, Some(expected), None) else {
245                    arg_parse_failed = true;
246                    break;
247                };
248                args.push(parsed);
249            }
250            // When the args couldn't be coerced to this overload's expected
251            // types, move on to the next one.
252            if !arg_parse_failed {
253                let parse_with_args = create_compound_expression_from(overloads, args, ctx);
254                if parse_with_args.is_some() {
255                    return parse_with_args;
256                }
257            }
258        }
259    }
260    // The overload that takes this many arguments failed, and its errors say
261    // why. Parsing the arguments again would double the work at every level.
262    if overload_matched_arity {
263        return None;
264    }
265
266    // No overload takes this many arguments. Parse the arguments without
267    // expected types just for the error message
268    ctx.clear_errors();
269    let mut args = Vec::with_capacity(length - 1);
270
271    for i in 1..length {
272        let parsed = ctx.parse(&value.array_member(i), i, None, None)?;
273        args.push(parsed);
274    }
275
276    ctx.error(expected_types_error(overloads, &args));
277
278    None
279}
280
281/// The call of the function `name` of `ctx`'s functions with `args`, through
282/// the first of its overloads whose parameters the arguments' types match.
283pub fn create_compound_expression(name: &str, args: Vec<Expr>, ctx: &mut ParsingContext) -> ParseResult {
284    let functions = Arc::clone(ctx.functions());
285    let overloads = functions.get(name).map_or(&[][..], FunctionDef::overloads);
286    create_compound_expression_from(overloads, args, ctx)
287}