Skip to content

Commit

Permalink
Merge pull request #4 from mpapierski/update-parser
Browse files Browse the repository at this point in the history
Update parser
  • Loading branch information
mpapierski authored Feb 5, 2025
2 parents e008738 + 69d644c commit e72ec92
Show file tree
Hide file tree
Showing 23 changed files with 365 additions and 191 deletions.
11 changes: 9 additions & 2 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: Check

on:
push:
branches: [ master ]
branches: [ main ]
pull_request:
branches: [ master ]
branches: [ main ]

env:
CARGO_TERM_COLOR: always
Expand Down Expand Up @@ -95,3 +95,10 @@ jobs:
toolchain: ${{ matrix.toolchain }}
command: test
args: --all-features --workspace

- name: Cargo test with no-std
uses: actions-rs/cargo@v1
with:
toolchain: ${{ matrix.toolchain }}
command: test
args: --no-default-features --workspace
8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "casper-wasm"
version = "0.46.0"
authors = ["Nikolay Volf <nikvolf@gmail.com>", "Svyatoslav Nikolsky <svyatonik@yandex.ru>", "Sergey Shulepov <s.pepyakin@gmail.com>"]
version = "0.46.1"
authors = ["Nikolay Volf <nikvolf@gmail.com>", "Svyatoslav Nikolsky <svyatonik@yandex.ru>", "Sergey Shulepov <s.pepyakin@gmail.com>", "Michał Papierski <michal@papierski.net>"]
license = "MIT/Apache-2.0"
readme = "README.md"
repository = "https://github.com/casper-network/casper-wasm"
Expand All @@ -12,13 +12,13 @@ keywords = ["wasm", "webassembly", "bytecode", "serde", "interpreter"]
categories = ["wasm", "parser-implementations"]
include = ["src/**/*", "LICENSE-*", "README.md"]
edition = "2021"
rust-version = "1.56.1"
rust-version = "1.80.0"

[workspace]
members = ["testsuite"]

[dev-dependencies]
time = "0.3"
hashbrown = "0.15.2"

[features]
default = ["std"]
Expand Down
24 changes: 15 additions & 9 deletions examples/bench-decoder.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,39 @@
extern crate casper_wasm;
extern crate time;

use std::fs;
use time::Instant;

#[cfg(feature = "std")]
fn rate(file_name: &'static str, iterations: u64) {
use std::fs;

use std::time::{Duration, Instant};

let file_size = fs::metadata(file_name)
.unwrap_or_else(|_| panic!("{} to exist", file_name))
.len();
let mut total_ms = 0;
let mut total = Duration::from_secs(0);

for _ in 0..iterations {
let start = Instant::now();
let _module = casper_wasm::deserialize_file(file_name);
let end = Instant::now();
let end = start.elapsed();

total_ms += (end - start).whole_milliseconds();
total += end;
}

println!(
"Rate for {}: {} MB/s",
file_name,
(file_size as f64 * iterations as f64 / (1024*1024) as f64) / // total work megabytes
(total_ms as f64 / 1000f64) // total seconds
(file_size as f64 * iterations as f64 / (1024*1024) as f64) / // total work megabytes
(total.as_millis() as f64 / 1000f64) // total seconds
);
}

#[cfg(feature = "std")]
fn main() {
rate("./res/cases/v1/clang.wasm", 10);
rate("./res/cases/v1/hello.wasm", 100);
rate("./res/cases/v1/with_names.wasm", 100);
}
#[cfg(not(feature = "std"))]
fn main() {
panic!("Compilation requires --feature std")
}
8 changes: 7 additions & 1 deletion examples/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ use std::env;

use casper_wasm::{builder, elements};

