quantum_queries/src/vm/mod.rs

465 lines
21 KiB
Rust

pub mod parsing;
use parsing::ast;
use crate::vm::parsing::ast::ComparisonOperator;
type Bytecode = (OpCode, usize);
#[derive(Debug)]
pub struct VmCode {
code: Vec<Bytecode>,
}
#[derive(Debug)]
pub struct Vm<'code> {
code: &'code VmCode,
registers: Registers,
}
#[derive(Debug)]
pub struct Registers {
x: i64,
y: i64,
n: i64,
p: i64,
k: i64,
}
#[derive(Debug)]
pub enum VmOutput {
Boolean(bool),
Arithmetic(ArithmeticValue),
}
#[derive(Debug)]
pub enum ArithmeticValue {
Integer(i64),
Floating(f64),
}
#[derive(Debug)]
pub enum OpCode {
UnaryBooleanOperator(ast::UnaryBooleanOperator),
BinaryArithmeticOperator(ast::BinaryArithmeticOperator),
ComparisonOperator(ast::ComparisonOperator),
UnaryArithmeticOperator(ast::UnaryArithmeticOperator),
BinaryBooleanOperator(ast::BinaryBooleanOperator),
Variable(ast::Variable),
Literal(i64),
}
enum Expression {
Boolean(ast::BooleanExpression),
Arithmetic(ast::ArithmeticExpression),
}
impl VmOutput {
pub fn unwrap_bool(self) -> bool {
match self {
VmOutput::Boolean(value) => value,
VmOutput::Arithmetic(_) => panic!("Expected boolean, got arithmetic value."),
}
}
#[allow(unused)]
pub fn unwrap_arithmetic(self) -> f64 {
match self {
VmOutput::Boolean(_) => panic!("Expected arithmetic, got boolean value."),
VmOutput::Arithmetic(value) => match value {
ArithmeticValue::Integer(value) => value as f64,
ArithmeticValue::Floating(value) => value,
},
}
}
}
impl Registers {
pub fn load(x: u64, y: u64, n: u32, p: u32, k: u32) -> Self {
Self {
x: x as i64,
y: y as i64,
n: n as i64,
p: p as i64,
k: k as i64,
}
}
}
pub fn compile_boolean(expression: ast::BooleanExpression) -> VmCode {
let mut code = Vec::<Bytecode>::new();
compile_expression(Expression::Boolean(expression), &mut code);
VmCode { code }
}
#[allow(unused)]
pub fn compile_arithmetic(expression: ast::ArithmeticExpression) -> VmCode {
let mut code = Vec::<Bytecode>::new();
compile_expression(Expression::Arithmetic(expression), &mut code);
VmCode { code }
}
impl VmCode {
pub fn any<P: Fn(&OpCode) -> bool>(&self, predicate: P) -> bool {
for (opcode, _) in &self.code {
if predicate(opcode) {
return true;
}
}
false
}
}
impl<'code> Vm<'code> {
pub fn load(code: &'code VmCode, registers: Registers) -> Self {
Vm { code, registers }
}
pub fn run(&self) -> VmOutput {
// Alias for convenience
let code = &self.code.code;
let registers = &self.registers;
struct Resolver<'f> {
f: &'f dyn Fn(&Resolver, usize) -> VmOutput,
}
let resolver = Resolver {
f: &|resolver: &Resolver, op_index: usize| -> VmOutput {
let (opcode, offset) = &code[op_index];
match opcode {
OpCode::UnaryBooleanOperator(op) => match op {
ast::UnaryBooleanOperator::Not => {
let value = (resolver.f)(resolver, op_index + 1);
match value {
VmOutput::Arithmetic(_) => panic!("Bad bytecode! Unary operator is followed by arithmetic resolution."),
VmOutput::Boolean(value) => VmOutput::Boolean(!value),
}
}
},
OpCode::ComparisonOperator(op) => {
let left_operand = match (resolver.f)(resolver, op_index + 1) {
VmOutput::Arithmetic(value) => value,
VmOutput::Boolean(_) => panic!(
"Bad bytecode! Left operand of arithmetic operator is boolean."
),
};
let right_operand = match (resolver.f)(resolver, op_index + offset) {
VmOutput::Arithmetic(value) => value,
VmOutput::Boolean(_) => panic!(
"Bad bytecode! Right operand of arithmetic operator is boolean."
),
};
fn comparison<T: std::cmp::PartialOrd>(
op: &ComparisonOperator,
left_operand: T,
right_operand: T,
) -> VmOutput {
VmOutput::Boolean(match op {
ast::ComparisonOperator::GreaterOrEqual => {
left_operand.ge(&right_operand)
}
ast::ComparisonOperator::LessOrEqual => {
left_operand.le(&right_operand)
}
ast::ComparisonOperator::GreaterThan => {
left_operand.gt(&right_operand)
}
ast::ComparisonOperator::LessThan => {
left_operand.lt(&right_operand)
}
ast::ComparisonOperator::NotEqual => {
left_operand.ne(&right_operand)
}
ast::ComparisonOperator::Equal => left_operand.eq(&right_operand),
})
};
match left_operand {
ArithmeticValue::Integer(left_operand) => match right_operand {
ArithmeticValue::Integer(right_operand) => {
comparison(op, left_operand, right_operand)
}
ArithmeticValue::Floating(right_operand) => {
comparison(op, left_operand as f64, right_operand)
}
},
ArithmeticValue::Floating(left_operand) => match right_operand {
ArithmeticValue::Integer(right_operand) => {
comparison(op, left_operand, right_operand as f64)
}
ArithmeticValue::Floating(right_operand) => {
comparison(op, left_operand, right_operand)
}
},
}
}
OpCode::BinaryArithmeticOperator(op) => {
let left_operand = match (resolver.f)(resolver, op_index + 1) {
VmOutput::Arithmetic(value) => value,
VmOutput::Boolean(_) => panic!(
"Bad bytecode! Left operand of arithmetic operator is boolean."
),
};
let right_operand = match (resolver.f)(resolver, op_index + offset) {
VmOutput::Arithmetic(value) => value,
VmOutput::Boolean(_) => panic!(
"Bad bytecode! Right operand of arithmetic operator is boolean."
),
};
let operations_as_integer = |left_operand: i64, right_operand: i64| match op
{
ast::BinaryArithmeticOperator::Times => {
ArithmeticValue::Integer(left_operand * right_operand)
}
ast::BinaryArithmeticOperator::Divide => {
if left_operand % right_operand == 0 {
ArithmeticValue::Integer(left_operand / right_operand)
} else {
ArithmeticValue::Floating(
left_operand as f64 / right_operand as f64,
)
}
}
ast::BinaryArithmeticOperator::Plus => {
ArithmeticValue::Integer(left_operand + right_operand)
}
ast::BinaryArithmeticOperator::Minus => {
ArithmeticValue::Integer(left_operand - right_operand)
}
ast::BinaryArithmeticOperator::Xor => {
ArithmeticValue::Integer(left_operand ^ right_operand)
}
ast::BinaryArithmeticOperator::Pow => {
if right_operand > 0 {
ArithmeticValue::Integer(left_operand.pow(right_operand as u32))
} else {
ArithmeticValue::Floating(
(left_operand as f64).powi(right_operand as i32),
)
}
}
};
let operations_as_floating =
|left_operand: f64, right_operand: f64| match op {
ast::BinaryArithmeticOperator::Times => {
ArithmeticValue::Floating(left_operand * right_operand)
}
ast::BinaryArithmeticOperator::Divide => ArithmeticValue::Floating(
left_operand as f64 / right_operand as f64,
),
ast::BinaryArithmeticOperator::Plus => {
ArithmeticValue::Floating(left_operand + right_operand)
}
ast::BinaryArithmeticOperator::Minus => {
ArithmeticValue::Floating(left_operand - right_operand)
}
ast::BinaryArithmeticOperator::Xor => ArithmeticValue::Integer(
left_operand as i64 ^ right_operand as i64,
),
ast::BinaryArithmeticOperator::Pow => {
ArithmeticValue::Floating(left_operand.powf(right_operand))
}
};
VmOutput::Arithmetic(match left_operand {
ArithmeticValue::Integer(left_operand) => match right_operand {
ArithmeticValue::Integer(right_operand) => {
operations_as_integer(left_operand, right_operand)
}
ArithmeticValue::Floating(right_operand) => {
operations_as_floating(left_operand as f64, right_operand)
}
},
ArithmeticValue::Floating(left_operand) => match right_operand {
ArithmeticValue::Integer(right_operand) => {
operations_as_floating(left_operand, right_operand as f64)
}
ArithmeticValue::Floating(right_operand) => {
operations_as_floating(left_operand, right_operand)
}
},
})
}
OpCode::UnaryArithmeticOperator(op) => {
let value = match (resolver.f)(resolver, op_index + 1) {
VmOutput::Arithmetic(value) => value,
VmOutput::Boolean(_) => panic!("Bad bytecode! Arithmetic unary operator followed by boolean resolution."),
};
VmOutput::Arithmetic(match op {
ast::UnaryArithmeticOperator::Negative => match value {
ArithmeticValue::Integer(value) => ArithmeticValue::Integer(-value),
ArithmeticValue::Floating(value) => {
ArithmeticValue::Floating(-value)
}
},
ast::UnaryArithmeticOperator::Ham => {
ArithmeticValue::Integer(match value {
ArithmeticValue::Integer(value) => value.count_ones() as i64,
ArithmeticValue::Floating(value) => {
(value as u64).count_ones() as i64
}
})
}
ast::UnaryArithmeticOperator::Sqrt => {
ArithmeticValue::Floating(match value {
ArithmeticValue::Integer(value) => (value as f64).sqrt(),
ArithmeticValue::Floating(value) => value.sqrt(),
})
}
})
}
OpCode::BinaryBooleanOperator(op) => {
let left_operand = match (resolver.f)(resolver, op_index + 1) {
VmOutput::Boolean(value) => value,
VmOutput::Arithmetic(_) => panic!(
"Bad bytecode! Left operand of boolean operator is arithmetic."
),
};
let right_operand = match (resolver.f)(resolver, op_index + offset) {
VmOutput::Boolean(value) => value,
VmOutput::Arithmetic(_) => panic!(
"Bad bytecode! Right operand of boolean operator is arithmetic."
),
};
VmOutput::Boolean(match op {
ast::BinaryBooleanOperator::And => left_operand & right_operand,
ast::BinaryBooleanOperator::Or => left_operand | right_operand,
ast::BinaryBooleanOperator::Xor => left_operand ^ right_operand,
})
}
OpCode::Variable(var) => {
VmOutput::Arithmetic(ArithmeticValue::Integer(match var {
ast::Variable::X => registers.x,
ast::Variable::Y => registers.y,
ast::Variable::N => registers.n,
ast::Variable::P => registers.p,
ast::Variable::K => registers.k,
}))
}
OpCode::Literal(lit) => VmOutput::Arithmetic(ArithmeticValue::Integer(*lit)),
}
},
};
(resolver.f)(&resolver, 0)
}
}
/// Returns how many code-points (Bytecode units) were emitted
fn compile_expression(expression: Expression, code: &mut Vec<Bytecode>) -> usize {
match expression {
Expression::Boolean(expression) => match expression {
ast::BooleanExpression::BinaryBooleanConjunction(expression) => {
let expression = *expression;
code.push((OpCode::BinaryBooleanOperator(expression.operator), 0));
let index = code.len() - 1;
let left_operand_size =
compile_expression(Expression::Boolean(expression.left_operand), code);
let right_operand_size =
compile_expression(Expression::Boolean(expression.right_operand), code);
code[index].1 = left_operand_size + 1;
return 1 + left_operand_size + right_operand_size;
}
ast::BooleanExpression::UnaryBooleanConjunction(expression) => {
let expression = *expression;
code.push((OpCode::UnaryBooleanOperator(expression.operator), 0));
let operand_size =
compile_expression(Expression::Boolean(expression.operand), code);
return 1 + operand_size;
}
ast::BooleanExpression::ComparisonConjunction(expression) => {
code.push((OpCode::ComparisonOperator(expression.operator), 0));
let index = code.len() - 1;
let left_operand_size = match expression.left_operand {
ast::ArithmeticOperand::Literal(literal) => {
code.push((OpCode::Literal(literal), 0));
1_usize
}
ast::ArithmeticOperand::Expression(expression) => {
compile_expression(Expression::Arithmetic(*expression), code)
}
};
let right_operand_size = match expression.right_operand {
ast::ArithmeticOperand::Literal(literal) => {
code.push((OpCode::Literal(literal), 0));
1_usize
}
ast::ArithmeticOperand::Expression(expression) => {
compile_expression(Expression::Arithmetic(*expression), code)
}
};
code[index].1 = left_operand_size + 1;
return 1 + left_operand_size + right_operand_size;
}
},
Expression::Arithmetic(expression) => match expression {
ast::ArithmeticExpression::Variable(variable) => {
code.push((OpCode::Variable(variable), 0));
return 1;
}
ast::ArithmeticExpression::UnaryArithmeticConjunction(expression) => {
let expression = *expression;
code.push((OpCode::UnaryArithmeticOperator(expression.operator), 0));
let operand_size = match expression.operand {
ast::ArithmeticOperand::Literal(literal) => {
code.push((OpCode::Literal(literal), 0));
1_usize
}
ast::ArithmeticOperand::Expression(expression) => {
compile_expression(Expression::Arithmetic(*expression), code)
}
};
return 1 + operand_size;
}
ast::ArithmeticExpression::BinaryArithmeticConjunction(expression) => {
code.push((OpCode::BinaryArithmeticOperator(expression.operator), 0));
let index = code.len() - 1;
let left_operand_size = match expression.left_operand {
ast::ArithmeticOperand::Literal(literal) => {
code.push((OpCode::Literal(literal), 0));
1_usize
}
ast::ArithmeticOperand::Expression(expression) => {
compile_expression(Expression::Arithmetic(*expression), code)
}
};
let right_operand_size = match expression.right_operand {
ast::ArithmeticOperand::Literal(literal) => {
code.push((OpCode::Literal(literal), 0));
1_usize
}
ast::ArithmeticOperand::Expression(expression) => {
compile_expression(Expression::Arithmetic(*expression), code)
}
};
code[index].1 = left_operand_size + 1;
return 1 + left_operand_size + right_operand_size;
}
},
}
}
#[test]
fn boolean_compilation_test() {
let expression =
parsing::parse_relation("and (and (< x 1) (!= 1 y)) (< ham x k)").expect("Valid AST");
println!("{:?}", compile_boolean(expression));
}
#[test]
fn run_test() {
let expression = parsing::parse_relation("(= (ham (^ x y)) (ham 1))");
if let Err(e) = expression {
println!("{}", e);
panic!();
}
let code = compile_boolean(expression.unwrap());
let vm = Vm::load(&code, Registers::load(0b_1011, 0b_1111, 10, 2, 3));
println!("{:?}", vm.run());
}