Skip to content

Commit

Permalink
refactor: rename constant, impl deref for stacks
Browse files Browse the repository at this point in the history
  • Loading branch information
Fumuran committed Sep 13, 2024
1 parent dd9f54a commit 414a7c2
Show file tree
Hide file tree
Showing 19 changed files with 115 additions and 115 deletions.
2 changes: 1 addition & 1 deletion air/src/constraints/stack/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ pub fn get_assertions_last_step(
stack_outputs: &StackOutputs,
) {
// stack columns at the last step should be set to stack outputs, excluding overflow outputs
for (i, value) in stack_outputs.elements().iter().enumerate() {
for (i, value) in stack_outputs.iter().enumerate() {
result.push(Assertion::single(STACK_TRACE_OFFSET + i, step, *value));
}
}
Expand Down
6 changes: 3 additions & 3 deletions air/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ impl Air for ProcessorAir {
result.push(Assertion::single(FMP_COL_IDX, 0, Felt::new(2u64.pow(30))));

// add initial assertions for the stack.
stack::get_assertions_first_step(&mut result, self.stack_inputs.elements());
stack::get_assertions_first_step(&mut result, &*self.stack_inputs);

// Add initial assertions for the range checker.
range::get_assertions_first_step(&mut result);
Expand Down Expand Up @@ -272,8 +272,8 @@ impl PublicInputs {
impl vm_core::ToElements<Felt> for PublicInputs {
fn to_elements(&self) -> Vec<Felt> {
let mut result = self.program_info.to_elements();
result.append(&mut self.stack_inputs.to_elements());
result.append(&mut self.stack_outputs.to_elements());
result.append(&mut self.stack_inputs.to_vec());
result.append(&mut self.stack_outputs.to_vec());
result
}
}
Expand Down
8 changes: 2 additions & 6 deletions air/src/trace/stack/mod.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
use core::ops::Range;

use vm_core::utils::range;
use vm_core::{stack::MIN_STACK_DEPTH, utils::range};

// CONSTANTS
// ================================================================================================

/// Index at which stack item columns start in the stack trace.
pub const STACK_TOP_OFFSET: usize = 0;

/// The number of stack registers which can be accessed by the VM directly. This is also the
/// minimum stack depth enforced by the VM.
pub const STACK_TOP_SIZE: usize = 16;

/// Location of stack top items in the stack trace.
pub const STACK_TOP_RANGE: Range<usize> = range(STACK_TOP_OFFSET, STACK_TOP_SIZE);
pub const STACK_TOP_RANGE: Range<usize> = range(STACK_TOP_OFFSET, MIN_STACK_DEPTH);

/// Number of bookkeeping and helper columns in the stack trace.
pub const NUM_STACK_HELPER_COLS: usize = 3;
Expand Down
5 changes: 0 additions & 5 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,3 @@ pub mod stack;
pub use stack::{StackInputs, StackOutputs};

pub mod utils;

// TYPE ALIASES
// ================================================================================================

pub type StackTopState = [Felt; stack::MIN_STACK_DEPTH];
39 changes: 23 additions & 16 deletions core/src/stack/inputs.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use alloc::vec::Vec;
use core::slice;
use core::{ops::Deref, slice};

use super::{
super::ZERO, get_stack_values_num, ByteWriter, Felt, InputError, Serializable, ToElements,
MIN_STACK_DEPTH,
super::ZERO, get_num_stack_values, ByteWriter, Felt, InputError, Serializable, MIN_STACK_DEPTH,
};
use crate::utils::{ByteReader, Deserializable, DeserializationError};

Expand Down Expand Up @@ -54,16 +53,22 @@ impl StackInputs {

Self::new(values)
}
}

// PUBLIC ACCESSORS
// --------------------------------------------------------------------------------------------
impl Deref for StackInputs {
type Target = [Felt; MIN_STACK_DEPTH];

/// Returns the initial stack elements in stack/reversed order.
pub fn elements(&self) -> &[Felt] {
fn deref(&self) -> &Self::Target {
&self.elements
}
}

impl From<[Felt; MIN_STACK_DEPTH]> for StackInputs {
fn from(value: [Felt; MIN_STACK_DEPTH]) -> Self {
Self { elements: value }
}
}

impl<'a> IntoIterator for &'a StackInputs {
type Item = &'a Felt;
type IntoIter = slice::Iter<'a, Felt>;
Expand All @@ -82,27 +87,29 @@ impl IntoIterator for StackInputs {
}
}

impl ToElements<Felt> for StackInputs {
fn to_elements(&self) -> Vec<Felt> {
self.elements.to_vec()
}
}

// SERIALIZATION
// ================================================================================================

impl Serializable for StackInputs {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
target.write_u8(get_stack_values_num(self.elements()));
target.write_u8(get_num_stack_values(self));
target.write_many(self.elements);
}
}

impl Deserializable for StackInputs {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let elements_num = source.read_u8()?;
let mut elements = source.read_many::<Felt>(elements_num.into())?;
let num_elements = source.read_u8()?;

// check that `num_elements` is valid
if num_elements > MIN_STACK_DEPTH as u8 {
return Err(DeserializationError::InvalidValue(format!(
"number of stack elements should not be greater than {}, but {} was found",
MIN_STACK_DEPTH, num_elements
)));
}

let mut elements = source.read_many::<Felt>(num_elements.into())?;
elements.resize(MIN_STACK_DEPTH, ZERO);

Ok(StackInputs { elements: elements.try_into().unwrap() })
Expand Down
10 changes: 5 additions & 5 deletions core/src/stack/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{
errors::{InputError, OutputError},
Felt, ToElements,
Felt,
};
use crate::utils::{ByteWriter, Serializable};

Expand All @@ -26,14 +26,14 @@ pub const MIN_STACK_DEPTH: usize = 16;
// ================================================================================================

/// Get the number of non-zero stack elements.
fn get_stack_values_num(values: &[Felt]) -> u8 {
let mut acc = 0;
fn get_num_stack_values(values: &[Felt; MIN_STACK_DEPTH]) -> u8 {
let mut num_trailing_zeros = 0;
for v in values.iter().rev() {
if v.as_int() == 0 {
acc += 1;
num_trailing_zeros += 1;
} else {
break;
}
}
(MIN_STACK_DEPTH - acc) as u8
(MIN_STACK_DEPTH - num_trailing_zeros) as u8
}
46 changes: 28 additions & 18 deletions core/src/stack/outputs.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use alloc::vec::Vec;
use core::ops::Deref;

use miden_crypto::{Word, ZERO};

use super::{
get_stack_values_num, ByteWriter, Felt, OutputError, Serializable, ToElements, MIN_STACK_DEPTH,
};
use super::{get_num_stack_values, ByteWriter, Felt, OutputError, Serializable, MIN_STACK_DEPTH};
use crate::utils::{range, ByteReader, Deserializable, DeserializationError};

// STACK OUTPUTS
Expand Down Expand Up @@ -84,11 +83,6 @@ impl StackOutputs {
Some(word_elements)
}

/// Returns the stack outputs, which is state of the stack at the end of execution.
pub fn elements(&self) -> &[Felt] {
&self.elements
}

/// Returns the number of requested stack outputs or returns the full stack if fewer than the
/// requested number of stack values exist.
pub fn stack_truncated(&self, num_outputs: usize) -> &[Felt] {
Expand All @@ -100,19 +94,27 @@ impl StackOutputs {
// --------------------------------------------------------------------------------------------

/// Returns mutable access to the stack outputs, to be used for testing or running examples.
/// TODO: this should be marked with #[cfg(test)] attribute, but that currently won't work with
/// the integration test handler util.
pub fn stack_mut(&mut self) -> &mut [Felt] {
&mut self.elements
}

/// Converts the [`StackOutputs`] into the vector of `u64` values.
pub fn as_int_vec(&self) -> Vec<u64> {
self.elements.iter().map(|e| (*e).as_int()).collect()
}
}

// HELPER FUNCTIONS
// ================================================================================================
impl Deref for StackOutputs {
type Target = [Felt; 16];

impl ToElements<Felt> for StackOutputs {
fn to_elements(&self) -> Vec<Felt> {
self.elements.to_vec()
fn deref(&self) -> &Self::Target {
&self.elements
}
}

impl From<[Felt; MIN_STACK_DEPTH]> for StackOutputs {
fn from(value: [Felt; MIN_STACK_DEPTH]) -> Self {
Self { elements: value }
}
}

Expand All @@ -121,16 +123,24 @@ impl ToElements<Felt> for StackOutputs {

impl Serializable for StackOutputs {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
target.write_u8(get_stack_values_num(self.elements()));
target.write_u8(get_num_stack_values(self));
target.write_many(self.elements);
}
}

impl Deserializable for StackOutputs {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let elements_num = source.read_u8()?;
let mut elements = source.read_many::<Felt>(elements_num.into())?;
let num_elements = source.read_u8()?;

// check that `num_elements` is valid
if num_elements > MIN_STACK_DEPTH as u8 {
return Err(DeserializationError::InvalidValue(format!(
"number of stack elements should not be greater than {}, but {} was found",
MIN_STACK_DEPTH, num_elements
)));
}

let mut elements = source.read_many::<Felt>(num_elements.into())?;
elements.resize(MIN_STACK_DEPTH, ZERO);

Ok(Self { elements: elements.try_into().unwrap() })
Expand Down
2 changes: 1 addition & 1 deletion miden/src/cli/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ impl OutputFile {
/// Returns a new [OutputFile] from the specified outputs vectors
pub fn new(stack_outputs: &StackOutputs) -> Self {
Self {
stack: stack_outputs.elements().iter().map(|&v| v.to_string()).collect::<Vec<String>>(),
stack: stack_outputs.iter().map(|&v| v.to_string()).collect::<Vec<String>>(),
}
}

Expand Down
2 changes: 1 addition & 1 deletion processor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub use vm_core::{
};
use vm_core::{
mast::{BasicBlockNode, CallNode, JoinNode, LoopNode, OpBatch, SplitNode, OP_GROUP_SIZE},
Decorator, DecoratorIterator, FieldElement, StackTopState,
Decorator, DecoratorIterator, FieldElement,
};
pub use winter_prover::matrix::ColMatrix;

Expand Down
7 changes: 4 additions & 3 deletions processor/src/operations/u32_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,9 @@ where

#[cfg(test)]
mod tests {
use miden_air::trace::{decoder::NUM_USER_OP_HELPERS, stack::STACK_TOP_SIZE};
use miden_air::trace::decoder::NUM_USER_OP_HELPERS;
use test_utils::rand::rand_value;
use vm_core::stack::MIN_STACK_DEPTH;

use super::{
super::{Felt, Operation},
Expand Down Expand Up @@ -466,8 +467,8 @@ mod tests {
(d, c, b, a)
}

fn build_expected(values: &[u32]) -> [Felt; STACK_TOP_SIZE] {
let mut expected = [ZERO; STACK_TOP_SIZE];
fn build_expected(values: &[u32]) -> [Felt; MIN_STACK_DEPTH] {
let mut expected = [ZERO; MIN_STACK_DEPTH];
for (&value, result) in values.iter().zip(expected.iter_mut()) {
*result = Felt::new(value as u64);
}
Expand Down
5 changes: 0 additions & 5 deletions processor/src/stack/aux_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,6 @@ impl AuxTraceBuilder {
}

impl<E: FieldElement<BaseField = Felt>> AuxColumnBuilder<E> for AuxTraceBuilder {
/// Initializes the overflow stack auxiliary column.
fn init_responses(&self, _main_trace: &MainTrace, _alphas: &[E]) -> E {
E::ONE
}

/// Removes a row from the stack overflow table.
fn get_requests_at(&self, main_trace: &MainTrace, alphas: &[E], i: RowIndex) -> E {
let is_left_shift = main_trace.is_left_shift(i);
Expand Down
3 changes: 1 addition & 2 deletions processor/src/stack/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,8 @@ impl Stack {
init_trace_capacity: usize,
keep_overflow_trace: bool,
) -> Self {
let init_values = inputs.elements();
let overflow = OverflowTable::new(keep_overflow_trace);
let trace = StackTrace::new(init_values, init_trace_capacity, MIN_STACK_DEPTH, ZERO);
let trace = StackTrace::new(&**inputs, init_trace_capacity, MIN_STACK_DEPTH, ZERO);

Self {
clk: RowIndex::from(0),
Expand Down
8 changes: 3 additions & 5 deletions processor/src/stack/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ use miden_air::trace::{
};
use vm_core::FieldElement;

use super::{
super::StackTopState, Felt, OverflowTableRow, Stack, StackInputs, MIN_STACK_DEPTH, ONE, ZERO,
};
use super::{Felt, OverflowTableRow, Stack, StackInputs, MIN_STACK_DEPTH, ONE, ZERO};

// TYPE ALIASES
// ================================================================================================
Expand Down Expand Up @@ -396,7 +394,7 @@ fn generate_trace() {

/// Builds a [StackTopState] that starts with the provided stack inputs and is padded with zeros
/// until the minimum stack depth.
fn build_stack(stack_inputs: &[u64]) -> StackTopState {
fn build_stack(stack_inputs: &[u64]) -> [Felt; MIN_STACK_DEPTH] {
let mut result = [ZERO; MIN_STACK_DEPTH];
for (idx, &input) in stack_inputs.iter().enumerate() {
result[idx] = Felt::new(input);
Expand Down Expand Up @@ -426,7 +424,7 @@ fn build_helpers_partial(num_overflow: usize, next_overflow_addr: usize) -> Stac
}

/// Returns values in stack top columns of the provided trace at the specified row.
fn read_stack_top(trace: &[Vec<Felt>; STACK_TRACE_WIDTH], row: usize) -> StackTopState {
fn read_stack_top(trace: &[Vec<Felt>; STACK_TRACE_WIDTH], row: usize) -> [Felt; MIN_STACK_DEPTH] {
let mut result = [ZERO; MIN_STACK_DEPTH];
for (value, column) in result.iter_mut().zip(trace) {
*value = column[row];
Expand Down
Loading

0 comments on commit 414a7c2

Please sign in to comment.