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
pub use crate::stdfn::{RpcCallId, TimerId};
use crate::{
    expr::{Expr, ExprId, ExprKind},
    stdfn,
};
use arcstr::ArcStr;
use fxhash::{FxBuildHasher, FxHashMap};
use netidx::{
    chars::Chars,
    path::Path,
    subscriber::{Dval, SubId, UpdatesFlags, Value},
};
use std::{
    collections::{HashMap, VecDeque},
    fmt,
    sync::{Arc, Weak},
    time::Duration,
};

pub struct DbgCtx {
    events: VecDeque<(ExprId, Value)>,
    watch: HashMap<ExprId, Vec<Weak<dyn Fn(&Value) + Send + Sync>>, FxBuildHasher>,
    current: HashMap<ExprId, Value, FxBuildHasher>,
}

impl DbgCtx {
    fn new() -> Self {
        DbgCtx {
            events: VecDeque::new(),
            watch: HashMap::with_hasher(FxBuildHasher::default()),
            current: HashMap::with_hasher(FxBuildHasher::default()),
        }
    }

    pub fn add_watch(&mut self, id: ExprId, watch: &Arc<dyn Fn(&Value) + Send + Sync>) {
        let watches = self.watch.entry(id).or_insert_with(Vec::new);
        if let Some(v) = self.current.get(&id) {
            watch(v);
        }
        watches.push(Arc::downgrade(watch));
    }

    pub fn add_event(&mut self, id: ExprId, value: Value) {
        const MAX: usize = 1000;
        self.events.push_back((id, value.clone()));
        self.current.insert(id, value.clone());
        if self.events.len() > MAX {
            self.events.pop_front();
            if self.watch.len() > MAX {
                self.watch.retain(|_, vs| {
                    vs.retain(|v| Weak::upgrade(v).is_some());
                    !vs.is_empty()
                });
            }
        }
        if let Some(watch) = self.watch.get_mut(&id) {
            let mut i = 0;
            while i < watch.len() {
                match Weak::upgrade(&watch[i]) {
                    None => {
                        watch.remove(i);
                    }
                    Some(f) => {
                        f(&value);
                        i += 1;
                    }
                }
            }
        }
    }

    pub fn clear(&mut self) {
        self.events.clear();
        self.current.clear();
        self.watch.retain(|_, v| {
            v.retain(|w| Weak::strong_count(w) > 0);
            v.len() > 0
        });
    }
}

#[derive(Debug)]
pub enum Event<E> {
    Variable(Path, Chars, Value),
    Netidx(SubId, Value),
    Rpc(RpcCallId, Value),
    Timer(TimerId),
    User(E),
}

pub type InitFn<C, E> = Arc<
    dyn Fn(
            &mut ExecCtx<C, E>,
            &[Node<C, E>],
            Path,
            ExprId,
        ) -> Box<dyn Apply<C, E> + Send + Sync>
        + Send
        + Sync,
>;

pub trait Register<C: Ctx, E> {
    fn register(ctx: &mut ExecCtx<C, E>);
}

pub trait Apply<C: Ctx, E> {
    fn current(&self) -> Option<Value>;
    fn update(
        &mut self,
        ctx: &mut ExecCtx<C, E>,
        from: &mut [Node<C, E>],
        event: &Event<E>,
    ) -> Option<Value>;
}

pub trait Ctx {
    fn clear(&mut self);
    fn durable_subscribe(
        &mut self,
        flags: UpdatesFlags,
        path: Path,
        ref_by: ExprId,
    ) -> Dval;
    fn unsubscribe(&mut self, path: Path, dv: Dval, ref_by: ExprId);
    fn ref_var(&mut self, name: Chars, scope: Path, ref_by: ExprId);
    fn unref_var(&mut self, name: Chars, scope: Path, ref_by: ExprId);
    fn register_fn(&mut self, name: Chars, scope: Path);
    fn set_var(
        &mut self,
        variables: &mut FxHashMap<Path, FxHashMap<Chars, Value>>,
        local: bool,
        scope: Path,
        name: Chars,
        value: Value,
    );

