use std::io::{BufRead, Write};
use qxide::Backend;
use super::diag::{Code, Diagnostic, SourceMap, Span};
use super::{ast, front, interp, lexer, msg, parser, render_output, sim_error, Failure};
const NAME: &str = "<repl>";
#[derive(Clone)]
struct Entry {
text: String,
line: usize,
typed: Option<Typed>,
}
#[derive(Clone)]
struct Typed {
input: String,
prefix: usize,
code: usize,
suffix: usize,
}
struct Region {
start: usize,
len: usize,
typed: Typed,
}
pub struct Session {
fns: Vec<Entry>,
stmts: Vec<Entry>,
next_line: usize,
seed: u64,
shown: String,
}
pub enum Reply {
Out(String),
Err(String),
Quit,
}
enum New<'a> {
Nothing,
Fn(&'a Entry),
Stmt(&'a Entry),
}
struct Program {
src: String,
regions: Vec<Region>,
labels: Vec<usize>,
input_at: usize,
main_close: Span,
}
impl Program {
fn assemble(fns: &[Entry], stmts: &[Entry], new: New) -> Program {
let mut p = Program {
src: String::new(),
regions: Vec::new(),
labels: Vec::new(),
input_at: 0,
main_close: Span::default(),
};
for f in fns {
p.push_entry(f);
p.push("", 0);
}
if let New::Fn(f) = new {
p.input_at = p.src.len();
p.push_entry(f);
p.push("", 0);
}
p.push("void main() {", 0);
for s in stmts {
p.push_entry(s);
}
if let New::Stmt(s) = new {
p.input_at = p.src.len();
p.push_entry(s);
}
p.main_close = Span::new(p.src.len(), p.src.len() + 1);
p.src.push('}');
p.labels.push(0);
p
}
fn push_entry(&mut self, e: &Entry) {
if let Some(typed) = &e.typed {
self.regions.push(Region {
start: self.src.len(),
len: e.text.len(),
typed: typed.clone(),
});
}
self.push(&e.text, e.line);
}
fn display(&self) -> (String, impl Fn(usize) -> usize + '_) {
let mut shown = String::with_capacity(self.src.len());
let mut at = 0;
for r in &self.regions {
shown.push_str(&self.src[at..r.start]);
shown.push_str(&r.typed.input);
at = r.start + r.len;
}
shown.push_str(&self.src[at..]);
let map = move |off: usize| {
let mut delta: isize = 0;
for r in &self.regions {
let t = &r.typed;
if off < r.start {
break;
}
if off <= r.start + r.len {
let rel = off - r.start;
let typed_rel = if rel <= t.prefix {
0
} else if rel - t.prefix <= t.code {
rel - t.prefix
} else {
(rel - t.prefix - t.suffix).max(t.code)
};
let typed_rel = typed_rel.min(t.input.len());
return (r.start as isize + delta) as usize + typed_rel;
}
delta += t.input.len() as isize - r.len as isize;
}
(off as isize + delta) as usize
};
(shown, map)
}
fn push(&mut self, text: &str, first_line: usize) {
for (i, line) in text.split('\n').enumerate() {
self.src.push_str(line);
self.src.push('\n');
self.labels
.push(if first_line == 0 { 0 } else { first_line + i });
}
}
fn render(&self, errors: &[Diagnostic]) -> Failure {
let (shown, at) = self.display();
let span = |s: Span| Span::new(at(s.start), at(s.end));
let map = SourceMap::new(NAME, &shown).with_labels(self.labels.clone());
let text: Vec<String> = errors
.iter()
.map(|d| {
let mut d = d.clone();
d.span = span(d.span);
for n in &mut d.notes {
n.span = n.span.map(span);
}
map.render(&d)
})
.collect();
Failure(text.join("\n"))
}
fn is_open_leak(&self, d: &Diagnostic) -> bool {
d.code == Code::NeverConsumed
&& d.notes.first().and_then(|n| n.span) == Some(self.main_close)
}
}
pub fn open_brackets(text: &str) -> i64 {
scan(text).depth
}
struct Scan {
depth: i64,
min_depth: i64,
trailing_comment: Option<usize>,
}
fn scan(text: &str) -> Scan {
let mut s = Scan {
depth: 0,
min_depth: 0,
trailing_comment: None,
};
let mut chars = text.char_indices().peekable();
while let Some((i, c)) = chars.next() {
match c {
'"' => {
while let Some((_, c)) = chars.next() {
match c {
'\\' => {
chars.next();
}
'"' | '\n' => break,
_ => {}
}
}
}
'/' if chars.peek().map(|&(_, c)| c) == Some('/') => {
s.trailing_comment = Some(i);
for (_, c) in chars.by_ref() {
if c == '\n' {
s.trailing_comment = None;
break;
}
}
}
'{' | '(' | '[' => s.depth += 1,
'}' | ')' | ']' => {
s.depth -= 1;
s.min_depth = s.min_depth.min(s.depth);
}
_ => {}
}
}
s
}
fn has_return(stmts: &[ast::Stmt], from: usize) -> bool {
stmts.iter().any(|s| match s {
ast::Stmt::Return { span, .. } => span.start >= from,
ast::Stmt::If(i) => if_has_return(i, from),
ast::Stmt::For { body, .. } => has_return(&body.stmts, from),
_ => false,
})
}
fn if_has_return(i: &ast::IfStmt, from: usize) -> bool {
has_return(&i.then.stmts, from)
|| match &i.els {
Some(ast::Else::Block(b)) => has_return(&b.stmts, from),
Some(ast::Else::If(inner)) => if_has_return(inner, from),
None => false,
}
}
fn is_fn_decl(input: &str) -> bool {
lexer::lex(input)
.ok()
.and_then(|toks| parser::parse(toks).ok())
.is_some_and(|p| !p.fns.is_empty())
}
impl Session {
pub fn new(seed: u64) -> Self {
Self {
fns: Vec::new(),
stmts: Vec::new(),
next_line: 1,
seed,
shown: String::new(),
}
}
pub fn input(&mut self, input: &str) -> Reply {
let input = input.trim_start_matches('\u{feff}').trim();
if input.is_empty() {
return Reply::Out(String::new());
}
if let Some(cmd) = input.strip_prefix(':') {
return self.command(cmd.trim());
}
let line = self.next_line;
let entry = |text: String| Entry {
text,
line,
typed: None,
};
let scanned = scan(input);
let code = input[..scanned.trailing_comment.unwrap_or(input.len())].trim_end();
let rest = &input[code.len()..];
let wrap = |prefix: &str, suffix: &str| Entry {
text: format!("{prefix}{code}{suffix}{rest}"),
line,
typed: Some(Typed {
input: input.to_string(),
prefix: prefix.len(),
code: code.len(),
suffix: suffix.len(),
}),
};
let reply = if is_fn_decl(input) {
let e = entry(input.to_string());
self.try_run(New::Fn(&e)).map(|out| (e, true, out))
} else if scanned.min_depth < 0 {
return Reply::Err(msg::repl_unbalanced());
} else if code.ends_with(';') || code.ends_with('}') {
let e = entry(input.to_string());
self.try_run(New::Stmt(&e)).map(|out| (e, false, out))
} else {
let echo = wrap("println(\"{}\", ", ");");
match self.try_run(New::Stmt(&echo)) {
Ok(out) => Ok((echo, false, out)),
Err(_) => {
let e = wrap("", ";");
self.try_run(New::Stmt(&e)).map(|out| (e, false, out))
}
}
};
match reply {
Ok((e, is_fn, out)) => {
self.next_line += input.lines().count();
if is_fn {
self.fns.push(e);
} else {
self.stmts.push(e);
}
Reply::Out(out)
}
Err(Failure(d)) => Reply::Err(d),
}
}
fn command(&mut self, cmd: &str) -> Reply {
match cmd {
"help" => Reply::Out(msg::repl_help()),
"quit" | "q" => Reply::Quit,
"reset" => {
*self = Session::new(self.seed);
Reply::Out(msg::repl_reset())
}
"qasm" => match self.build(New::Nothing) {
Ok((_, e)) => Reply::Out(e.circuit.to_qasm()),
Err(f) => Reply::Err(f.0),
},
other => Reply::Err(msg::repl_unknown_command(other)),
}
}
pub fn leaks(&self) -> Option<String> {
let p = Program::assemble(&self.fns, &self.stmts, New::Nothing);
let mut errors = front(&p.src).err()?;
for d in &mut errors {
d.notes.retain(|n| n.span != Some(p.main_close));
}
Some(p.render(&errors).0)
}
fn build(&self, new: New) -> Result<(Program, interp::Elaborated), Failure> {
let is_stmt = matches!(new, New::Stmt(_));
let p = Program::assemble(&self.fns, &self.stmts, new);
let program = match front(&p.src) {
Ok(program) => program,
Err(errors) => {
let errors: Vec<Diagnostic> =
errors.into_iter().filter(|d| !p.is_open_leak(d)).collect();
if !errors.is_empty() {
return Err(p.render(&errors));
}
let toks = lexer::lex(&p.src).map_err(|d| p.render(&[d]))?;
parser::parse(toks).map_err(|d| p.render(&[d]))?
}
};
if is_stmt {
let main = program.fns.iter().find(|f| f.name.name == "main");
let top_return = main.is_some_and(|f| has_return(&f.body.stmts, p.input_at));
if top_return {
return Err(Failure(msg::repl_return()));
}
}
let e = interp::elaborate(&program).map_err(|d| p.render(&[d]))?;
Ok((p, e))
}
fn try_run(&mut self, new: New) -> Result<String, Failure> {
let (p, e) = self.build(new)?;
let prints_bits = e
.output
.iter()
.any(|o| matches!(o, interp::OutPiece::Bit(_) | interp::OutPiece::Bits(..)));
let out = if prints_bits {
let at = Span::new(p.input_at, p.input_at);
let shot = e
.circuit
.simulate_shots(Backend::StateVector, self.seed, 1)
.next()
.expect("one shot")
.map_err(|err| p.render(&[sim_error(err, at)]))?;
render_output(&e.output, Some(&shot))
} else {
render_output(&e.output, None)
};
let new = out
.strip_prefix(self.shown.as_str())
.unwrap_or(&out)
.to_string();
self.shown = out;
Ok(new)
}
}
pub fn run(
input: impl BufRead,
out: &mut impl Write,
err: &mut impl Write,
seed: u64,
interactive: bool,
) -> u8 {
let mut session = Session::new(seed);
if interactive {
let _ = write!(out, "{}", msg::repl_banner(env!("CARGO_PKG_VERSION")));
}
let mut lines = input.lines();
let mut buf = String::new();
loop {
if interactive {
let _ = write!(out, "{}", if buf.is_empty() { "qx> " } else { "... " });
let _ = out.flush();
}
let Some(Ok(line)) = lines.next() else {
if !buf.trim().is_empty() {
report(session.input(&buf), out, err);
}
break;
};
buf.push_str(&line);
buf.push('\n');
if open_brackets(&buf) > 0 {
continue;
}
let reply = session.input(&buf);
buf.clear();
if matches!(reply, Reply::Quit) {
break;
}
report(reply, out, err);
}
match session.leaks() {
Some(d) => {
let _ = write!(err, "{d}");
1
}
None => 0,
}
}
fn report(reply: Reply, out: &mut impl Write, err: &mut impl Write) {
match reply {
Reply::Out(s) => {
let _ = write!(out, "{s}");
let _ = out.flush();
}
Reply::Err(s) => {
let _ = write!(err, "{s}");
let _ = err.flush();
}
Reply::Quit => {}
}
}