compmd 0.13.0

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In development.
Documentation
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! The type-checker: every expression is checked before it is evaluated (spec §8.2), each branch of `&&`, `||` and
//! `?:` too, so an error in a branch that isn't taken is still found.

use super::ast::{Expr, Literal, Macro, OPTIONAL};
use super::functions::{Function, LEFT_OUT};
use super::library::{self, INT_HINT};
use super::ops::BinaryOp;
use super::optionals::OptionalFunction;
use super::patterns;
use super::types::Type;
use super::{Error, FunctionTypes, Scope};
use crate::nearest::nearest;

/// What an expression is checked as: one of a document, or a pure expression (spec §8.2), which reads no `md` and
/// names a timestamp's time zone.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Profile {
    Document,
    Pure,
}

/// Checks `expr` as `profile` against the types of the variables in `scope`, and gives its type.
pub(crate) fn check(
    expr: &Expr,
    scope: &Scope,
    functions: &dyn FunctionTypes,
    profile: Profile,
) -> Result<Type, Error> {
    Checker {
        scope,
        functions,
        profile,
        locals: Vec::new(),
        guarded: Vec::new(),
    }
    .check(expr)
}

/// The names of a field path such as `md.doc.title`, or `None` for any other expression.
fn path(expr: &Expr) -> Option<Vec<&str>> {
    match expr {
        Expr::Ident(name, _) => Some(vec![name]),
        Expr::Select(operand, field, _) => {
            let mut names = path(operand)?;
            names.push(field);
            Some(names)
        }
        _ => None,
    }
}

/// The fields `condition` proves present when it is true: `has(a.b)`, and those of either side of `&&`.
fn proven(condition: &Expr) -> Vec<Vec<&str>> {
    match condition {
        Expr::Has(operand, field, ..) => path(operand)
            .map(|mut names| {
                names.push(field);
                names
            })
            .into_iter()
            .collect(),
        Expr::And(left, right, _) => proven(left).into_iter().chain(proven(right)).collect(),
        _ => Vec::new(),
    }
}

struct Checker<'a> {
    scope: &'a Scope,
    functions: &'a dyn FunctionTypes,
    profile: Profile,
    /// Comprehension variables, innermost last.
    locals: Vec<(&'a str, Type)>,
    /// Fields a `has()` proves present where they are checked, so a field a record may lack can be read there.
    guarded: Vec<Vec<&'a str>>,
}

impl<'a> Checker<'a> {
    fn check(&mut self, expr: &'a Expr) -> Result<Type, Error> {
        match expr {
            Expr::Literal(literal, _) => Ok(literal_type(literal)),
            Expr::Ident(name, at) => self.lookup(name).ok_or_else(|| {
                if self.profile == Profile::Pure && name == "md" {
                    return Error::type_error(
                        *at,
                        "a pure expression reads only its own variables, not md",
                    );
                }
                let names = self
                    .locals
                    .iter()
                    .map(|(n, _)| *n)
                    .chain(self.scope.names());
                unknown(*at, "name", name, names)
            }),
            Expr::Select(operand, field, at) | Expr::OptSelect(operand, field, at) => {
                let (operand_type, optional) = unwrapped(self.check(operand)?);
                let selected = self.select(expr, &operand_type, field, *at);
                read(expr, selected, &operand_type, optional)
            }
            Expr::Index(operand, index, at) | Expr::OptIndex(operand, index, at) => {
                let (operand, optional) = unwrapped(self.check(operand)?);
                let index_type = self.check(index)?;
                let found = self::index(&operand, &index_type, index, *at);
                read(expr, found, &operand, optional)
            }
            Expr::Unary(op, operand, at) => {
                let operand = self.check(operand)?;
                op.result_type(&operand).ok_or_else(|| {
                    Error::type_error(
                        *at,
                        format!("'{}' can't be applied to {operand}", op.name()),
                    )
                })
            }
            Expr::Binary(op, left, right, _) => self.binary(*op, left, right),
            Expr::Call {
                target,
                name,
                args,
                at,
            } => self.call(target.as_deref(), name, args, *at),
            Expr::And(left, right, at) => {
                self.boolean(left, *at, "&&")?;
                self.guarded_by(proven(left), |checker| checker.boolean(right, *at, "&&"))?;
                Ok(Type::Bool)
            }
            Expr::Or(left, right, at) => {
                self.boolean(left, *at, "||")?;
                self.boolean(right, *at, "||")?;
                Ok(Type::Bool)
            }
            Expr::Conditional(condition, then, otherwise, at) => {
                let condition_type = self.check(condition)?;
                if !condition_type.fits(&Type::Bool) {
                    return Err(Error::type_error(
                        *at,
                        format!("the condition of '?:' must be a bool, not {condition_type}"),
                    ));
                }
                let then = self.guarded_by(proven(condition), |checker| checker.check(then))?;
                Ok(then.join(self.check(otherwise)?))
            }
            Expr::List(items, _) => {
                let types = items
                    .iter()
                    .map(|item| self.check(item))
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(Type::list(Type::joined(types)))
            }
            Expr::Map(entries, _) => self.map(entries),
            Expr::Has(operand, _, at, _) => match self.check(operand)? {
                Type::Record(_) | Type::Map(..) | Type::Dyn => Ok(Type::Bool),
                other => Err(Error::type_error(
                    *at,
                    format!("has() needs a map, not {other}"),
                )),
            },
            Expr::Comprehension {
                kind,
                range,
                var,
                filter,
                body,
                at,
            } => {
                let element = self.element(*kind, range, *at)?;
                self.locals.push((var, element.clone()));
                let result = self.comprehension(*kind, element, filter.as_deref(), body, *at);
                self.locals.pop();
                result
            }
        }
    }

