Skip to main content

temple_dsl/embed/
queries.rs

1use crate::common::error::Span;
2use crate::eval::builtins::is_builtin_function;
3use crate::syntax::ast::{Expr, ExprKind, PathSegment};
4use smol_str::SmolStr;
5
6/// A read of an `input` path: `input.data.order` is `["data", "order"]`,
7/// stopping at the first index or method call.
8#[derive(Debug, Clone, PartialEq, Eq)]
9#[allow(missing_docs)] // fields name themselves
10pub struct InputRead {
11    pub path: Vec<SmolStr>,
12    /// Whether any step uses `?.`.
13    pub optional: bool,
14    pub span: Span,
15}
16
17pub(super) struct CallSite {
18    pub name: SmolStr,
19    pub arity: usize,
20    pub span: Span,
21}
22
23fn input_read(expr: &Expr) -> Option<InputRead> {
24    let ExprKind::Path { root, segments, .. } = &expr.kind else {
25        return None;
26    };
27    if root != "input" {
28        return None;
29    }
30    let mut read = InputRead {
31        path: Vec::new(),
32        optional: false,
33        span: expr.span,
34    };
35    for segment in segments {
36        let PathSegment::Field { name, optional, .. } = segment else {
37            break;
38        };
39        read.path.push(name.clone());
40        read.optional |= *optional;
41    }
42    Some(read)
43}
44
45pub(super) fn reads_in_expr(expr: &Expr, reads: &mut Vec<InputRead>) {
46    reads.extend(input_read(expr));
47    expr.for_each_child(&mut |child| reads_in_expr(child, reads));
48}
49
50pub(super) fn call_sites(expr: &Expr, calls: &mut Vec<CallSite>) {
51    if let ExprKind::FuncCall {
52        name,
53        name_span,
54        args,
55    } = &expr.kind
56    {
57        if !is_builtin_function(name) {
58            calls.push(CallSite {
59                name: name.clone(),
60                arity: args.len(),
61                span: *name_span,
62            });
63        }
64    }
65    expr.for_each_child(&mut |child| call_sites(child, calls));
66}