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>>,
replays: HashMap<usize, usize>,
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(),
replays: 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)?;
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)?;
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, of: usize, snapshot: Vec<Cell>) {
self.replays.insert(self.line_no, of);
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.replays.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 line = line.trim();
let (rest, rounded) = match line.strip_prefix('&') {
Some(rest) => (rest, false),
None => (line.strip_prefix("(=")?, true),
};
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 rest = if rounded {
if suffix == '#' {
return None;
}
rest[1..].strip_prefix(')')?
} else {
&rest[1..]
};
let tail = rest.trim_start();
if !(tail.is_empty()
|| tail.starts_with('|')
|| tail.starts_with("@|")
|| tail.starts_with("*__"))
{
return None;
}
Some((n, suffix, tail))
}
pub fn retired_suffix(n: usize) -> String {
format!("'&{n}#' is retired: the stored result of line {n} is '&{n}='")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reader {
Line,
Cell,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Read {
Manual(std::result::Result<String, String>),
Remount(String),
MountTarget,
Model(String),
Refused(String),
Definitions(String),
Stored(usize),
Query { text: String, fresh: bool },
}
pub fn remount_cell(text: &str) -> Option<String> {
let mut out = String::new();
for stmt in text.split(';') {
let stmt = stmt.trim();
if stmt.is_empty() {
continue;
}
let rest = stmt.strip_prefix("mount")?;
if !rest.starts_with(|c: char| c.is_whitespace() || c == ':') {
return None;
}
let (name, target) = rest.split_once(':')?;
if !target.trim().starts_with('?') {
return None;
}
out.push_str(&format!("mount {}: {};\n", name.trim(), target.trim()));
}
(!out.is_empty()).then_some(out)
}
pub fn embedded_ref(text: &str, suffix: char) -> Option<usize> {
let chars: Vec<char> = text.chars().collect();
let mut quote: Option<char> = None;
let mut i = 0;
while i < chars.len() {
let c = chars[i];
match quote {
Some(q) => {
if c == '\\' {
i += 1;
} else if c == q {
quote = None;
}
}
None if c == '"' || c == '\'' => quote = Some(c),
None if c == '&' => {
let mut j = i + 1;
while chars.get(j).is_some_and(|d| d.is_ascii_digit()) {
j += 1;
}
if j > i + 1 && chars.get(j) == Some(&suffix) {
let before = i == 0 || !chars[i - 1].is_alphanumeric();
let after = !chars.get(j + 1).is_some_and(|d| d.is_alphanumeric());
if before && after {
return chars[i + 1..j].iter().collect::<String>().parse().ok();
}
}
}
None => {}
}
i += 1;
}
None
}
impl Session {
fn names_a_replay(&self, text: &str) -> Option<(usize, usize)> {
if self.replays.is_empty() {
return None;
}
let chars: Vec<char> = text.chars().collect();
let mut quote: Option<char> = None;
let mut i = 0;
while i < chars.len() {
let c = chars[i];
match quote {
Some(q) => {
if c == '\\' {
i += 1;
} else if c == q {
quote = None;
}
}
None if c == '"' || c == '\'' => quote = Some(c),
None if c == '&' || (c == '(' && chars.get(i + 1) == Some(&'=')) => {
let from = if c == '&' { i + 1 } else { i + 2 };
let mut j = from;
while chars.get(j).is_some_and(|d| d.is_ascii_digit()) {
j += 1;
}
let before = i == 0 || !chars[i - 1].is_alphanumeric();
let goes_on = chars
.get(j)
.is_some_and(|d| d.is_alphanumeric() || matches!(d, '=' | '_'));
if j > from
&& before
&& !goes_on
&& let Ok(n) = chars[from..j].iter().collect::<String>().parse::<usize>()
&& let Some(of) = self.replays.get(&n)
{
return Some((n, *of));
}
}
None => {}
}
i += 1;
}
None
}
pub fn read(&self, text: &str, reader: Reader) -> Read {
let text = text.trim();
if let Some(page) = quarb::man::line(text) {
return Read::Manual(page);
}
let first = text.split_whitespace().next().unwrap_or_default();
let defines = text.starts_with("def ")
|| text == "def"
|| text.starts_with("macro ")
|| text == "macro";
let resolved;
let text = match reader {
Reader::Line => {
if let Some(cell) = remount_cell(text) {
return Read::Remount(cell);
}
if text
.strip_prefix("mount")
.is_some_and(|rest| rest.starts_with(|c: char| c.is_whitespace() || c == ':'))
{
return Read::MountTarget;
}
let last = self.line_no().saturating_sub(1);
resolved = match quarb::resolve_previous_line(text, last) {
Ok(resolved) => resolved,
Err(e) => return Read::Refused(e),
};
let text = resolved.as_deref().unwrap_or(text);
if text.starts_with("def ")
|| text == "def"
|| text.starts_with("macro ")
|| text == "macro"
{
return Read::Definitions(text.to_string());
}
text
}
Reader::Cell => {
if let Some(why) = quarb::previous_line_in_a_file(text) {
return Read::Refused(why);
}
let defs_alone =
defines && quarb::parse_defs(&format!("{}{text}", self.defs_text)).is_ok();
if defs_alone {
return Read::Definitions(text.to_string());
}
let re_read = remount_cell(text);
if (quarb_model::STATEMENTS.contains(&first) && !defines) || re_read.is_some() {
return Read::Model(re_read.unwrap_or_else(|| text.to_string()));
}
text
}
};
if let Some(n) = embedded_ref(text, '#') {
return Read::Refused(retired_suffix(n));
}
if let Some((n, of)) = self.names_a_replay(text) {
return Read::Refused(format!(
"'&{n}' is no query: line {n} replayed the stored result of line {of}; \
'&{of}' runs that line's query again, '&{n}=' gives the result line {n} showed"
));
}
match history_head(text) {
Some((n, '=', "")) => Read::Stored(n),
Some((n, '=', tail)) => match self.frozen_head_query(n, tail) {
Ok(headed) => Read::Query {
text: headed,
fresh: false,
},
Err(e) => Read::Refused(e),
},
Some((n, '!', tail)) => Read::Query {
text: format!("&{n} {tail}").trim_end().to_string(),
fresh: true,
},
_ if embedded_ref(text, '=').is_some() => Read::Refused(
"'&N=' recalls a stored result: alone on a line, or at its head before a pipe \
('&N= | count')"
.to_string(),
),
_ => Read::Query {
text: text.to_string(),
fresh: false,
},
}
}
}