Skip to content

Commit

Permalink
Merge pull request #246 from everx-labs/remove-failure
Browse files Browse the repository at this point in the history
Use modern crates anyhow and thiserror instead of failure
  • Loading branch information
tonjen authored Jun 20, 2024
1 parent 3813f5a commit 82ef6cc
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 43 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

All notable changes to this project will be documented in this file.

## Version 1.6.1

- Use modern crates anyhow and thiserror instead of failure
-
## Version 1.6.0

- fix `parse_slice_base`

## Version 1.5.0

- crate was renamed from `ton_assembler` to `ever_assembler`
Expand Down
9 changes: 5 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,20 @@
build = 'build.rs'
edition = '2021'
name = 'ever_assembler'
version = '1.5.9'
version = '1.6.2'

[dependencies]
anyhow = '1.0'
clap = { features = [ 'derive' ], version = '4.3' }
failure = '0.1'
hex = '0.4'
log = '0.4'
num = '0.4'
num-traits = '0.2'
serde = { features = [ 'derive' ], version = '1.0' }
serde_json = '1.0'
ever_block = { git = 'https://github.com/everx-labs/ever-block.git', tag = '1.10.4' }
ever_vm = { git = 'https://github.com/everx-labs/ever-vm.git', tag = '2.1.9' }
thiserror = '1.0'
ever_block = { git = 'https://github.com/everx-labs/ever-block.git', tag = '1.11.0' }
ever_vm = { git = 'https://github.com/everx-labs/ever-vm.git', tag = '2.2.1' }

[features]
gosh = [ ]
Expand Down
19 changes: 9 additions & 10 deletions src/bin/disasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@ use std::{process::ExitCode, collections::HashSet, io::Write};

use clap::{Parser, Subcommand};

