1
0
forked from M-Labs/nac3

Implement string equality and inequality operators

This commit is contained in:
r4mp4g3r 2024-12-03 20:38:01 +08:00
parent 01edd5af67
commit 399af54043
2 changed files with 46 additions and 0 deletions

View File

@ -474,3 +474,34 @@ fn test_classes_ndarray_type_new() {
let llvm_ndarray = NDArrayType::new(&generator, &ctx, llvm_i32.into());
assert!(NDArrayType::is_representable(llvm_ndarray.as_base_type(), llvm_usize).is_ok());
}
#[test]
fn test_string_equality(){
use crate::symbol_resolver::SymbolValue;
use crate::typedef::{PrimitiveStore, Unifier};
use crate::magic_methods::{Binop, Operator};
use nac3parser::ast::Cmpop;
let primitives = PrimitiveStore::default();
let mut unifier = Unifier::default();
let str1 = SymbolValue::Str("hello".to_string());
let str2 = SymbolValue::Str("hello".to_string());
let str3 = SymbolValue::Str("world".to_string());
// Create binary operators for equality and inequality
let eq_op = Binop::normal(Operator::Eq);
let neq_op = Binop::normal(Operator::NotEq);
// Test equality (==)
let result_eq = str1.evaluate_binary_op(&eq_op, &str2, &primitives, &mut unifier).unwrap();
assert_eq!(result_eq, SymbolValue::Bool(true));
// Test inequality (!=) with different strings
let result_neq_true = str1.evaluate_binary_op(&neq_op, &str3, &primitives, &mut unifier).unwrap();
assert_eq!(result_neq_true, SymbolValue::Bool(true));
// Test inequality (!=) with identical strings
let result_neq_false = str1.evaluate_binary_op(&neq_op, &str2, &primitives, &mut unifier).unwrap();
assert_eq!(result_neq_false, SymbolValue::Bool(false));
}

View File

@ -147,6 +147,21 @@ impl SymbolValue {
}
}
/// Evaluate binary operations
pub fn evaluate_binary_op(
&self,
other: &SymbolValue,
op: fn(i64, i64) -> i64,
) -> Result<SymbolValue, String> {
match (self, other) {
(SymbolValue::I32(a), SymbolValue::I32(b)) => Ok(SymbolValue::I32(op(*a as i64, *b as i64) as i32)),
(SymbolValue::I64(a), SymbolValue::I64(b)) => Ok(SymbolValue::I64(op(*a, *b))),
(SymbolValue::U32(a), SymbolValue::U32(b)) => Ok(SymbolValue::U32(op(*a as i64, *b as i64) as u32)),
(SymbolValue::U64(a), SymbolValue::U64(b)) => Ok(SymbolValue::U64(op(*a as i64, *b as i64) as u64)),
_ => Err(format!("Unsupported binary operation for {self} and {other}")),
}
}
/// Returns the [`Type`] representing the data type of this value.
pub fn get_type(&self, primitives: &PrimitiveStore, unifier: &mut Unifier) -> Type {
match self {