    /// For a given name, this must have at most one outstanding call
    /// at a time, and must preserve the order of the calls. Calls to
    /// different names may execute concurrently.
    fn call_rpc(
        &mut self,
        name: Path,
        args: Vec<(Chars, Value)>,
        ref_by: ExprId,
        id: RpcCallId,
    );

    /// arrange to have a Timer event delivered after timeout
    fn set_timer(&mut self, id: TimerId, timeout: Duration, ref_by: ExprId);
}

pub fn store_var(
    variables: &mut FxHashMap<Path, FxHashMap<Chars, Value>>,
    local: bool,
    scope: &Path,
    name: &Chars,
    value: Value,
) -> (bool, Path) {
    if local {
        let mut new = false;
        variables
            .entry(scope.clone())
            .or_insert_with(|| {
                new = true;
                HashMap::with_hasher(FxBuildHasher::default())
            })
            .insert(name.clone(), value);
        (new, scope.clone())
    } else {
        let mut iter = Path::dirnames(scope);
        loop {
            match iter.next_back() {
                Some(scope) => {
                    if let Some(vars) = variables.get_mut(scope) {
                        if let Some(var) = vars.get_mut(name) {
                            *var = value;
                            break (false, Path::from(ArcStr::from(scope)));
                        }
                    }
                }
                None => break store_var(variables, true, &Path::root(), name, value),
            }
        }
    }
}

pub struct ExecCtx<C: Ctx + 'static, E: 'static> {
    pub functions: FxHashMap<String, InitFn<C, E>>,
    pub variables: FxHashMap<Path, FxHashMap<Chars, Value>>,
    pub dbg_ctx: DbgCtx,
    pub user: C,
}

impl<C: Ctx, E> ExecCtx<C, E> {
    pub fn lookup_var(&self, scope: &Path, name: &Chars) -> Option<(&Path, &Value)> {
        let mut iter = Path::dirnames(scope);
        loop {
            match iter.next_back() {
                Some(scope) => {
                    if let Some((scope, vars)) = self.variables.get_key_value(scope) {
                        if let Some(var) = vars.get(name) {
                            break Some((scope, var));
                        }
                    }
                }
                None => break None,
            }
        }
    }

    pub fn clear(&mut self) {
        self.variables.clear();
        self.dbg_ctx.clear();
        self.user.clear();
    }

    pub fn no_std(user: C) -> Self {
        ExecCtx {
            functions: HashMap::with_hasher(FxBuildHasher::default()),
            variables: HashMap::with_hasher(FxBuildHasher::default()),
            dbg_ctx: DbgCtx::new(),
            user,
        }
    }

    pub fn new(user: C) -> Self {
        let mut t = ExecCtx::no_std(user);
        stdfn::AfterIdle::register(&mut t);
        stdfn::All::register(&mut t);
        stdfn::And::register(&mut t);
        stdfn::Any::register(&mut t);
        stdfn::Array::register(&mut t);
        stdfn::Basename::register(&mut t);
        stdfn::Cast::register(&mut t);
        stdfn::Cmp::register(&mut t);
        stdfn::Contains::register(&mut t);
        stdfn::Count::register(&mut t);
        stdfn::Dirname::register(&mut t);
        stdfn::Divide::register(&mut t);
        stdfn::Do::register(&mut t);
        stdfn::EndsWith::register(&mut t);
        stdfn::Eval::register(&mut t);
        stdfn::FilterErr::register(&mut t);
        stdfn::Filter::register(&mut t);
        stdfn::Get::register(&mut t);
        stdfn::If::register(&mut t);
        stdfn::Index::register(&mut t);
        stdfn::Isa::register(&mut t);
        stdfn::IsErr::register(&mut t);
        stdfn::Load::register(&mut t);
        stdfn::Max::register(&mut t);
        stdfn::Mean::register(&mut t);
        stdfn::Min::register(&mut t);
        stdfn::Not::register(&mut t);
        stdfn::Once::register(&mut t);
        stdfn::Or::register(&mut t);
        stdfn::Product::register(&mut t);
        stdfn::Replace::register(&mut t);
        stdfn::RpcCall::register(&mut t);
        stdfn::Sample::register(&mut t);
        stdfn::Set::register(&mut t);
        stdfn::StartsWith::register(&mut t);
        stdfn::Store::register(&mut t);
        stdfn::StringConcat::register(&mut t);
        stdfn::StringJoin::register(&mut t);
        stdfn::StripPrefix::register(&mut t);
        stdfn::StripSuffix::register(&mut t);
        stdfn::Sum::register(&mut t);
        stdfn::Timer::register(&mut t);
        stdfn::TrimEnd::register(&mut t);
        stdfn::Trim::register(&mut t);
        stdfn::TrimStart::register(&mut t);
        stdfn::Uniq::register(&mut t);
        t
    }
}