use failure::format_err;
use ever_assembler::disasm::{fmt::print_tree_of_cells, loader::Loader, disasm_ex};
use ever_block::{Cell, Status, read_boc, SliceData, write_boc};
use ever_block::{error, Cell, Status, read_boc, SliceData, write_boc};

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
Expand Down Expand Up @@ -85,8 +84,8 @@ fn main_impl() -> Status {

fn subcommand_dump(filename: String) -> Status {
let tvc = std::fs::read(filename)
.map_err(|e| format_err!("failed to read boc file: {}", e))?;
let roots = read_boc(tvc).map_err(|e| format_err!("{}", e))?.roots;
.map_err(|e| error!("failed to read boc file: {}", e))?;
let roots = read_boc(tvc).map_err(|e| error!("{}", e))?.roots;
if roots.is_empty() {
println!("empty");
} else {
Expand Down Expand Up @@ -120,12 +119,12 @@ fn count_unique_cells(cell: &Cell) -> usize {

fn subcommand_extract(filename: String, output: String, index: usize, root: Option<usize>) -> Status {
let boc = std::fs::read(filename)
.map_err(|e| format_err!("failed to read input file: {}", e))?;
let roots = read_boc(boc).map_err(|e| format_err!("{}", e))?.roots;
.map_err(|e| error!("failed to read input file: {}", e))?;
let roots = read_boc(boc).map_err(|e| error!("{}", e))?.roots;

let root_index = root.unwrap_or_default();
let root = roots.get(root_index)
.ok_or_else(|| format_err!("failed to get root {}", root_index))?;
.ok_or_else(|| error!("failed to get root {}", root_index))?;

let cell = root.reference(index)?;

Expand All @@ -150,8 +149,8 @@ fn subcommand_fragment(fragment: String) -> Status {

fn subcommand_text(filename: String, stateinit: bool, full: bool) -> Status {
let boc = std::fs::read(filename)
.map_err(|e| format_err!("failed to read input file: {}", e))?;
let roots = read_boc(boc).map_err(|e| format_err!("{}", e))?.roots;
.map_err(|e| error!("failed to read input file: {}", e))?;
let roots = read_boc(boc).map_err(|e| error!("{}", e))?.roots;

let roots_count = roots.len();
if roots_count == 0 {
Expand All @@ -162,7 +161,7 @@ fn subcommand_text(filename: String, stateinit: bool, full: bool) -> Status {
}

let root0 = roots.get(0)
.ok_or_else(|| format_err!("failed to get root 0"))?;
.ok_or_else(|| error!("failed to get root 0"))?;
let cell = if stateinit {
root0.reference(0)?
} else {
Expand Down
27 changes: 13 additions & 14 deletions src/complex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@

use std::collections::{BTreeMap, HashMap};
use std::{marker::PhantomData, ops::Range};
use ever_block::{BuilderData, Cell, HashmapE, HashmapType, SliceData, Status};
use failure::format_err;
use ever_block::{error, BuilderData, Cell, HashmapE, HashmapType, SliceData, Status};

use super::errors::{
OperationError, ParameterError,
Expand Down Expand Up @@ -623,13 +622,13 @@ fn compile_inline(engine: &mut Engine, par: &[&str], destination: &mut Units, _p
fn compile_code_dict_cell(engine: &mut Engine, par: &[&str], destination: &mut Units, _pos: DbgPos) -> CompileResult {
par.assert_len(2)?;
let dict_key_bitlen = par[0].parse::<usize>()
.map_err(|_| OperationError::CodeDictConstruction)?;
.map_err(|e| OperationError::CodeDictConstruction(e.to_string()))?;
let tokens = par[1]
.split(&[' ', '\t', '\n', ',', '='])
.split(&[' ', '\t', '\n', '\r', ',', '='])
.filter(|t| !t.is_empty())
.collect::<Vec<_>>();
if tokens.len().is_odd() {
return Err(OperationError::CodeDictConstruction)
return Err(OperationError::CodeDictConstruction("Odd number of tokens".to_string()))
}

let mut map = HashMap::new();
Expand All @@ -639,18 +638,18 @@ fn compile_code_dict_cell(engine: &mut Engine, par: &[&str], destination: &mut U
// parse the key
let key = pair[0];
if !key.to_ascii_lowercase().starts_with('x') {
return Err(OperationError::CodeDictConstruction)
return Err(OperationError::CodeDictConstruction(format!("key {} should start with 'x'", key)))
}
let key_slice = SliceData::from_string(&key[1..])
.map_err(|_| ParameterError::UnexpectedType.parameter("key"))?;
if key_slice.remaining_bits() != dict_key_bitlen {
return Err(OperationError::CodeDictConstruction)
return Err(OperationError::CodeDictConstruction(format!("key {} should have {} bits", key, dict_key_bitlen)))
}

// get an assembled fragment by the name
let name = pair[1];
let (value_slice, mut value_dbg) = engine.named_units.get(name)
.ok_or(OperationError::CodeDictConstruction)?
.ok_or(OperationError::CodeDictConstruction(format!("Fragment {} is not defined", name)))?
.clone()
.finalize();

Expand All @@ -661,17 +660,17 @@ fn compile_code_dict_cell(engine: &mut Engine, par: &[&str], destination: &mut U
let value_cell = value_slice.clone().into_cell();
info.append(&mut value_dbg);
dict.setref(key_slice.clone(), &value_cell)
.map_err(|_| OperationError::CodeDictConstruction)?;
.map_err(|e| OperationError::CodeDictConstruction(e.to_string()))?;
}
}

// update debug info
for (key, (mut value_dbg, value_slice)) in map {
let value_slice_after = dict.get(key)
.map_err(|_| OperationError::CodeDictConstruction)?
.ok_or(OperationError::CodeDictConstruction)?;
let value_slice_after = dict.get(key.clone())
.map_err(|e| OperationError::CodeDictConstruction(e.to_string()))?
.ok_or(OperationError::CodeDictConstruction(format!("Value for key {} is not found", key)))?;
adjust_debug_map(&mut value_dbg, value_slice, value_slice_after)
.map_err(|_| OperationError::CodeDictConstruction)?;
.map_err(|e| OperationError::CodeDictConstruction(e.to_string()))?;
info.append(&mut value_dbg);
}

Expand All @@ -689,7 +688,7 @@ fn adjust_debug_map(map: &mut DbgInfo, before: SliceData, after: SliceData) -> S
let hash_before = before.cell().repr_hash();
let hash_after = after.cell().repr_hash();
let entry_before = map.remove(&hash_before)
.ok_or_else(|| format_err!("Failed to remove old value."))?;
.ok_or_else(|| error!("Failed to remove old value."))?;

let adjustment = after.pos();
let mut entry_after = BTreeMap::new();
Expand Down
4 changes: 2 additions & 2 deletions src/disasm/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,15 @@ macro_rules! create_handler_3r {
macro_rules! check {
($expr:expr) => {
if !$expr {
return Err(failure::err_msg(format!("check failed {}:{}", file!(), line!())))
ever_block::fail!("check failed {}:{}", file!(), line!())
}
};
}

macro_rules! check_eq {
($lhs:expr, $rhs:literal) => {
if $lhs != $rhs {
return Err(failure::err_msg(format!("check failed {}:{}", file!(), line!())))
ever_block::fail!("check failed {}:{}", file!(), line!())
}
};
}
Expand Down
9 changes: 3 additions & 6 deletions src/disasm/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
* limitations under the License.
*/

use failure::format_err;
use ever_block::{read_boc, write_boc, SliceData, Status};

use crate::disasm::{disasm, fmt::print_tree_of_cells};
Expand All @@ -34,8 +33,7 @@ fn round_trip_test(filename: &str, check_bin: bool) -> Status {
let bin0 = &std::fs::read(filename)?;
let toc0 = read_boc(bin0)?.withdraw_single_root()?;
let mut asm0 = disasm(&mut SliceData::load_cell(toc0.clone())?)?;
let toc1 = crate::compile_code_to_cell(&asm0.clone())
.map_err(|e| format_err!("{}", e))?;
let toc1 = crate::compile_code_to_cell(&asm0.clone()).unwrap();
let mut asm1 = disasm(&mut SliceData::load_cell(toc1.clone())?)?;

if !check_bin {
Expand Down Expand Up @@ -110,8 +108,7 @@ fn fragments() -> Status {
fn check_code(name: &str) -> Status {
let inp = std::fs::read_to_string(format!("src/tests/disasm/{}.in", name))?;
let out = std::fs::read_to_string(format!("src/tests/disasm/{}.out", name))?;
let mut code = crate::compile_code(&inp)
.map_err(|e| format_err!("{}", e))?;
let mut code = crate::compile_code(&inp).unwrap();
let dis = disasm(&mut code)?;
if dis == out {
return Ok(())
Expand All @@ -124,7 +121,7 @@ fn check_code(name: &str) -> Status {
_ => ()
}
}
Err(format_err!("check failed"))
panic!("check code failed")
}

#[test]
Expand Down
9 changes: 5 additions & 4 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
* limitations under the License.
*/

use ever_block::Error;
use std::fmt;

#[derive(Clone, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -51,12 +52,12 @@ pub enum OperationError {
CellComputeInternal,
FragmentIsAlreadyDefined(String),
FragmentIsNotDefined(String),
CodeDictConstruction,
CodeDictConstruction(String),
Internal(String),
}

impl From<failure::Error> for OperationError {
fn from(e: failure::Error) -> Self {
impl From<Error> for OperationError {
fn from(e: Error) -> Self {
Self::Internal(e.to_string())
}
}
Expand Down Expand Up @@ -198,7 +199,7 @@ impl fmt::Display for OperationError {
CellComputeInternal => write!(f, "Failed to compute the cell"),
FragmentIsAlreadyDefined(name) => write!(f, "Fragment {} is already defined", name),
FragmentIsNotDefined(name) => write!(f, "Fragment {} is not defined", name),
CodeDictConstruction => write!(f, "Failed to construct code dictionary"),
CodeDictConstruction(message) => write!(f, "Failed to construct code dictionary {}", message),
Internal(message) => write!(f, "{}", message),
}
}
Expand Down
24 changes: 21 additions & 3 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ pub fn parse_slice(slice: &str, bits: usize) -> Result<Vec<u8>, ParameterError>

pub fn parse_slice_base(slice: &str, mut bits: usize, base: u32) -> Result<Vec<u8>, ParameterError> {
debug_assert!(bits < 8, "it is offset to get slice parsed");
let origin_bits = bits;
let mut acc = 0u8;
let mut data = vec![];
let mut completion_tag = false;
Expand All @@ -175,7 +176,8 @@ pub fn parse_slice_base(slice: &str, mut bits: usize, base: u32) -> Result<Vec<u
acc |= (x << (4 - bits)) as u8;
bits += 4;
} else {
data.push(acc | (x as u8 >> (bits - 4)));
acc |= x as u8 >> (bits - 4);
data.push(acc);
acc = (x << (12 - bits)) as u8;
bits -= 4;
}
Expand All @@ -189,14 +191,30 @@ pub fn parse_slice_base(slice: &str, mut bits: usize, base: u32) -> Result<Vec<u
}
}
}

let mut removing_trailing_zeroes = || {
while data.last() == Some(&0) {
data.pop();
}
if data.is_empty() {
data.push(1 << (7 - origin_bits));
}
};

if bits != 0 {
if !completion_tag {
if completion_tag {
if acc == 0 {
removing_trailing_zeroes();
}
} else {
acc |= 1 << (7 - bits);
}
if acc != 0 || data.is_empty() {
data.push(acc);
}
} else if !completion_tag {
} else if completion_tag {
removing_trailing_zeroes();
} else {
data.push(0x80);
}
Ok(data)
Expand Down

0 comments on commit 82ef6cc

Please sign in to comment.