    /// The type of the elements a macro ranges over: a list's elements, or a map's keys; an optional's value for
    /// `optMap` and `optFlatMap`.
    fn element(&mut self, kind: Macro, range: &'a Expr, at: usize) -> Result<Type, Error> {
        let range = self.check(range)?;
        if kind.on_optional() {
            return match range {
                Type::Optional(value) => Ok((*value).clone()),
                Type::Dyn => Ok(Type::Dyn),
                other => Err(Error::type_error(
                    at,
                    format!("{}() needs an optional, not {other}", kind.name()),
                )),
            };
        }
        match range {
            Type::List(element) => Ok((*element).clone()),
            Type::Map(key, _) => Ok((*key).clone()),
            Type::Record(_) => Ok(Type::String),
            Type::Dyn => Ok(Type::Dyn),
            other => Err(Error::type_error(
                at,
                format!("{}() needs a list or a map, not {other}", kind.name()),
            )),
        }
    }

    /// An operator's type, or an error at the start of the expression it makes.
    fn binary(&mut self, op: BinaryOp, left: &'a Expr, right: &'a Expr) -> Result<Type, Error> {
        let at = left.start();
        let (left, right) = (self.check(left)?, self.check(right)?);
        op.result_type(&left, &right).ok_or_else(|| {
            let hint = if op == BinaryOp::Remainder {
                int_hint(&[left.clone(), right.clone()])
            } else {
                ""
            };
            Error::type_error(
                at,
                format!(
                    "'{}' can't be applied to {left} and {right}{hint}",
                    op.name()
                ),
            )
        })
    }

    /// A map literal: CEL's map keys are `int`, `uint`, `bool` and `string`.
    fn map(&mut self, entries: &'a [(Expr, Expr)]) -> Result<Type, Error> {
        let (mut keys, mut values) = (Vec::new(), Vec::new());
        for (key, value) in entries {
            let key_type = self.check(key)?;
            if !matches!(
                key_type.cel(),
                Type::Int | Type::Uint | Type::Bool | Type::String | Type::Dyn
            ) {
                return Err(Error::type_error(
                    key.at(),
                    format!("a map key must be an int, uint, bool or string, not {key_type}"),
                ));
            }
            keys.push(key_type);
            values.push(self.check(value)?);
        }
        Ok(Type::map(Type::joined(keys), Type::joined(values)))
    }

