graphix_compiler/
lib.rs

1#[macro_use]
2extern crate netidx_core;
3#[macro_use]
4extern crate combine;
5#[macro_use]
6extern crate serde_derive;
7
8pub mod env;
9pub mod expr;
10pub mod node;
11pub mod typ;
12
13use crate::{
14    env::Env,
15    expr::{ExprId, ModPath},
16    typ::{FnType, Type},
17};
18use anyhow::{bail, Result};
19use arcstr::ArcStr;
20use enumflags2::{bitflags, BitFlags};
21use expr::Expr;
22use futures::channel::mpsc;
23use fxhash::{FxHashMap, FxHashSet};
24use log::info;
25use netidx::{
26    path::Path,
27    publisher::{Id, Val, WriteRequest},
28    subscriber::{self, Dval, SubId, UpdatesFlags, Value},
29};
30use netidx_protocols::rpc::server::{ArgSpec, RpcCall};
31use node::compiler;
32use parking_lot::RwLock;
33use poolshark::{
34    global::{GPooled, Pool},
35    local::LPooled,
36};
37use std::{
38    any::{Any, TypeId},
39    cell::Cell,
40    collections::{
41        hash_map::{self, Entry},
42        HashMap,
43    },
44    fmt::Debug,
45    mem,
46    sync::{
47        self,
48        atomic::{AtomicBool, Ordering},
49        LazyLock,
50    },
51    time::Duration,
52};
53use tokio::{task, time::Instant};
54use triomphe::Arc;
55
56#[derive(Debug, Clone, Copy)]
57#[bitflags]
58#[repr(u64)]
59pub enum CFlag {
60    WarnUnhandled,
61    WarnUnhandledArith,
62    WarnUnused,
63    WarningsAreErrors,
64}
65
66#[allow(dead_code)]
67static TRACE: AtomicBool = AtomicBool::new(false);
68
69#[allow(dead_code)]
70fn set_trace(b: bool) {
71    TRACE.store(b, Ordering::Relaxed)
72}
73
74#[allow(dead_code)]
75fn with_trace<F: FnOnce() -> Result<R>, R>(enable: bool, spec: &Expr, f: F) -> Result<R> {
76    let set = if enable {
77        eprintln!("trace enabled at {}, spec: {}", spec.pos, spec);
78        let prev = trace();
79        set_trace(true);
80        !prev
81    } else {
82        false
83    };
84    let r = match f() {
85        Err(e) => {
86            eprintln!("traced at {} failed with {e:?}", spec.pos);
87            Err(e)
88        }
89        r => r,
90    };
91    if set {
92        eprintln!("trace disabled at {}", spec.pos);
93        set_trace(false)
94    }
95    r
96}
97
98#[allow(dead_code)]
99fn trace() -> bool {
100    TRACE.load(Ordering::Relaxed)
101}
102
103#[macro_export]
104macro_rules! tdbg {
105    ($e:expr) => {
106        if $crate::trace() {
107            dbg!($e)
108        } else {
109            $e
110        }
111    };
112}
113
114#[macro_export]
115macro_rules! err {
116    ($tag:expr, $err:literal) => {{
117        let e: Value = ($tag.clone(), arcstr::literal!($err)).into();
118        Value::Error(triomphe::Arc::new(e))
119    }};
120}
121
122#[macro_export]
123macro_rules! errf {
124    ($tag:expr, $fmt:expr, $($args:expr),*) => {{
125        let msg: ArcStr = compact_str::format_compact!($fmt, $($args),*).as_str().into();
126        let e: Value = ($tag.clone(), msg).into();
127        Value::Error(triomphe::Arc::new(e))
128    }};
129    ($tag:expr, $fmt:expr) => {{
130        let msg: ArcStr = compact_str::format_compact!($fmt).as_str().into();
131        let e: Value = ($tag.clone(), msg).into();
132        Value::Error(triomphe::Arc::new(e))
133    }};
134}
135
136#[macro_export]
137macro_rules! defetyp {
138    ($name:ident, $tag_name:ident, $tag:literal, $typ:expr) => {
139        static $tag_name: ArcStr = arcstr::literal!($tag);
140        static $name: ::std::sync::LazyLock<$crate::typ::Type> =
141            ::std::sync::LazyLock::new(|| {
142                let scope = $crate::expr::ModPath::root();
143                $crate::expr::parser::parse_type(&format!($typ, $tag))
144                    .expect("failed to parse type")
145                    .scope_refs(&scope)
146            });
147    };
148}
149
150defetyp!(CAST_ERR, CAST_ERR_TAG, "InvalidCast", "Error<`{}(string)>");
151
152atomic_id!(LambdaId);
153
154impl From<u64> for LambdaId {
155    fn from(v: u64) -> Self {
156        LambdaId(v)
157    }
158}
159
160atomic_id!(BindId);
161
162impl From<u64> for BindId {
163    fn from(v: u64) -> Self {
164        BindId(v)
165    }
166}
167
168impl TryFrom<Value> for BindId {
169    type Error = anyhow::Error;
170
171    fn try_from(value: Value) -> Result<Self> {
172        match value {
173            Value::U64(id) => Ok(BindId(id)),
174            v => bail!("invalid bind id {v}"),
175        }
176    }
177}
178
179pub trait UserEvent: Clone + Debug + Any {
180    fn clear(&mut self);
181}
182
183pub trait CustomBuiltinType: Debug + Any + Send + Sync {}
184
185impl CustomBuiltinType for Value {}
186impl CustomBuiltinType for Option<Value> {}
187
188#[derive(Debug, Clone)]
189pub struct NoUserEvent;
190
191impl UserEvent for NoUserEvent {
192    fn clear(&mut self) {}
193}
194
195#[derive(Debug, Clone, Copy)]
196#[bitflags]
197#[repr(u64)]
198pub enum PrintFlag {
199    /// Dereference type variables and print both the tvar name and the bound
200    /// type or "unbound".
201    DerefTVars,
202    /// Replace common primitives with shorter type names as defined
203    /// in core. e.g. Any, instead of the set of every primitive type.
204    ReplacePrims,
205    /// When formatting an Origin don't print the source, just the location
206    NoSource,
207    /// When formatting an Origin don't print the origin's parents
208    NoParents,
209}
210
211thread_local! {
212    static PRINT_FLAGS: Cell<BitFlags<PrintFlag>> = Cell::new(PrintFlag::ReplacePrims | PrintFlag::NoSource);
213}
214
215/// global pool of channel watch batches
216pub static CBATCH_POOL: LazyLock<Pool<Vec<(BindId, Box<dyn CustomBuiltinType>)>>> =
217    LazyLock::new(|| Pool::new(10000, 1000));
218
219/// For the duration of the closure F change the way type variables
220/// are formatted (on this thread only) according to the specified
221/// flags.
222pub fn format_with_flags<G: Into<BitFlags<PrintFlag>>, R, F: FnOnce() -> R>(
223    flags: G,
224    f: F,
225) -> R {
226    let prev = PRINT_FLAGS.replace(flags.into());
227    let res = f();
228    PRINT_FLAGS.set(prev);
229    res
230}
231
232/// Event represents all the things that happened simultaneously in a
233/// given execution cycle. Event may contain only one update for each
234/// variable and netidx subscription in a given cycle, if more updates
235/// happen simultaneously they must be queued and deferred to later
236/// cycles.
237#[derive(Debug)]
238pub struct Event<E: UserEvent> {
239    pub init: bool,
240    pub variables: FxHashMap<BindId, Value>,
241    pub netidx: FxHashMap<SubId, subscriber::Event>,
242    pub writes: FxHashMap<Id, WriteRequest>,
243    pub rpc_calls: FxHashMap<BindId, RpcCall>,
244    pub custom: FxHashMap<BindId, Box<dyn CustomBuiltinType>>,
245    pub user: E,
246}
247
248impl<E: UserEvent> Event<E> {
249    pub fn new(user: E) -> Self {
250        Event {
251            init: false,
252            variables: HashMap::default(),
253            netidx: HashMap::default(),
254            writes: HashMap::default(),
255            rpc_calls: HashMap::default(),
256            custom: HashMap::default(),
257            user,
258        }
259    }
260
261    pub fn clear(&mut self) {
262        let Self { init, variables, netidx, rpc_calls, writes, custom, user } = self;
263        *init = false;
264        variables.clear();
265        netidx.clear();
266        rpc_calls.clear();
267        custom.clear();
268        writes.clear();
269        user.clear();
270    }
271}
272
273#[derive(Debug, Clone, Default)]
274pub struct Refs {
275    refed: LPooled<FxHashSet<BindId>>,
276    bound: LPooled<FxHashSet<BindId>>,
277}
278
279impl Refs {
280    pub fn clear(&mut self) {
281        self.refed.clear();
282        self.bound.clear();
283    }
284
285    pub fn with_external_refs(&self, mut f: impl FnMut(BindId)) {
286        for id in &*self.refed {
287            if !self.bound.contains(id) {
288                f(*id);
289            }
290        }
291    }
292}
293
294pub type Node<R, E> = Box<dyn Update<R, E>>;
295
296pub type BuiltInInitFn<R, E> = sync::Arc<
297    dyn for<'a, 'b, 'c> Fn(
298            &'a mut ExecCtx<R, E>,
299            &'a FnType,
300            &'b Scope,
301            &'c [Node<R, E>],
302            ExprId,
303        ) -> Result<Box<dyn Apply<R, E>>>
304        + Send
305        + Sync
306        + 'static,
307>;
308
309pub type InitFn<R, E> = sync::Arc<
310    dyn for<'a, 'b, 'c> Fn(
311            &'a Scope,
312            &'b mut ExecCtx<R, E>,
313            &'c mut [Node<R, E>],
314            ExprId,
315            bool,
316        ) -> Result<Box<dyn Apply<R, E>>>
317        + Send
318        + Sync
319        + 'static,
320>;
321
322/// Apply is a kind of node that represents a function application. It
323/// does not hold ownership of it's arguments, instead those are held
324/// by a CallSite node. This allows us to change the function called
325/// at runtime without recompiling the arguments.
326pub trait Apply<R: Rt, E: UserEvent>: Debug + Send + Sync + Any {
327    fn update(
328        &mut self,
329        ctx: &mut ExecCtx<R, E>,
330        from: &mut [Node<R, E>],
331        event: &mut Event<E>,
332    ) -> Option<Value>;
333
334    /// delete any internally generated nodes, only needed for
335    /// builtins that dynamically generate code at runtime
336    fn delete(&mut self, _ctx: &mut ExecCtx<R, E>) {
337        ()
338    }
339
340    /// apply custom typechecking to the lambda, only needed for
341    /// builtins that take lambdas as arguments
342    fn typecheck(
343        &mut self,
344        _ctx: &mut ExecCtx<R, E>,
345        _from: &mut [Node<R, E>],
346    ) -> Result<()> {
347        Ok(())
348    }
349
350    /// return the lambdas type, builtins do not need to implement
351    /// this, it is implemented by the BuiltIn wrapper
352    fn typ(&self) -> Arc<FnType> {
353        static EMPTY: LazyLock<Arc<FnType>> = LazyLock::new(|| {
354            Arc::new(FnType {
355                args: Arc::from_iter([]),
356                constraints: Arc::new(RwLock::new(LPooled::take())),
357                rtype: Type::Bottom,
358                throws: Type::Bottom,
359                vargs: None,
360            })
361        });
362        Arc::clone(&*EMPTY)
363    }
364
365    /// Populate the Refs structure with all the ids bound and refed by this
366    /// node. It is only necessary for builtins to implement this if they create
367    /// nodes, such as call sites.
368    fn refs<'a>(&self, _refs: &mut Refs) {}
369
370    /// put the node to sleep, used in conditions like select for branches that
371    /// are not selected. Any cached values should be cleared on sleep.
372    fn sleep(&mut self, _ctx: &mut ExecCtx<R, E>);
373}
374
375/// Update represents a regular graph node, as opposed to a function
376/// application represented by Apply. Regular graph nodes are used for
377/// every built in node except for builtin functions.
378pub trait Update<R: Rt, E: UserEvent>: Debug + Send + Sync + Any + 'static {
379    /// update the node with the specified event and return any output
380    /// it might generate
381    fn update(&mut self, ctx: &mut ExecCtx<R, E>, event: &mut Event<E>) -> Option<Value>;
382
383    /// delete the node and it's children from the specified context
384    fn delete(&mut self, ctx: &mut ExecCtx<R, E>);
385
386    /// type check the node and it's children
387    fn typecheck(&mut self, ctx: &mut ExecCtx<R, E>) -> Result<()>;
388
389    /// return the node type
390    fn typ(&self) -> &Type;
391
392    /// Populate the Refs structure with all the bind ids either refed or bound
393    /// by the node and it's children
394    fn refs(&self, refs: &mut Refs);
395
396    /// return the original expression used to compile this node
397    fn spec(&self) -> &Expr;
398
399    /// put the node to sleep, called on unselected branches
400    fn sleep(&mut self, ctx: &mut ExecCtx<R, E>);
401}
402
403pub trait BuiltIn<R: Rt, E: UserEvent> {
404    const NAME: &str;
405    const TYP: LazyLock<FnType>;
406
407    fn init(ctx: &mut ExecCtx<R, E>) -> BuiltInInitFn<R, E>;
408}
409
410pub trait Abortable {
411    fn abort(&self);
412}
413
414impl Abortable for task::AbortHandle {
415    fn abort(&self) {
416        task::AbortHandle::abort(self)
417    }
418}
419
420pub trait Rt: Debug + 'static {
421    type AbortHandle: Abortable;
422
423    fn clear(&mut self);
424
425    /// Subscribe to the specified netidx path
426    ///
427    /// When the subscription updates you are expected to deliver
428    /// Netidx events to the expression specified by ref_by.
429    fn subscribe(&mut self, flags: UpdatesFlags, path: Path, ref_by: ExprId) -> Dval;
430
431    /// Called when a subscription is no longer needed
432    fn unsubscribe(&mut self, path: Path, dv: Dval, ref_by: ExprId);
433
434    /// List the netidx path, return Value::Null if the path did not
435    /// change. When the path did update you should send the output
436    /// back as a properly formatted struct with two fields, rows and
437    /// columns both containing string arrays.
438    fn list(&mut self, id: BindId, path: Path);
439
440    /// List the table at path, return Value::Null if the path did not
441    /// change
442    fn list_table(&mut self, id: BindId, path: Path);
443
444    /// list or table will no longer be called on this BindId, and
445    /// related resources can be cleaned up.
446    fn stop_list(&mut self, id: BindId);
447
448    /// Publish the specified value, returning it's Id, which must be
449    /// used to update the value and unpublish it. If the path is
450    /// already published, return an error.
451    fn publish(&mut self, path: Path, value: Value, ref_by: ExprId) -> Result<Val>;
452
453    /// Update the specified value
454    fn update(&mut self, id: &Val, value: Value);
455
456    /// Stop publishing the specified id
457    fn unpublish(&mut self, id: Val, ref_by: ExprId);
458
459    /// This will be called by the compiler whenever a bound variable
460    /// is referenced. The ref_by is the toplevel expression that
461    /// contains the variable reference. When a variable event
462    /// happens, you should update all the toplevel expressions that
463    /// ref that variable.
464    ///
465    /// ref_var will also be called when a bound lambda expression is
466    /// referenced, in that case the ref_by id will be the toplevel
467    /// expression containing the call site.
468    fn ref_var(&mut self, id: BindId, ref_by: ExprId);
469    fn unref_var(&mut self, id: BindId, ref_by: ExprId);
470
471    /// Called by the ExecCtx when set_var is called on it.
472    ///
473    /// All expressions that ref the id should be updated when this happens. The
474    /// runtime must deliver all set_vars in a single event except that set_vars
475    /// for the same variable in the same cycle must be queued and deferred to
476    /// the next cycle.
477    ///
478    /// The runtime MUST NOT change event while a cycle is in
479    /// progress. set_var must be queued until the cycle ends and then
480    /// presented as a new batch.
481    fn set_var(&mut self, id: BindId, value: Value);
482
483    /// Notify the RT that a top level variable has been set internally
484    ///
485    /// This is called when the compiler has determined that it's safe to set a
486    /// variable without waiting a cycle. When the updated variable is a
487    /// toplevel node this method is called to notify the runtime that needs to
488    /// update any dependent toplevel nodes.
489    fn notify_set(&mut self, id: BindId);
490
491    /// This must return results from the same path in the call order.
492    ///
493    /// when the rpc returns you are expected to deliver a Variable
494    /// event with the specified id to the expression specified by
495    /// ref_by.
496    fn call_rpc(&mut self, name: Path, args: Vec<(ArcStr, Value)>, id: BindId);
497
498    /// Publish an rpc at the specified path with the specified
499    /// procedure level doc and arg spec.
500    ///
501    /// When the RPC is called the rpc table in event will be
502    /// populated under the specified bind id.
503    ///
504    /// If the procedure is already published an error will be
505    /// returned
506    fn publish_rpc(
507        &mut self,
508        name: Path,
509        doc: Value,
510        spec: Vec<ArgSpec>,
511        id: BindId,
512    ) -> Result<()>;
513
514    /// unpublish the rpc identified by the bind id.
515    fn unpublish_rpc(&mut self, name: Path);
516
517    /// arrange to have a Timer event delivered after timeout. When
518    /// the timer expires you are expected to deliver a Variable event
519    /// for the id, containing the current time.
520    fn set_timer(&mut self, id: BindId, timeout: Duration);
521
522    /// Spawn a task
523    ///
524    /// When the task completes it's output must be delivered as a
525    /// custom event using the returned `BindId`
526    ///
527    /// Calling `abort` must guarantee that if it is called before the
528    /// task completes then no update will be delivered.
529    fn spawn<F: Future<Output = (BindId, Box<dyn CustomBuiltinType>)> + Send + 'static>(
530        &mut self,
531        f: F,
532    ) -> Self::AbortHandle;
533
534    /// Spawn a task
535    ///
536    /// When the task completes it's output must be delivered as a
537    /// variable event using the returned `BindId`
538    ///
539    /// Calling `abort` must guarantee that if it is called before the
540    /// task completes then no update will be delivered.
541    fn spawn_var<F: Future<Output = (BindId, Value)> + Send + 'static>(
542        &mut self,
543        f: F,
544    ) -> Self::AbortHandle;
545
546    /// Ask the runtime to watch a channel
547    ///
548    /// When event batches arrive via the channel the runtime must
549    /// deliver the events as custom updates.
550    fn watch(
551        &mut self,
552        s: mpsc::Receiver<GPooled<Vec<(BindId, Box<dyn CustomBuiltinType>)>>>,
553    );
554
555    /// Ask the runtime to watch a channel
556    ///
557    /// When event batches arrive via the channel the runtime must
558    /// deliver the events variable updates.
559    fn watch_var(&mut self, s: mpsc::Receiver<GPooled<Vec<(BindId, Value)>>>);
560}
561
562#[derive(Default)]
563pub struct LibState(FxHashMap<TypeId, Box<dyn Any + Send + Sync>>);
564
565impl LibState {
566    /// Look up and return the context global library state of type
567    /// `T`.
568    ///
569    /// If none is registered in this context for `T` then create one
570    /// using `T::default`
571    pub fn get_or_default<T>(&mut self) -> &mut T
572    where
573        T: Default + Any + Send + Sync,
574    {
575        self.0
576            .entry(TypeId::of::<T>())
577            .or_insert_with(|| Box::new(T::default()) as Box<dyn Any + Send + Sync>)
578            .downcast_mut::<T>()
579            .unwrap()
580    }
581
582    /// Look up and return the context global library state of type
583    /// `T`.
584    ///
585    /// If none is registered in this context for `T` then create one
586    /// using the provided function.
587    pub fn get_or_else<T, F>(&mut self, f: F) -> &mut T
588    where
589        T: Any + Send + Sync,
590        F: FnOnce() -> T,
591    {
592        self.0
593            .entry(TypeId::of::<T>())
594            .or_insert_with(|| Box::new(f()) as Box<dyn Any + Send + Sync>)
595            .downcast_mut::<T>()
596            .unwrap()
597    }
598
599    pub fn entry<'a, T>(
600        &'a mut self,
601    ) -> hash_map::Entry<'a, TypeId, Box<dyn Any + Send + Sync>>
602    where
603        T: Any + Send + Sync,
604    {
605        self.0.entry(TypeId::of::<T>())
606    }
607
608    /// return true if `T` is present
609    pub fn contains<T>(&self) -> bool
610    where
611        T: Any + Send + Sync,
612    {
613        self.0.contains_key(&TypeId::of::<T>())
614    }
615
616    /// Look up and return a reference to the context global library
617    /// state of type `T`.
618    ///
619    /// If none is registered in this context for `T` return `None`
620    pub fn get<T>(&mut self) -> Option<&T>
621    where
622        T: Any + Send + Sync,
623    {
624        self.0.get(&TypeId::of::<T>()).map(|t| t.downcast_ref::<T>().unwrap())
625    }
626
627    /// Look up and return a mutable reference to the context global
628    /// library state of type `T`.
629    ///
630    /// If none is registered return `None`
631    pub fn get_mut<T>(&mut self) -> Option<&mut T>
632    where
633        T: Any + Send + Sync,
634    {
635        self.0.get_mut(&TypeId::of::<T>()).map(|t| t.downcast_mut::<T>().unwrap())
636    }
637
638    /// Set the context global library state of type `T`
639    ///
640    /// Any existing state will be returned
641    pub fn set<T>(&mut self, t: T) -> Option<Box<T>>
642    where
643        T: Any + Send + Sync,
644    {
645        self.0
646            .insert(TypeId::of::<T>(), Box::new(t) as Box<dyn Any + Send + Sync>)
647            .map(|t| t.downcast::<T>().unwrap())
648    }
649
650    /// Remove and refurn the context global state library state of type `T`
651    pub fn remove<T>(&mut self) -> Option<Box<T>>
652    where
653        T: Any + Send + Sync,
654    {
655        self.0.remove(&TypeId::of::<T>()).map(|t| t.downcast::<T>().unwrap())
656    }
657}
658
659pub struct ExecCtx<R: Rt, E: UserEvent> {
660    builtins: FxHashMap<&'static str, (FnType, BuiltInInitFn<R, E>)>,
661    builtins_allowed: bool,
662    tags: FxHashSet<ArcStr>,
663    /// context global library state for built-in functions
664    pub libstate: LibState,
665    /// the language environment, typdefs, binds, lambdas, etc
666    pub env: Env<R, E>,
667    /// the last value of every bound variable
668    pub cached: FxHashMap<BindId, Value>,
669    /// the runtime
670    pub rt: R,
671}
672
673impl<R: Rt, E: UserEvent> ExecCtx<R, E> {
674    pub fn clear(&mut self) {
675        self.env.clear();
676        self.rt.clear();
677    }
678
679    /// Build a new execution context.
680    ///
681    /// This is a very low level interface that you can use to build a
682    /// custom runtime with deep integration to your code. It is very
683    /// difficult to use, and if you don't implement everything
684    /// correctly the semantics of the language can be wrong.
685    ///
686    /// Most likely you want to use the `rt` module instead.
687    pub fn new(user: R) -> Self {
688        Self {
689            env: Env::new(),
690            builtins: FxHashMap::default(),
691            builtins_allowed: true,
692            libstate: LibState::default(),
693            tags: FxHashSet::default(),
694            cached: HashMap::default(),
695            rt: user,
696        }
697    }
698
699    pub fn register_builtin<T: BuiltIn<R, E>>(&mut self) -> Result<()> {
700        let f = T::init(self);
701        match self.builtins.entry(T::NAME) {
702            Entry::Vacant(e) => {
703                e.insert((T::TYP.clone(), f));
704            }
705            Entry::Occupied(_) => bail!("builtin {} is already registered", T::NAME),
706        }
707        Ok(())
708    }
709
710    /// Built in functions should call this when variables are set
711    /// unless they are sure the variable does not need to be
712    /// cached. This will also call the user ctx set_var.
713    pub fn set_var(&mut self, id: BindId, v: Value) {
714        self.cached.insert(id, v.clone());
715        self.rt.set_var(id, v)
716    }
717
718    fn tag(&mut self, s: &ArcStr) -> ArcStr {
719        match self.tags.get(s) {
720            Some(s) => s.clone(),
721            None => {
722                self.tags.insert(s.clone());
723                s.clone()
724            }
725        }
726    }
727
728    /// Restore the lexical environment to the snapshot `env` for the
729    /// duration of `f` restoring it to it's original value
730    /// afterwords. `by_id` and `lambdas` defined by the closure will
731    /// be retained.
732    pub fn with_restored<T, F: FnOnce(&mut Self) -> T>(
733        &mut self,
734        env: Env<R, E>,
735        f: F,
736    ) -> T {
737        let snap = self.env.restore_lexical_env(env);
738        let orig = mem::replace(&mut self.env, snap);
739        let r = f(self);
740        self.env = self.env.restore_lexical_env(orig);
741        r
742    }
743}
744
745#[derive(Debug, Clone)]
746pub struct Scope {
747    pub lexical: ModPath,
748    pub dynamic: ModPath,
749}
750
751impl Scope {
752    pub fn append<S: AsRef<str> + ?Sized>(&self, s: &S) -> Self {
753        Self {
754            lexical: ModPath(self.lexical.append(s)),
755            dynamic: ModPath(self.dynamic.append(s)),
756        }
757    }
758
759    pub fn root() -> Self {
760        Self { lexical: ModPath::root(), dynamic: ModPath::root() }
761    }
762}
763
764/// compile the expression into a node graph in the specified context
765/// and scope, return the root node or an error if compilation failed.
766pub fn compile<R: Rt, E: UserEvent>(
767    ctx: &mut ExecCtx<R, E>,
768    flags: BitFlags<CFlag>,
769    scope: &Scope,
770    spec: Expr,
771) -> Result<Node<R, E>> {
772    let top_id = spec.id;
773    let env = ctx.env.clone();
774    let st = Instant::now();
775    let mut node = match compiler::compile(ctx, flags, spec, scope, top_id) {
776        Ok(n) => n,
777        Err(e) => {
778            ctx.env = env;
779            return Err(e);
780        }
781    };
782    info!("compile time {:?}", st.elapsed());
783    let st = Instant::now();
784    if let Err(e) = node.typecheck(ctx) {
785        ctx.env = env;
786        return Err(e);
787    }
788    info!("typecheck time {:?}", st.elapsed());
789    Ok(node)
790}