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