pub enum Node<C: Ctx, E> {
    Error(Expr, Value),
    Constant(Expr, Value),
    Apply {
        spec: Expr,
        args: Vec<Node<C, E>>,
        function: Box<dyn Apply<C, E> + Send + Sync>,
    },
}

impl<C: Ctx, E> fmt::Display for Node<C, E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Node::Error(s, _) | Node::Constant(s, _) | Node::Apply { spec: s, .. } => {
                write!(f, "{}", s)
            }
        }
    }
}

impl<C: Ctx, E> Node<C, E> {
    pub fn compile_int(
        ctx: &mut ExecCtx<C, E>,
        spec: Expr,
        scope: Path,
        top_id: ExprId,
    ) -> Self {
        match &spec {
            Expr { kind: ExprKind::Constant(v), id } => {
                ctx.dbg_ctx.add_event(*id, v.clone());
                Node::Constant(spec.clone(), v.clone())
            }
            Expr { kind: ExprKind::Apply { args, function }, id } => {
                let scope = if function == "do" && id != &top_id {
                    scope.append(&format!("do{:?}", id))
                } else {
                    scope
                };
                let args: Vec<Node<C, E>> = args
                    .iter()
                    .map(|spec| {
                        Node::compile_int(ctx, spec.clone(), scope.clone(), top_id)
                    })
                    .collect();
                match ctx.functions.get(function).map(Arc::clone) {
                    None => {
                        let e = Value::Error(Chars::from(format!(
                            "unknown function {}",
                            function
                        )));
                        ctx.dbg_ctx.add_event(spec.id, e.clone());
                        Node::Error(spec.clone(), e)
                    }
                    Some(init) => {
                        let function = init(ctx, &args, scope, top_id);
                        if let Some(v) = function.current() {
                            ctx.dbg_ctx.add_event(spec.id, v)
                        }
                        Node::Apply { spec, args, function }
                    }
                }
            }
        }
    }

    pub fn compile(ctx: &mut ExecCtx<C, E>, scope: Path, spec: Expr) -> Self {
        let top_id = spec.id;
        Self::compile_int(ctx, spec, scope, top_id)
    }

    pub fn current(&self) -> Option<Value> {
        match self {
            Node::Error(_, v) => Some(v.clone()),
            Node::Constant(_, v) => Some(v.clone()),
            Node::Apply { function, .. } => function.current(),
        }
    }

    pub fn update(&mut self, ctx: &mut ExecCtx<C, E>, event: &Event<E>) -> Option<Value> {
        match self {
            Node::Error(_, _) | Node::Constant(_, _) => None,
            Node::Apply { spec, args, function } => {
                let res = function.update(ctx, args, event);
                if let Some(v) = &res {
                    ctx.dbg_ctx.add_event(spec.id, v.clone());
                }
                res
            }
        }
    }
}