    fn lookup(&self, name: &str) -> Option<Type> {
        let local = self
            .locals
            .iter()
            .rev()
            .find(|(n, _)| *n == name)
            .map(|(_, t)| t);
        local.or_else(|| self.scope.get(name)).cloned()
    }

    /// Checks `check` with the fields in `guards` proven present.
    fn guarded_by<T>(
        &mut self,
        guards: Vec<Vec<&'a str>>,
        check: impl FnOnce(&mut Self) -> T,
    ) -> T {
        let count = guards.len();
        self.guarded.extend(guards);
        let result = check(self);
        self.guarded.truncate(self.guarded.len() - count);
        result
    }

    fn boolean(&mut self, side: &'a Expr, at: usize, operator: &str) -> Result<(), Error> {
        let side = self.check(side)?;
        if side.fits(&Type::Bool) {
            Ok(())
        } else {
            Err(Error::type_error(
                at,
                format!("'{operator}' takes bools, not {side}"),
            ))
        }
    }

    fn select(&self, expr: &Expr, operand: &Type, field: &str, at: usize) -> Result<Type, Error> {
        match operand {
            Type::Record(fields) => match fields.get(field) {
                Some(ty) => Ok(ty.clone()),
                None if path(expr).is_some_and(|path| self.guarded.contains(&path)) => {
                    Ok(Type::Dyn)
                }
                None => Err(unknown(
                    at,
                    "field",
                    field,
                    fields.keys().map(String::as_str),
                )),
            },
            Type::Map(key, value) if Type::String.fits(key) => Ok((**value).clone()),
            Type::Dyn => Ok(Type::Dyn),
            other => Err(Error::type_error(at, format!("{other} has no fields"))),
        }
    }

    fn comprehension(
        &mut self,
        kind: Macro,
        element: Type,
        filter: Option<&'a Expr>,
        body: &'a Expr,
        at: usize,
    ) -> Result<Type, Error> {
        let predicate = |checker: &mut Self, expr: &'a Expr| -> Result<(), Error> {
            let ty = checker.check(expr)?;
            if ty.fits(&Type::Bool) {
                Ok(())
            } else {
                Err(Error::type_error(
                    at,
                    format!("{}() needs a bool expression, not {ty}", kind.name()),
                ))
            }
        };
        if let Some(filter) = filter {
            predicate(self, filter)?;
        }
        match kind {
            Macro::Map => Ok(Type::list(self.check(body)?)),
            Macro::OptMap => Ok(Type::optional(self.check(body)?)),
            Macro::OptFlatMap => match self.check(body)? {
                optional @ (Type::Optional(_) | Type::Dyn) => Ok(optional),
                other => Err(Error::type_error(
                    at,
                    format!("optFlatMap() needs an optional expression, not {other}"),
                )),
            },
            Macro::Filter => {
                predicate(self, body)?;
                Ok(Type::list(element))
            }
            Macro::All | Macro::Exists | Macro::ExistsOne => {
                predicate(self, body)?;
                Ok(Type::Bool)
            }
        }
    }

    fn call(
        &mut self,
        target: Option<&'a Expr>,
        name: &str,
        args: &'a [Expr],
        at: usize,
    ) -> Result<Type, Error> {
        if matches!(target, Some(Expr::Ident(namespace, _)) if namespace == "md") {
            return self.md_call(name, args, at);
        }
        if Expr::is_optional_call(target) && self.lookup(OPTIONAL).is_none() {
            let arg_types = args
                .iter()
                .map(|a| self.check(a))
                .collect::<Result<Vec<_>, _>>()?;
            return library::type_of::<OptionalFunction>(name, None, &arg_types)
                .map_err(|message| Error::type_error(at, message));
        }
        let receiver = target.map(|t| self.check(t)).transpose()?;
        let arg_types = args
            .iter()
            .map(|a| self.check(a))
            .collect::<Result<Vec<_>, _>>()?;
        if LEFT_OUT.contains(&name) {
            return Err(Error::type_error(
                at,
                format!("{name}() isn't in the CompMD CEL profile"),
            ));
        }
        let result = library::type_of::<Function>(name, receiver.as_ref(), &arg_types)
            .map_err(|message| Error::type_error(at, message))?;
        // A timestamp's method without arguments is a getter in md.tz.
        if self.profile == Profile::Pure
            && receiver.as_ref().map(Type::cel) == Some(&Type::Timestamp)
            && args.is_empty()
        {
            return Err(Error::type_error(
                at,
                format!(
                    "a pure expression has no md.tz: name the time zone, an offset such as {name}(\"+00:00\")"
                ),
            ));
        }
        patterns::check(name, args)?;
        Ok(result)
    }

    fn md_call(&mut self, name: &str, args: &'a [Expr], at: usize) -> Result<Type, Error> {
        let arg_types = args
            .iter()
            .map(|a| self.check(a))
            .collect::<Result<Vec<_>, _>>()?;
        self.functions
            .result_type(name, &arg_types)
            .map_err(|message| Error::type_error(at, message))
    }
}

