aura-lang 0.4.0

Aura configuration language: deterministic, capability-secured, schema-validated configs — embeddable library + the `aura` CLI
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
//! Host functions (D35): what a host provides, and what a script asks for.
//!
//! Two halves, kept apart on purpose. [`HostTable`] is the host's side - the
//! functions it registered, their kind and arity. [`requirements`] is the
//! script's side - every use of a `host:` module, found by walking the AST
//! before anything runs. The loader checks one against the other at load, `aura
//! check` lists the second without the first, and the language server explains
//! the import line from it. One walk, three readers, so they cannot disagree
//! about what a script needs.

use std::sync::Arc;

use indexmap::IndexMap;

use crate::eval::value::{FuncBody, FunctionDef, Value};
use crate::lexer::token::StrPart;
use crate::lexer::Lexer;
use crate::parser::ast::{Expr, ImportSource, LambdaBody, LitValue, Module, ObjectBody, Stmt};
use crate::parser::Parser;
use crate::span::Span;

/// Whether the host vouches the function is deterministic (D35 §2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostKind {
    /// Deterministic, by the host's promise. Allowed under `--hermetic`.
    Pure,
    /// A capability, like `env()`: refused under `--hermetic`.
    Effect,
}

/// What a host function produced, before it becomes an Aura value.
pub enum HostOutcome {
    /// Built by the exact serializer the boundary uses for arguments (D33), so
    /// a host result is held to the same rules: no NaN turned into `null`, no
    /// integer wrapped. Plain data, so it has no lifetime of its own.
    Value(Value<'static>),
    /// The host returned `Err` - `E0008`.
    Failed(String),
    /// An argument did not fit the function's types - `E0009`.
    BadArgument(String),
}

/// The erased function: JSON arguments in, an outcome out.
pub type HostCall = dyn Fn(&[serde_json::Value]) -> HostOutcome + Send + Sync;

/// One function a host provides.
pub struct HostFn {
    /// `geo.region`
    pub name: String,
    pub kind: HostKind,
    pub arity: usize,
    /// D35 §3: reachable from imported modules too, by explicit grant.
    pub for_imports: bool,
    pub call: Arc<HostCall>,
}

impl std::fmt::Debug for HostFn {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HostFn")
            .field("name", &self.name)
            .field("kind", &self.kind)
            .field("arity", &self.arity)
            .field("for_imports", &self.for_imports)
            .finish()
    }
}

/// Every function a host provides, by module and name.
#[derive(Debug, Default, Clone)]
pub struct HostTable {
    fns: IndexMap<String, Arc<HostFn>>,
    /// D35 §5: what one call costs in steps.
    pub call_steps: u64,
}

/// One step of evaluation is one expression; a host call is a system call, and
/// costs more. The host may change it (`host_call_steps`).
pub const DEFAULT_HOST_CALL_STEPS: u64 = 100;

impl HostTable {
    pub fn new() -> Self {
        HostTable {
            fns: IndexMap::new(),
            call_steps: DEFAULT_HOST_CALL_STEPS,
        }
    }

    pub fn insert(&mut self, f: HostFn) {
        self.fns.insert(f.name.clone(), Arc::new(f));
    }

    pub fn get(&self, module: &str, func: &str) -> Option<&Arc<HostFn>> {
        self.fns.get(&format!("{module}.{func}"))
    }

    /// Whether the host provides anything under this module name.
    pub fn has_module(&self, module: &str) -> bool {
        self.module_fns(module).next().is_some()
    }

    pub fn module_fns<'s>(&'s self, module: &'s str) -> impl Iterator<Item = &'s Arc<HostFn>> + 's {
        self.fns
            .values()
            .filter(move |f| f.name.split_once('.').is_some_and(|(m, _)| m == module))
    }

    pub fn fns(&self) -> impl Iterator<Item = &Arc<HostFn>> {
        self.fns.values()
    }

    /// Whether any registered function is an effect - a grant, so the load is
    /// no longer hermetic (D35 §2).
    pub fn has_effects(&self) -> bool {
        self.fns.values().any(|f| f.kind == HostKind::Effect)
    }
}