#[cfg(feature = "std")]
fn main() {
// Example binary accepts one parameter which is the output file
// where generated wasm module will be written at the end of execution
let args = env::args().collect::<Vec<_>>();
if args.len() != 2 {
println!("Usage: {} output_file.wasm", args[0]);
return
return;
}

// Main entry for the builder api is the module function
Expand Down Expand Up @@ -46,3 +47,8 @@ fn main() {
// Module structure can be serialzed to produce a valid wasm file
casper_wasm::serialize_to_file(&args[1], module).unwrap();
}

#[cfg(not(feature = "std"))]
fn main() {
panic!("Compilation requires --feature std")
}
10 changes: 8 additions & 2 deletions examples/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ extern crate casper_wasm;

use std::env;

#[cfg(feature = "std")]
fn main() {
// Example executable takes one argument which must
// refernce the existing file with a valid wasm module
// reference the existing file with a valid wasm module
let args = env::args().collect::<Vec<_>>();
if args.len() != 2 {
println!("Usage: {} somefile.wasm", args[0]);
return
return;
}

// Here we load module using dedicated for this purpose
Expand Down Expand Up @@ -42,3 +43,8 @@ fn main() {
println!(" size: {}", entry.value().len());
}
}

#[cfg(not(feature = "std"))]
fn main() {
panic!("Compilation requires --feature std")
}
9 changes: 7 additions & 2 deletions examples/exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,15 @@ fn type_by_index(module: &Module, index: usize) -> FunctionType {
}
}

#[cfg(feature = "std")]
fn main() {
// Example executable takes one argument which must
// refernce the existing file with a valid wasm module
// reference the existing file with a valid wasm module
let args: Vec<_> = args().collect();
if args.len() < 2 {
println!("Prints export function names with and their types");
println!("Usage: {} <wasm file>", args[0]);
return
return;
}

// Here we load module using dedicated for this purpose
Expand Down Expand Up @@ -83,3 +84,7 @@ fn main() {
println!("{:}", export);
}
}
#[cfg(not(feature = "std"))]
fn main() {
panic!("Compilation requires --feature std")
}
8 changes: 7 additions & 1 deletion examples/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ extern crate casper_wasm;
use casper_wasm::elements::Section;
use std::env;

#[cfg(feature = "std")]
fn main() {
let args = env::args().collect::<Vec<_>>();
if args.len() != 2 {
println!("Usage: {} somefile.wasm", args[0]);
return
return;
}

let module = casper_wasm::deserialize_file(&args[1]).expect("Failed to load module");
Expand Down Expand Up @@ -51,3 +52,8 @@ fn main() {
}
}
}

#[cfg(not(feature = "std"))]
fn main() {
panic!("Compilation requires --feature std")
}
10 changes: 8 additions & 2 deletions examples/inject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,17 @@ pub fn inject_nop(instructions: &mut elements::Instructions) {

position += 1;
if position >= instructions.len() {
break
break;
}
}
}