/// `ty`'s value's type when it is an optional, and whether it was one: a select or an index on an optional reads its
/// value, and stays optional.
fn unwrapped(ty: Type) -> (Type, bool) {
    match ty {
        Type::Optional(value) => ((*value).clone(), true),
        other => (other, false),
    }
}

/// The type of `expr`, a select or an index whose operand has type `operand` and gives `found`: optional when it is
/// `.?` or `[?…]`, or reads an optional (`on_optional`). `.?` and `[?…]` read a field a record of known fields lacks
/// as `dyn`, which is none when evaluated rather than an error.
fn read(
    expr: &Expr,
    found: Result<Type, Error>,
    operand: &Type,
    on_optional: bool,
) -> Result<Type, Error> {
    if !matches!(expr, Expr::OptSelect(..) | Expr::OptIndex(..)) {
        let found = found?;
        return Ok(if on_optional {
            Type::optional(found)
        } else {
            found
        });
    }
    match (found, operand) {
        (Err(_), Type::Record(_)) => Ok(Type::optional(Type::Dyn)),
        (found, _) => found.map(Type::optional),
    }
}

fn int_hint(given: &[Type]) -> &'static str {
    if given.contains(&Type::Double) {
        INT_HINT
    } else {
        ""
    }
}

fn literal_type(literal: &Literal) -> Type {
    match literal {
        Literal::Int(_) => Type::Int,
        Literal::Uint(_) => Type::Uint,
        Literal::Double(_) => Type::Double,
        Literal::String(_) => Type::String,
        Literal::Bool(_) => Type::Bool,
        Literal::Null => Type::Null,
    }
}

fn index(operand: &Type, index_type: &Type, index: &Expr, at: usize) -> Result<Type, Error> {
    match operand {
        Type::List(element) if index_type.fits(&Type::Int) => Ok((**element).clone()),
        Type::List(_) => Err(Error::type_error(
            at,
            format!(
                "a list index must be an int, not {index_type}{}",
                int_hint(std::slice::from_ref(index_type))
            ),
        )),
        // Number keys match by value, so any number finds an `int` or `uint` key.
        Type::Map(key, value)
            if index_type.fits(key) || (key.is_numeric() && index_type.is_numeric()) =>
        {
            Ok((**value).clone())
        }
        Type::Record(fields) if index_type.fits(&Type::String) => match index {
            Expr::Literal(Literal::String(field), _) => fields
                .get(field)
                .cloned()
                .ok_or_else(|| unknown(at, "field", field, fields.keys().map(String::as_str))),
            _ => Ok(Type::Dyn),
        },
        Type::Dyn => Ok(Type::Dyn),
        other => Err(Error::type_error(
            at,
            format!("{other} can't be indexed with {index_type}"),
        )),
    }
}

/// An unknown name, field or function, with the nearest known one when one is close enough.
fn unknown<'n>(
    at: usize,
    what: &str,
    name: &str,
    known: impl IntoIterator<Item = &'n str>,
) -> Error {
    match nearest(name, known) {
        Some(near) => Error::type_error(
            at,
            format!("unknown {what} '{name}'; did you mean '{near}'?"),
        ),
        None => Error::type_error(at, format!("unknown {what} '{name}'")),
    }
}