/// The module value a script's alias is bound to: an object of functions.
pub fn module_value<'a>(table: &HostTable, module: &str) -> Value<'a> {
    // Parameter names are only ever shown in a function's `Debug` form.
    const NAMES: [&str; 8] = ["a", "b", "c", "d", "e", "f", "g", "h"];
    Value::object(
        table
            .module_fns(module)
            .map(|f| {
                let func = f.name.split_once('.').map_or("", |(_, n)| n).to_string();
                let def = FunctionDef {
                    params: (0..f.arity).map(|i| NAMES[i % NAMES.len()]).collect(),
                    body: FuncBody::Host(f.clone()),
                    closure: std::sync::Weak::new(),
                    defined_in_root: true,
                    origin_dir: None,
                };
                (func, Value::Function(Arc::new(def)))
            })
            .collect(),
    )
}

/// A host result, rebuilt in the caller's lifetime. Built through the usual
/// constructors, so its memory is charged to the call (D35 §5).
pub(crate) fn rebind<'a>(v: &Value<'static>) -> Value<'a> {
    match v {
        Value::Null => Value::Null,
        Value::Bool(b) => Value::Bool(*b),
        Value::Int(i) => Value::Int(*i),
        Value::Float(f) => Value::Float(*f),
        Value::Str(s) => Value::str(s),
        Value::List(xs) => Value::list(xs.iter().map(rebind).collect()),
        Value::Object(m) => Value::object(m.iter().map(|(k, v)| (k.clone(), rebind(v))).collect()),
        // The boundary serializer produces data only.
        Value::Schema(_) | Value::Enum(_) | Value::Function(_) => Value::Null,
    }
}

thread_local! {
    static INSIDE_HOST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Marks the thread as running a host function, for as long as it lives
/// (D35 §6). A script entered while it is set refuses with `E0010`.
pub(crate) struct InsideHost(bool);

impl InsideHost {
    pub(crate) fn enter() -> Self {
        InsideHost(INSIDE_HOST.with(|c| c.replace(true)))
    }
}

impl Drop for InsideHost {
    fn drop(&mut self) {
        INSIDE_HOST.with(|c| c.set(self.0));
    }
}

/// Whether this thread is inside a host function called from a script.
pub(crate) fn inside_host() -> bool {
    INSIDE_HOST.with(|c| c.get())
}

// ---------------------------------------------------------------------------
// What a script asks for
// ---------------------------------------------------------------------------

/// One use of a host module in a script.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Requirement<'a> {
    /// The host module, as written after `host:`.
    pub module: &'a str,
    /// The alias the script bound it to.
    pub alias: &'a str,
    /// The function, when the use is a direct call `alias.func(...)`. `None`
    /// for any other use - the module passed around, stored, inspected - which
    /// is then taken to use every function the module has: the check has to
    /// stay sound when it cannot see which one is called (D35).
    pub func: Option<&'a str>,
    /// The number of arguments, for a direct call.
    pub arity: Option<usize>,
    pub span: Span,
}

/// Every `import "host:..."` in a module: `(alias, module, span)`.
pub fn host_imports<'a>(module: &Module<'a>) -> Vec<(&'a str, &'a str, Span)> {
    module
        .imports
        .iter()
        .filter_map(|imp| match imp.source {
            ImportSource::Host(m) => Some((imp.alias, m, imp.span)),
            _ => None,
        })
        .collect()
}

/// Every use of a host module in `module`, including inside `#{...}`.
pub fn requirements<'a>(module: &Module<'a>) -> Vec<Requirement<'a>> {
    let aliases: Vec<(&'a str, &'a str)> = host_imports(module)
        .into_iter()
        .map(|(a, m, _)| (a, m))
        .collect();
    let mut w = Walker {
        aliases: &aliases,
        out: Vec::new(),
    };
    if !aliases.is_empty() {
        for s in &module.stmts {
            w.stmt(s);
        }
    }
    w.out
}

struct Walker<'w, 'a> {
    aliases: &'w [(&'a str, &'a str)],
    out: Vec<Requirement<'a>>,
}