#[cfg(feature = "std")]
fn main() {
let args = env::args().collect::<Vec<_>>();
if args.len() != 3 {
println!("Usage: {} input_file.wasm output_file.wasm", args[0]);
return
return;
}

let mut module = casper_wasm::deserialize_file(&args[1]).unwrap();
Expand All @@ -46,3 +47,8 @@ fn main() {

casper_wasm::serialize_to_file(&args[2], build.build()).unwrap();
}

#[cfg(not(feature = "std"))]
fn main() {
panic!("Compilation requires --feature std")
}
8 changes: 7 additions & 1 deletion examples/roundtrip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ extern crate casper_wasm;

use std::env;

#[cfg(feature = "std")]
fn main() {
let args = env::args().collect::<Vec<_>>();
if args.len() != 3 {
println!("Usage: {} in.wasm out.wasm", args[0]);
return
return;
}

let module = match casper_wasm::deserialize_file(&args[1])
Expand All @@ -25,3 +26,8 @@ fn main() {

casper_wasm::serialize_to_file(&args[2], module).expect("Failed to write module");
}

#[cfg(not(feature = "std"))]
fn main() {
panic!("Compilation requires --feature std")
}
8 changes: 7 additions & 1 deletion examples/show.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ extern crate casper_wasm;

use std::env;

#[cfg(feature = "std")]
fn main() {
let args = env::args().collect::<Vec<_>>();
if args.len() != 3 {
println!("Usage: {} <wasm file> <index of function>", args[0]);
return
return;
}

let module = casper_wasm::deserialize_file(&args[1]).expect("Failed to load module");
Expand Down Expand Up @@ -36,3 +37,8 @@ fn main() {
println!("{}", instruction);
}
}

#[cfg(not(feature = "std"))]
fn main() {
panic!("Compilation requires --features std")
}
2 changes: 2 additions & 0 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[toolchain]
channel = "1.84.1"
2 changes: 1 addition & 1 deletion src/builder/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ where
let elements::Type::Function(ref existing) = t;
*existing == func_type
}) {
return existing_entry.0 as u32
return existing_entry.0 as u32;
}
self.module.types.types_mut().push(elements::Type::Function(func_type));
self.module.types.types().len() as u32 - 1
Expand Down
13 changes: 9 additions & 4 deletions src/elements/index_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,13 @@ impl<T> IndexMap<T> {
for _ in 0..len {
let idx: u32 = VarUint32::deserialize(rdr)?.into();
if idx as usize >= max_entry_space {
return Err(Error::Other("index is larger than expected"))
return Err(Error::Other("index is larger than expected"));
}
match prev_idx {
Some(prev) if prev >= idx => {
// Supposedly these names must be "sorted by index", so
// let's try enforcing that and seeing what happens.
return Err(Error::Other("indices are out of order"))
return Err(Error::Other("indices are out of order"));
},
_ => {
prev_idx = Some(idx);
Expand Down Expand Up @@ -178,7 +178,9 @@ where
type Error = Error;

fn serialize<W: io::Write>(self, wtr: &mut W) -> Result<(), Self::Error> {
VarUint32::from(self.len()).serialize(wtr)?;
VarUint32::try_from(self.len())
.map_err(|_| Self::Error::InvalidVarInt32)?
.serialize(wtr)?;
for (idx, value) in self.entries.into_iter() {
VarUint32::from(idx).serialize(wtr)?;
value.serialize(wtr)?;
Expand All @@ -205,7 +207,10 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::io;
use crate::{
alloc::string::{String, ToString},
io,
};

#[test]
fn default_is_empty_no_matter_how_we_look_at_it() {
Expand Down
17 changes: 10 additions & 7 deletions src/elements/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,14 +204,17 @@ impl fmt::Display for Error {
Error::InvalidSectionId(ref id) => write!(f, "Invalid section id: {}", id),
Error::SectionsOutOfOrder => write!(f, "Sections out of order"),
Error::DuplicatedSections(ref id) => write!(f, "Duplicated sections ({})", id),
Error::InvalidMemoryReference(ref mem_ref) =>
write!(f, "Invalid memory reference ({})", mem_ref),
Error::InvalidTableReference(ref table_ref) =>
write!(f, "Invalid table reference ({})", table_ref),
Error::InvalidMemoryReference(ref mem_ref) => {
write!(f, "Invalid memory reference ({})", mem_ref)
},
Error::InvalidTableReference(ref table_ref) => {
write!(f, "Invalid table reference ({})", table_ref)
},
Error::InvalidLimitsFlags(ref flags) => write!(f, "Invalid limits flags ({})", flags),
Error::UnknownFunctionForm(ref form) => write!(f, "Unknown function form ({})", form),
Error::InconsistentCode =>
write!(f, "Number of function body entries and signatures does not match"),
Error::InconsistentCode => {
write!(f, "Number of function body entries and signatures does not match")
},
Error::InvalidSegmentFlags(n) => write!(f, "Invalid segment flags: {}", n),
Error::TooManyLocals => write!(f, "Too many locals"),
Error::DuplicatedNameSubsections(n) => write!(f, "Duplicated name subsections: {}", n),
Expand Down Expand Up @@ -307,7 +310,7 @@ pub fn deserialize_buffer<T: Deserialize>(contents: &[u8]) -> Result<T, T::Error
if reader.position() != contents.len() {
// It's a TrailingData, since if there is not enough data then
// UnexpectedEof must have been returned earlier in T::deserialize.
return Err(io::Error::TrailingData.into())
return Err(io::Error::TrailingData.into());
}
Ok(result)
}
Expand Down
Loading

0 comments on commit e72ec92

Please sign in to comment.