From 373c512397dde9c767ac65453780931a84704ce4 Mon Sep 17 00:00:00 2001 From: Ben Bridle Date: Fri, 18 Apr 2025 20:34:39 +1200 Subject: Implement operator for expressions The operator returns the width of an integer in bits, using the same calculation as for packing an integer into a bit field. --- src/types/expression_stack.rs | 9 +++++++++ src/types/operator.rs | 3 +++ 2 files changed, 12 insertions(+) (limited to 'src/types') diff --git a/src/types/expression_stack.rs b/src/types/expression_stack.rs index 4d26eb2..d14d808 100644 --- a/src/types/expression_stack.rs +++ b/src/types/expression_stack.rs @@ -61,11 +61,20 @@ impl ExpressionStack { Operator::BitOr => { pop!(b); pop!(a); push!(a | b) }, Operator::BitXor => { pop!(b); pop!(a); push!(a ^ b) }, Operator::BitNot => { pop!(a); push!(!a) }, + Operator::Length => { pop!(a); push!(width(a) as isize) }, } return Ok(()); } } +/// Find the number of bits required to hold an integer. +pub fn width(value: isize) -> u32 { + match value.cmp(&0) { + std::cmp::Ordering::Less => (-value).ilog2() + 2, + std::cmp::Ordering::Equal => 0, + std::cmp::Ordering::Greater => value.ilog2() + 1, + } +} pub enum StackError { Underflow, diff --git a/src/types/operator.rs b/src/types/operator.rs index a7e7b9b..af607e3 100644 --- a/src/types/operator.rs +++ b/src/types/operator.rs @@ -18,6 +18,7 @@ pub enum Operator { BitOr, BitXor, BitNot, + Length, } impl Operator { @@ -55,6 +56,7 @@ impl Operator { "" => Some(Operator::BitOr), "" => Some(Operator::BitXor), "" => Some(Operator::BitNot), + "" => Some(Operator::Length), _ => None, } } @@ -81,6 +83,7 @@ impl std::fmt::Display for Operator { Operator::BitOr => "", Operator::BitXor => "", Operator::BitNot => "", + Operator::Length => "", }; write!(f, "{string}") } -- cgit v1.2.3-70-g09d2