impl<'a> Walker<'_, 'a> {
    fn module_of(&self, name: &str) -> Option<&'a str> {
        self.aliases
            .iter()
            .find(|(a, _)| *a == name)
            .map(|(_, m)| *m)
    }

    fn stmts(&mut self, body: &[Stmt<'a>]) {
        for s in body {
            self.stmt(s);
        }
    }

    fn stmt(&mut self, s: &Stmt<'a>) {
        match s {
            Stmt::Assign { value, .. } | Stmt::Property { value, .. } | Stmt::Expr(value) => {
                self.expr(value)
            }
            Stmt::Assert { cond, message, .. } => {
                self.expr(cond);
                if let Some(m) = message {
                    self.expr(m);
                }
            }
            Stmt::TypeDecl(t) => {
                for f in &t.fields {
                    if let Some(d) = &f.default {
                        self.expr(d);
                    }
                }
                for inv in &t.invariants {
                    self.expr(&inv.cond);
                    if let Some(m) = &inv.message {
                        self.expr(m);
                    }
                }
            }
            Stmt::EnumDecl(_) => {}
            Stmt::FuncDecl { body, .. } => self.stmts(body),
            Stmt::Block(b) => {
                self.expr(&b.label);
                self.stmts(&b.body);
            }
        }
    }

    fn body(&mut self, b: &ObjectBody<'a>) {
        for (_, e, _) in &b.props {
            self.expr(e);
        }
    }

    fn expr(&mut self, e: &Expr<'a>) {
        match e {
            Expr::Literal(LitValue::InterpStr(parts), span) => {
                for part in parts {
                    if let StrPart::Interp(src) = part {
                        // Interpolations are parsed lazily, so the walk has to
                        // parse them itself: a host call inside `"#{...}"` must
                        // not slip past the hermetic and import checks.
                        if let Ok(toks) = Lexer::new(src, span.source).tokenize() {
                            if let Ok(inner) = Parser::new(toks).parse_expression() {
                                self.expr_at(&inner, *span);
                            }
                        }
                    }
                }
            }
            Expr::Literal(..) => {}
            Expr::Variable(name, span) => {
                if let Some(module) = self.module_of(name) {
                    self.out.push(Requirement {
                        module,
                        alias: name,
                        func: None,
                        arity: None,
                        span: *span,
                    });
                }
            }
            Expr::MethodCall {
                recv,
                method,
                args,
                lambda,
                span,
            } => {
                let direct = match recv.as_ref() {
                    Expr::Variable(name, _) => self.module_of(name).map(|m| (name, m)),
                    _ => None,
                };
                match direct {
                    Some((alias, module)) => self.out.push(Requirement {
                        module,
                        alias,
                        func: Some(method),
                        arity: Some(args.len()),
                        span: *span,
                    }),
                    None => self.expr(recv),
                }
                for a in args {
                    self.expr(a);
                }
                if let Some(l) = lambda {
                    self.expr(l);
                }
            }
            Expr::Unary { rhs, .. } => self.expr(rhs),
            Expr::Binary { lhs, rhs, .. } => {
                self.expr(lhs);
                self.expr(rhs);
            }
            Expr::Ternary {
                cond,
                then,
                otherwise,
                ..
            } => {
                self.expr(cond);
                self.expr(then);
                self.expr(otherwise);
            }
            Expr::Cond {
                arms, otherwise, ..
            } => {
                for (c, v) in arms {
                    self.expr(c);
                    self.expr(v);
                }
                self.expr(otherwise);
            }
            Expr::Call { callee, args, .. } => {
                self.expr(callee);
                for a in args {
                    self.expr(a);
                }
            }
            Expr::FieldAccess { recv, .. } => self.expr(recv),
            Expr::Index { recv, key, .. } => {
                self.expr(recv);
                self.expr(key);
            }
            Expr::ObjectLiteral(b) => self.body(b),
            Expr::ListLiteral(xs, _) => {
                for x in xs {
                    self.expr(x);
                }
            }
            Expr::Lambda { body, .. } => match body {
                LambdaBody::Expr(e) => self.expr(e),
                LambdaBody::Block(b) => self.stmts(b),
            },
            Expr::SchemaInstance { body, .. } => self.body(body),
        }
    }

    /// An expression parsed out of an interpolation: its spans start at zero,
    /// so every requirement found in it is reported at the string's own span.
    fn expr_at(&mut self, e: &Expr<'a>, at: Span) {
        let before = self.out.len();
        self.expr(e);
        for r in &mut self.out[before..] {
            r.span = at;
        }
    }
}