use crate::{Cell, Executor, SessionState, Store};
use anyhow::{Context, Result};
use std::collections::HashMap;
pub struct Session {
executor: Box<dyn Executor>,
store: Box<dyn Store>,
defs_text: String,
snapshots: HashMap<usize, Vec<Cell>>,
line_no: usize,
budget: Option<quarb::plan::Budget>,
}
impl Session {
pub fn new(executor: Box<dyn Executor>, store: Box<dyn Store>) -> Session {
let state = store.load().unwrap_or_default();
let line_no = state.line_no.max(1);
Session {
executor,
store,
defs_text: state.defs_text,
snapshots: HashMap::new(),
line_no,
budget: None,
}
}
pub fn set_budget(&mut self, budget: Option<quarb::plan::Budget>) {
self.budget = budget;
}
pub fn budget(&self) -> Option<&quarb::plan::Budget> {
self.budget.as_ref()
}
pub fn plan(&self, line: &str) -> Result<quarb::plan::Plan> {
self.executor
.plan(&self.combined(line), self.budget.as_ref())
}
pub fn plan_text(&self, line: &str) -> Result<String> {
Ok(self.plan(line)?.to_kaiv(line))
}
fn within_budget(&self, query: &str) -> Result<()> {
if let Some(b) = &self.budget {
let plan = self.executor.plan(query, Some(b))?;
if let Some(why) = b.exceeded_by(&plan) {
return Err(quarb::QuarbError::refused(why).into());
}
}
Ok(())
}
pub fn set_executor(&mut self, executor: Box<dyn Executor>) {
self.executor = executor;
}
pub fn seed_defs(&mut self, text: &str) -> Result<()> {
quarb::parse_defs(text).context("parsing --defs")?;
let stripped = quarb::strip_defs_comments(text);
if !stripped.trim().is_empty() && self.defs_text.contains(stripped.trim()) {
return Ok(());
}
let candidate = format!("{}{}\n", self.defs_text, stripped);
quarb::parse_defs(&candidate).context("parsing --defs")?;
self.defs_text = candidate;
self.persist();
Ok(())
}
pub fn closes_with_session_push(&self, line: &str) -> bool {
quarb::closes_with_session_push(&self.combined(line))
}
pub fn add_def(&mut self, line: &str) -> Result<()> {
let candidate = format!("{}{}\n", self.defs_text, line);
quarb::parse_defs(&candidate).context("parsing definition")?;
self.defs_text = candidate;
self.snapshots.insert(self.line_no, Vec::new());
self.line_no += 1;
self.persist();
Ok(())
}
fn combined(&self, line: &str) -> String {
if self.defs_text.is_empty() {
line.to_string()
} else {
format!("{}\n{line}", self.defs_text)
}
}
fn in_line<T>(&self, result: Result<T>) -> Result<T> {
if self.defs_text.is_empty() {
return result;
}
let before = self.defs_text.chars().count() + 1;
result.map_err(|e| match e.downcast::<quarb::QuarbError>() {
Ok(q) => q.in_text_after(before).into(),
Err(e) => e,
})
}
pub fn eval(&self, line: &str) -> Result<Vec<Cell>> {
let q = self.combined(line);
self.within_budget(&q)?;
self.in_line(self.executor.run(&q))
}
pub fn eval_table(&self, line: &str) -> Result<(Vec<Cell>, Option<String>)> {
let q = self.combined(line);
self.within_budget(&q)?;
self.in_line(if quarb::closes_with_table(&q) {
self.executor.run_table(&q)
} else {
self.executor.run(&q).map(|cells| (cells, None))
})
}
pub fn eval_rich(&self, line: &str) -> Result<(Vec<Cell>, Option<String>)> {
let q = self.combined(line);
self.within_budget(&q)?;
self.in_line(self.executor.run_rich(&q))
}
pub fn rich_of(&self, cells: &[Cell]) -> Option<String> {
let mode = self.pretty_mode();
let values: Vec<quarb::Value> = cells
.iter()
.filter_map(|c| match c {
Cell::Value(v) => Some(v.clone()),
Cell::Node(_) => None,
})
.collect();
quarb::rich::html_of(&values, None, None, mode)
}
pub fn pretty_mode(&self) -> quarb::PrettyMode {
self.session_memory()
.map(|m| m.borrow().pretty)
.unwrap_or(quarb::PrettyMode::Off)
}
pub fn set_pretty(&self, mode: quarb::PrettyMode) {
if let Some(m) = self.session_memory() {
m.borrow_mut().pretty = mode;
}
}
pub fn export_rich(&self, line: &str) -> Result<String> {
let (cells, html) = self.eval_rich(line)?;
let diagnostics = self.diagnostics();
let level = self.diagnostics_level();
Ok(match html {
Some(h) => quarb::rich::document(&h, &diagnostics, level),
None => {
let text: Vec<String> = cells.iter().map(|c| c.display()).collect();
quarb::rich::document(
&format!(
"<pre class=\"quarb-text\">{}</pre>",
quarb::table::escape(&text.join("\n"))
),
&diagnostics,
level,
)
}
})
}
pub fn refs(&self) -> Vec<String> {
self.executor.refs()
}
pub fn diagnostics(&self) -> Vec<quarb::Diagnostic> {
self.executor.diagnostics()
}
pub fn diagnostics_level(&self) -> quarb::Severity {
self.session_memory()
.map(|m| m.borrow().diagnostics)
.unwrap_or(quarb::Severity::Warning)
}
pub fn session_memory(&self) -> Option<quarb::SessionMemory> {
self.executor.session_memory()
}
pub fn eval_fresh(&self, line: &str) -> Result<Vec<Cell>> {
let q = self.combined(line);
self.within_budget(&q)?;
self.in_line(self.executor.run_fresh(&q))
}
pub fn export(&self, line: &str, kind: &str) -> Result<String> {
let line = line.trim();
if line.is_empty() {
return self.executor.export("", kind);
}
self.executor.export(&self.combined(line), kind)
}
pub fn commit(&mut self, line: &str, snapshot: Vec<Cell>) -> bool {
self.snapshots.insert(self.line_no, snapshot);
let candidate = format!("{}def &{}: {} ;\n", self.defs_text, self.line_no, line);
let referenceable = quarb::parse_defs(&candidate).is_ok();
if referenceable {
self.defs_text = candidate;
}
self.line_no += 1;
self.persist();
referenceable
}
pub fn frozen_head_query(&self, n: usize, tail: &str) -> std::result::Result<String, String> {
let cells = self
.frozen(n)
.ok_or_else(|| format!("&{n}# has no captured result (line {n} hasn't run)"))?;
let lits: Vec<String> = cells
.iter()
.map(|c| match c {
Cell::Value(v) => v.to_quarb(),
Cell::Node(s) => quarb::Value::Str(s.clone()).to_quarb(),
})
.collect();
let head = match lits.as_slice() {
[one] => one.clone(),
many => format!("@({}) | ...", many.join("; ")),
};
Ok(format!("= {head} {tail}"))
}
pub fn frozen(&self, n: usize) -> Option<&Vec<Cell>> {
self.snapshots.get(&n)
}
pub fn record_frozen(&mut self, snapshot: Vec<Cell>) {
self.snapshots.insert(self.line_no, snapshot);
self.line_no += 1;
self.persist();
}
fn persist(&self) {
let state = SessionState {
defs_text: self.defs_text.clone(),
line_no: self.line_no,
};
let _ = self.store.save(&state);
}
pub fn complete(&self, text: &str, cursor: usize) -> Vec<quarb::complete::Candidate> {
self.executor.complete(text, cursor)
}
pub fn line_no(&self) -> usize {
self.line_no
}
pub fn history(&self) -> &str {
&self.defs_text
}
pub fn restore(&mut self, defs_text: String, line_no: usize) {
self.defs_text = defs_text;
self.line_no = line_no.max(1);
}
pub fn reset(&mut self) {
self.defs_text.clear();
self.snapshots.clear();
self.line_no = 1;
self.persist();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::MemStore;
struct NullExec;
impl Executor for NullExec {
fn run(&self, _query: &str) -> anyhow::Result<Vec<Cell>> {
Ok(vec![])
}
}
#[test]
fn seed_defs_strips_comments() {
let mut s = Session::new(Box::new(NullExec), Box::new(MemStore));
s.seed_defs("# a library header\ndef &a: /x;\n# and a note\ndef &b: /y;")
.unwrap();
assert!(!s.history().contains('#'), "history: {}", s.history());
assert!(s.history().contains("def &a"));
assert!(s.history().contains("def &b"));
}
}
pub fn history_head(line: &str) -> Option<(usize, char, &str)> {
let rest = line.trim().strip_prefix('&')?;
let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len();
if digits == 0 {
return None;
}
let n: usize = rest[..digits].parse().ok()?;
let rest = &rest[digits..];
let suffix = rest.chars().next().filter(|c| matches!(c, '#' | '!'))?;
let tail = rest[1..].trim_start();
if !(tail.is_empty()
|| tail.starts_with('|')
|| tail.starts_with("@|")
|| tail.starts_with("*__"))
{
return None;
}
Some((n, suffix, tail))
}