use crate::error::ParseError;
use crate::qasm;
use crate::Circuit;
pub fn parse(src: &str) -> Result<Circuit, ParseError> {
let normalized = normalize(src).map_err(ParseError::new)?;
qasm::parse(&normalized)
}
pub fn is_openqasm3(src: &str) -> bool {
let clean = qasm::strip_comments(src);
for line in clean.lines() {
if let Some(rest) = line.trim().strip_prefix("OPENQASM") {
return rest.trim_start().starts_with('3');
}
}
false
}
fn normalize(src: &str) -> Result<String, String> {
let clean = qasm::strip_comments(src);
let statements = qasm::split_statements(&clean)?;
let mut out = String::from("OPENQASM 2.0;\n");
for stmt in statements {
if stmt.starts_with("OPENQASM") {
continue;
}
for rewritten in rewrite(stmt)? {
out.push_str(&rewritten);
out.push_str(";\n");
}
}
Ok(out)
}
fn rewrite(stmt: &str) -> Result<Vec<String>, String> {
let head = stmt
.split(|c: char| c.is_whitespace() || c == '(' || c == '[')
.next()
.unwrap_or("");
match head {
"for" | "while" | "def" | "defcal" | "let" | "cal" | "extern" | "duration" | "stretch"
| "delay" | "box" | "else" => Err(format!(
"unsupported OpenQASM 3 construct `{head}`; this engine covers the \
subset that maps onto OpenQASM 2"
)),
"qubit" => Ok(vec![declaration(stmt, "qubit", "qreg")?]),
"bit" => Ok(vec![declaration(stmt, "bit", "creg")?]),
"if" => conditional(stmt),
_ => match measurement_assignment(stmt) {
Some(rewritten) => Ok(vec![rewritten]),
None => Ok(vec![stmt.to_string()]),
},
}
}
fn declaration(stmt: &str, from: &str, to: &str) -> Result<String, String> {
let rest = stmt
.strip_prefix(from)
.ok_or_else(|| format!("malformed declaration `{stmt}`"))?
.trim();
let (size, name) = match rest.strip_prefix('[') {
Some(after) => {
let close = after
.find(']')
.ok_or_else(|| format!("declaration needs `]`: `{stmt}`"))?;
(after[..close].trim().to_string(), after[close + 1..].trim())
}
None => ("1".to_string(), rest),
};
if name.is_empty() {
return Err(format!("declaration needs a name: `{stmt}`"));
}
Ok(format!("{to} {name}[{size}]"))
}
fn measurement_assignment(stmt: &str) -> Option<String> {
let (target, rest) = stmt.split_once('=')?;
let source = rest.strip_prefix(' ').unwrap_or(rest).trim();
let source = source.strip_prefix("measure")?;
Some(format!("measure {} -> {}", source.trim(), target.trim()))
}
fn conditional(stmt: &str) -> Result<Vec<String>, String> {
let open = stmt
.find('{')
.ok_or_else(|| format!("conditional needs a `{{ ... }}` block: `{stmt}`"))?;
let close = stmt
.rfind('}')
.ok_or_else(|| format!("conditional needs `}}`: `{stmt}`"))?;
if close < open {
return Err(format!("malformed conditional `{stmt}`"));
}
let condition = stmt[..open].trim();
let mut guarded = Vec::new();
for inner in stmt[open + 1..close].split(';') {
let inner = inner.trim();
if inner.is_empty() {
continue;
}
guarded.push(format!("{condition} {inner}"));
}
if guarded.is_empty() {
return Err(format!("conditional has no statements: `{stmt}`"));
}
Ok(guarded)
}