graphix_shell/
lib.rs

1use anyhow::{bail, Context, Result};
2use arcstr::{literal, ArcStr};
3use derive_builder::Builder;
4use enumflags2::BitFlags;
5use graphix_compiler::{
6    expr::{ExprId, ModPath, ModuleResolver},
7    format_with_flags,
8    typ::{TVal, Type},
9    CFlag, ExecCtx, PrintFlag,
10};
11use graphix_rt::{CompExp, CouldNotResolve, GXConfig, GXEvent, GXExt, GXHandle, GXRt};
12use graphix_stdlib::Module;
13use input::InputReader;
14use netidx::{
15    path::Path,
16    publisher::{Publisher, Value},
17    subscriber::Subscriber,
18};
19use poolshark::global::GPooled;
20use reedline::Signal;
21use std::{collections::HashMap, path::PathBuf, sync::LazyLock, time::Duration};
22use tokio::{select, sync::mpsc};
23use triomphe::Arc;
24use tui::Tui;
25
26mod completion;
27mod input;
28mod tui;
29
30type Env<X> = graphix_compiler::env::Env<GXRt<X>, <X as GXExt>::UserEvent>;
31
32const TUITYP: LazyLock<Type> = LazyLock::new(|| Type::Ref {
33    scope: ModPath::root(),
34    name: ModPath::from(["tui", "Tui"]),
35    params: Arc::from_iter([]),
36});
37
38enum Output<X: GXExt> {
39    None,
40    Tui(Tui<X>),
41    Text(CompExp<X>),
42}
43
44impl<X: GXExt> Output<X> {
45    fn from_expr(gx: &GXHandle<X>, env: &Env<X>, e: CompExp<X>) -> Self {
46        if let Some(typ) = e.typ.with_deref(|t| t.cloned())
47            && typ != Type::Bottom
48            && typ != Type::Any
49            && TUITYP.contains(env, &typ).unwrap()
50        {
51            Self::Tui(Tui::start(gx, env.clone(), e))
52        } else {
53            Self::Text(e)
54        }
55    }
56
57    async fn clear(&mut self) {
58        match self {
59            Self::None | Self::Text(_) => (),
60            Self::Tui(tui) => tui.stop().await,
61        }
62        *self = Self::None
63    }
64
65    async fn process_update(&mut self, env: &Env<X>, id: ExprId, v: Value) {
66        match self {
67            Self::None => (),
68            Self::Tui(tui) => tui.update(id, v).await,
69            Self::Text(e) => {
70                if e.id == id {
71                    println!("{}", TVal { env: &env, typ: &e.typ, v: &v })
72                }
73            }
74        }
75    }
76}
77
78fn tui_mods() -> ModuleResolver {
79    ModuleResolver::VFS(HashMap::from_iter([
80        (Path::from("/tui"), literal!(include_str!("tui/mod.gx"))),
81        (
82            Path::from("/tui/input_handler"),
83            literal!(include_str!("tui/input_handler.gx")),
84        ),
85        (Path::from("/tui/text"), literal!(include_str!("tui/text.gx"))),
86        (Path::from("/tui/paragraph"), literal!(include_str!("tui/paragraph.gx"))),
87        (Path::from("/tui/block"), literal!(include_str!("tui/block.gx"))),
88        (Path::from("/tui/scrollbar"), literal!(include_str!("tui/scrollbar.gx"))),
89        (Path::from("/tui/layout"), literal!(include_str!("tui/layout.gx"))),
90        (Path::from("/tui/tabs"), literal!(include_str!("tui/tabs.gx"))),
91        (Path::from("/tui/barchart"), literal!(include_str!("tui/barchart.gx"))),
92        (Path::from("/tui/chart"), literal!(include_str!("tui/chart.gx"))),
93        (Path::from("/tui/sparkline"), literal!(include_str!("tui/sparkline.gx"))),
94        (Path::from("/tui/line_gauge"), literal!(include_str!("tui/line_gauge.gx"))),
95        (Path::from("/tui/gauge"), literal!(include_str!("tui/gauge.gx"))),
96        (Path::from("/tui/list"), literal!(include_str!("tui/list.gx"))),
97        (Path::from("/tui/table"), literal!(include_str!("tui/table.gx"))),
98        (Path::from("/tui/calendar"), literal!(include_str!("tui/calendar.gx"))),
99        (Path::from("/tui/canvas"), literal!(include_str!("tui/canvas.gx"))),
100        (Path::from("/tui/browser"), literal!(include_str!("tui/browser.gx"))),
101    ]))
102}
103
104#[derive(Debug, Clone)]
105pub enum Mode {
106    /// Read input line by line from the user and compile/execute it.
107    /// provide completion and print the value of the last expression
108    /// as it executes. Ctrl-C cancel's execution of the last
109    /// expression and Ctrl-D exits the shell.
110    Repl,
111    /// Load compile and execute the specified file. Print the value
112    /// of the last expression in the file to stdout. Ctrl-C exits the
113    /// shell.
114    File(PathBuf),
115    /// Compile and execute the code in the specified string. Besides
116    /// not loading from a file this mode behaves exactly like File.
117    Static(ArcStr),
118}
119
120impl Mode {
121    fn file_mode(&self) -> bool {
122        match self {
123            Self::Repl => false,
124            Self::File(_) | Self::Static(_) => true,
125        }
126    }
127}
128
129#[derive(Builder)]
130#[builder(pattern = "owned")]
131pub struct Shell<X: GXExt> {
132    /// do not run the users init module
133    #[builder(default = "false")]
134    no_init: bool,
135    /// drop subscribers if they don't consume updates after this timeout
136    #[builder(setter(strip_option), default)]
137    publish_timeout: Option<Duration>,
138    /// module resolution from netidx will fail if it can't subscribe
139    /// before this time elapses
140    #[builder(setter(strip_option), default)]
141    resolve_timeout: Option<Duration>,
142    /// define module resolvers to append to the default list
143    #[builder(default)]
144    module_resolvers: Vec<ModuleResolver>,
145    /// enable or disable features of the standard library
146    #[builder(default = "BitFlags::all()")]
147    stdlib_modules: BitFlags<Module>,
148    /// set the shell's mode
149    #[builder(default = "Mode::Repl")]
150    mode: Mode,
151    /// The netidx publisher to use. If you do not wish to use netidx
152    /// you can use netidx::InternalOnly to create an internal netidx
153    /// environment
154    publisher: Publisher,
155    /// The netidx subscriber to use. If you do not wish to use netidx
156    /// you can use netidx::InternalOnly to create an internal netidx
157    /// environment
158    subscriber: Subscriber,
159    /// Provide a closure to register any built-ins you wish to use.
160    ///
161    /// Your closure should register the builtins with the context and return a
162    /// string specifiying any modules you need to load in order to use them.
163    /// For example if you wish to implement a module called m containing
164    /// builtins foo and bar, then you would first implement foo and bar in rust
165    /// and register them with the context. You would add a VFS module resolver
166    /// to the set of resolvers containing prototypes that reference your rust
167    /// builtins. e.g.
168    ///
169    /// ``` ignore
170    /// pub let foo = |x, y| 'foo_builtin;
171    /// pub let bar = |x| 'bar_builtin
172    /// ```
173    ///
174    /// Your VFS resolver would map "/m" -> the above stubs. Your register
175    /// function would then return "mod m\n" to force loading the module at
176    /// startup. Then your user only needs to `use m`
177    #[builder(setter(strip_option), default)]
178    register: Option<Arc<dyn Fn(&mut ExecCtx<GXRt<X>, X::UserEvent>) -> ArcStr>>,
179    /// Enable compiler flags, these will be ORed with the default set of flags
180    /// for the mode.
181    #[builder(default)]
182    enable_flags: BitFlags<CFlag>,
183    /// Disable compiler flags, these will be subtracted from the final set.
184    /// (default_flags | enable_flags) - disable_flags
185    #[builder(default)]
186    disable_flags: BitFlags<CFlag>,
187}
188
189impl<X: GXExt> Shell<X> {
190    async fn init(
191        &mut self,
192        sub: mpsc::Sender<GPooled<Vec<GXEvent<X>>>>,
193    ) -> Result<GXHandle<X>> {
194        let publisher = self.publisher.clone();
195        let subscriber = self.subscriber.clone();
196        let mut ctx = ExecCtx::new(GXRt::<X>::new(publisher, subscriber));
197        let (root, mods) = graphix_stdlib::register(&mut ctx, self.stdlib_modules)?;
198        let usermods = self.register.as_mut().map(|f| f(&mut ctx));
199        let root = match usermods {
200            Some(m) => ArcStr::from(format!("{root};\nmod tui;\n{m}")),
201            None => ArcStr::from(format!("{root};\nmod tui")),
202        };
203        let mut flags = match self.mode {
204            Mode::File(_) | Mode::Static(_) => CFlag::WarnUnhandled | CFlag::WarnUnused,
205            Mode::Repl => BitFlags::empty(),
206        };
207        flags.insert(self.enable_flags);
208        flags.remove(self.disable_flags);
209        let mut mods = vec![mods, tui_mods()];
210        for res in self.module_resolvers.drain(..) {
211            mods.push(res);
212        }
213        let mut gx = GXConfig::builder(ctx, sub);
214        gx = gx.flags(flags);
215        if let Some(s) = self.publish_timeout {
216            gx = gx.publish_timeout(s);
217        }
218        if let Some(s) = self.resolve_timeout {
219            gx = gx.resolve_timeout(s);
220        }
221        Ok(gx
222            .root(root)
223            .resolvers(mods)
224            .build()
225            .context("building rt config")?
226            .start()
227            .await
228            .context("loading initial modules")?)
229    }
230
231    async fn load_env(
232        &mut self,
233        gx: &GXHandle<X>,
234        newenv: &mut Option<Env<X>>,
235        output: &mut Output<X>,
236        exprs: &mut Vec<CompExp<X>>,
237    ) -> Result<Env<X>> {
238        let env;
239        macro_rules! file_mode {
240            ($r:expr) => {{
241                exprs.extend($r.exprs);
242                env = gx.get_env().await?;
243                if let Some(e) = exprs.pop() {
244                    *output = Output::from_expr(&gx, &env, e);
245                }
246                *newenv = None
247            }};
248        }
249        match &self.mode {
250            Mode::File(file) => {
251                let r = gx.load(file.clone()).await?;
252                file_mode!(r)
253            }
254            Mode::Static(s) => {
255                let r = gx.compile(s.clone()).await?;
256                file_mode!(r)
257            }
258            Mode::Repl if !self.no_init => match gx.compile("mod init".into()).await {
259                Ok(res) => {
260                    env = res.env;
261                    exprs.extend(res.exprs);
262                    *newenv = Some(env.clone())
263                }
264                Err(e) if e.is::<CouldNotResolve>() => {
265                    env = gx.get_env().await?;
266                    *newenv = Some(env.clone())
267                }
268                Err(e) => {
269                    eprintln!("error in init module: {e:?}");
270                    env = gx.get_env().await?;
271                    *newenv = Some(env.clone())
272                }
273            },
274            Mode::Repl => {
275                env = gx.get_env().await?;
276                *newenv = Some(env.clone());
277            }
278        }
279        Ok(env)
280    }
281
282    pub async fn run(mut self) -> Result<()> {
283        let (tx, mut from_gx) = mpsc::channel(100);
284        let gx = self.init(tx).await?;
285        let script = self.mode.file_mode();
286        let mut input = InputReader::new();
287        let mut output = Output::None;
288        let mut newenv = None;
289        let mut exprs = vec![];
290        let mut env = self.load_env(&gx, &mut newenv, &mut output, &mut exprs).await?;
291        if !script {
292            println!("Welcome to the graphix shell");
293            println!("Press ctrl-c to cancel, ctrl-d to exit, and tab for help")
294        }
295        loop {
296            select! {
297                batch = from_gx.recv() => match batch {
298                    None => bail!("graphix runtime is dead"),
299                    Some(mut batch) => {
300                        for e in batch.drain(..) {
301                            match e {
302                                GXEvent::Updated(id, v) => {
303                                    output.process_update(&env, id, v).await
304                                },
305                                GXEvent::Env(e) => {
306                                    env = e;
307                                    newenv = Some(env.clone());
308                                }
309                            }
310                        }
311                    }
312                },
313                input = input.read_line(&mut output, &mut newenv) => {
314                    match input {
315                        Err(e) => eprintln!("error reading line {e:?}"),
316                        Ok(Signal::CtrlC) if script => break Ok(()),
317                        Ok(Signal::CtrlC) => output.clear().await,
318                        Ok(Signal::CtrlD) => break Ok(()),
319                        Ok(Signal::Success(line)) => {
320                            match gx.compile(ArcStr::from(line)).await {
321                                Err(e) => eprintln!("error: {e:?}"),
322                                Ok(res) => {
323                                    env = res.env;
324                                    newenv = Some(env.clone());
325                                    exprs.extend(res.exprs);
326                                    if exprs.last().map(|e| e.output).unwrap_or(false) {
327                                        let e = exprs.pop().unwrap();
328                                        let typ = e.typ
329                                            .with_deref(|t| t.cloned())
330                                            .unwrap_or_else(|| e.typ.clone());
331                                        format_with_flags(
332                                            PrintFlag::DerefTVars | PrintFlag::ReplacePrims,
333                                            || println!("-: {}", typ)
334                                        );
335                                        output = Output::from_expr(&gx, &env, e);
336                                    } else {
337                                        output.clear().await
338                                    }
339                                }
340                            }
341                        }
342                    }
343                },
344            }
345        }
346    }
347}