Skip to content

Commit

Permalink
Merge pull request #72 from starcoinorg/refactor-move-runtime
Browse files Browse the repository at this point in the history
Refactor move runtime
  • Loading branch information
simonjiao authored Aug 2, 2024
2 parents f4b86b0 + f8df5bc commit 905484b
Show file tree
Hide file tree
Showing 50 changed files with 2,369 additions and 1,711 deletions.
2,704 changes: 1,545 additions & 1,159 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 1 addition & 2 deletions language/evm/move-to-yul/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ impl<'a> Context<'a> {
.unwrap_or_else(|_| PathBuf::from("."))
.to_string_lossy()
.to_string()
+ &std::path::MAIN_SEPARATOR.to_string();
+ std::path::MAIN_SEPARATOR_STR;
if file_path.starts_with(&current_dir) {
file_path[current_dir.len()..].to_string()
} else {
Expand Down Expand Up @@ -255,7 +255,6 @@ impl<'a> Context<'a> {
pub fn derive_contracts(&self) -> Vec<Contract> {
self.env
.get_modules()
.into_iter()
.filter_map(|ref m| {
if is_evm_contract_module(m) {
Some(self.extract_contract(m))
Expand Down
2 changes: 1 addition & 1 deletion language/evm/move-to-yul/src/dispatcher_generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ impl Generator {
}
if !attributes::is_create_fun(fun) || self.storage_type.is_none() {
// If this is not a creator which returns a storage value, add return types.
types.extend(fun.get_return_types().into_iter())
types.extend(fun.get_return_types())
}
types.into_iter().all(|ty| !ty.is_reference())
}
Expand Down
3 changes: 1 addition & 2 deletions language/evm/move-to-yul/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ impl EventSignature {

let ordered_types = EventSignature::get_ordered_types(st);
for (offset, move_ty, field_name) in ordered_types
.map(|(offset, ty, field_name)| (offset, ty, field_name))
.collect_vec()
{
let solidity_ty = SolidityType::translate_from_move(ctx, &move_ty, false); // implicit mapping from a move type to a solidity type
Expand Down Expand Up @@ -253,7 +252,7 @@ pub(crate) fn define_emit_fun_for_send(
// #message[sig=b"xfer(address indexed, address indexed, uint128 indexed)]
for (i, (_, solidity_ty, move_ty, indexed_flag, _)) in signature_types.iter().enumerate() {
let mut var = if i == 0 {
params_vec.get(0).unwrap().to_string()
params_vec.first().unwrap().to_string()
} else if i == 1 {
message_hash_var.clone()
} else {
Expand Down
4 changes: 2 additions & 2 deletions language/evm/move-to-yul/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ pub fn run_to_yul<W: WriteColor>(error_writer: &mut W, mut options: Options) ->
if let Some(i) = options.output.rfind('.') {
options.abi_output = format!("{}.abi.json", &options.output[..i]);
}
fs::write(options.output, &content)?;
fs::write(options.abi_output, &abi_content)?;
fs::write(options.output, content)?;
fs::write(options.abi_output, abi_content)?;
}
Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion language/evm/move-to-yul/src/native_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl NativeFunctions {
attributes::extract_external_signature(fun),
)
} else if self.is_emit_fun(fun) {
let elem_type = fun_id.inst.get(0).unwrap(); // obtain the event type
let elem_type = fun_id.inst.first().unwrap(); // obtain the event type
if let Type::Struct(mid, sid, inst) = elem_type {
let st_id = QualifiedInstId {
module_id: *mid,
Expand Down
10 changes: 5 additions & 5 deletions language/evm/move-to-yul/src/tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl NativeFunctions {
}

fn define_empty_fun(gen: &mut FunctionGenerator, ctx: &Context, fun_id: &QualifiedInstId<FunId>) {
let key_type = fun_id.inst.get(0).expect("key type");
let key_type = fun_id.inst.first().expect("key type");

// TODO: right now the key to storage is simply hash (table_handle, key), which works when key
// is a primitive type. However, this doesn't work when key is a struct or a vector, represented
Expand Down Expand Up @@ -66,7 +66,7 @@ fn define_contains_fun(
ctx: &Context,
fun_id: &QualifiedInstId<FunId>,
) {
let key_type = fun_id.inst.get(0).expect("key type");
let key_type = fun_id.inst.first().expect("key type");

emitln!(ctx.writer, "(table_ref, key_ref) -> res {");
ctx.writer.indent();
Expand Down Expand Up @@ -133,7 +133,7 @@ fn define_contains_fun(
}

fn define_insert_fun(gen: &mut FunctionGenerator, ctx: &Context, fun_id: &QualifiedInstId<FunId>) {
let key_type = fun_id.inst.get(0).expect("key type");
let key_type = fun_id.inst.first().expect("key type");
let value_type = fun_id.inst.get(1).expect("value type");

emitln!(ctx.writer, "(table_ref, key_ref, value) {");
Expand Down Expand Up @@ -236,7 +236,7 @@ fn define_insert_fun(gen: &mut FunctionGenerator, ctx: &Context, fun_id: &Qualif
}

fn define_borrow_fun(gen: &mut FunctionGenerator, ctx: &Context, fun_id: &QualifiedInstId<FunId>) {
let key_type = fun_id.inst.get(0).expect("key type");
let key_type = fun_id.inst.first().expect("key type");

emitln!(ctx.writer, "(table_ref, key_ref) -> value_ref {");
ctx.writer.indent();
Expand Down Expand Up @@ -311,7 +311,7 @@ fn define_borrow_fun(gen: &mut FunctionGenerator, ctx: &Context, fun_id: &Qualif
}

fn define_remove_fun(gen: &mut FunctionGenerator, ctx: &Context, fun_id: &QualifiedInstId<FunId>) {
let key_type = fun_id.inst.get(0).expect("key type");
let key_type = fun_id.inst.first().expect("key type");
let value_type = fun_id.inst.get(1).expect("value type");

emitln!(ctx.writer, "(table_ref, key_ref) -> value {");
Expand Down
12 changes: 6 additions & 6 deletions language/evm/move-to-yul/src/vectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ fn define_empty_fun(gen: &mut FunctionGenerator, ctx: &Context, fun_id: &Qualifi
);
emitln!(ctx.writer, "() -> vector {");
ctx.writer.indent();
let type_size = ctx.type_size(fun_id.inst.get(0).unwrap());
let type_size = ctx.type_size(fun_id.inst.first().unwrap());
emitln!(
ctx.writer,
"vector := {}",
Expand Down Expand Up @@ -444,7 +444,7 @@ fn define_borrow_fun(gen: &mut FunctionGenerator, ctx: &Context, fun_id: &Qualif
1,
"vector instantiated with non-one type parameter"
);
let elem_type = fun_id.inst.get(0).unwrap();
let elem_type = fun_id.inst.first().unwrap();
let elem_type_size = ctx.type_size(elem_type);

emitln!(ctx.writer, "(v_ref, i) -> e_ptr {");
Expand Down Expand Up @@ -543,7 +543,7 @@ fn define_pop_back_fun(
1,
"vector instantiated with non-one type parameter"
);
let elem_type = fun_id.inst.get(0).unwrap();
let elem_type = fun_id.inst.first().unwrap();
let elem_type_size = ctx.type_size(elem_type);

emitln!(ctx.writer, "(v_ref) -> e {");
Expand Down Expand Up @@ -689,7 +689,7 @@ fn define_push_back_fun(
1,
"vector instantiated with non-one type parameter"
);
let elem_type = fun_id.inst.get(0).unwrap();
let elem_type = fun_id.inst.first().unwrap();
let elem_type_size = ctx.type_size(elem_type);

emitln!(ctx.writer, "(v_ref, e) {");
Expand Down Expand Up @@ -864,7 +864,7 @@ fn define_push_back_fun(
}

fn define_swap_fun(gen: &mut FunctionGenerator, ctx: &Context, fun_id: &QualifiedInstId<FunId>) {
let elem_type = fun_id.inst.get(0).unwrap();
let elem_type = fun_id.inst.first().unwrap();
let elem_type_size = ctx.type_size(elem_type);
emitln!(ctx.writer, "(v_ref, i, j) {");
ctx.writer.indent();
Expand Down Expand Up @@ -994,7 +994,7 @@ fn define_destroy_empty_fun(
);
emitln!(ctx.writer, "(v) {");
ctx.writer.indent();
let type_size = ctx.type_size(fun_id.inst.get(0).unwrap());
let type_size = ctx.type_size(fun_id.inst.first().unwrap());
emitln!(
ctx.writer,
"let size := {}",
Expand Down
6 changes: 3 additions & 3 deletions language/move-analyzer/src/symbols.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ impl UseDef {

references
.entry(def_loc)
.or_insert_with(BTreeSet::new)
.or_default()
.insert(use_loc);
Self {
col_start: use_start.character,
Expand Down Expand Up @@ -560,7 +560,7 @@ impl UseDefMap {
}

fn insert(&mut self, key: u32, val: UseDef) {
self.0.entry(key).or_insert_with(BTreeSet::new).insert(val);
self.0.entry(key).or_default().insert(val);
}

fn get(&self, key: u32) -> Option<BTreeSet<UseDef>> {
Expand Down Expand Up @@ -595,7 +595,7 @@ impl Symbols {
for (k, v) in other.references {
self.references
.entry(k)
.or_insert_with(BTreeSet::new)
.or_default()
.extend(v);
}
self.file_use_defs.extend(other.file_use_defs);
Expand Down
45 changes: 45 additions & 0 deletions language/move-binary-format/src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,37 @@ pub trait ModuleAccess: Sync {
.collect()
}

/// Returns an iterator that iterates over all immediate dependencies of the module.
///
/// This is more efficient than `immediate_dependencies` as it does not make new
/// copies of module ids on the heap.
fn immediate_dependencies_iter(
&self,
) -> impl DoubleEndedIterator<Item = (&AccountAddress, &IdentStr)> {
self.module_handles()
.iter()
.filter(|&handle| handle != self.self_handle())
.map(|handle| {
let addr = self.address_identifier_at(handle.address);
let name = self.identifier_at(handle.name);
(addr, name)
})
}

/// Returns an iterator that iterates over all immediate friends of the module.
///
/// This is more efficient than `immediate_dependencies` as it does not make new
/// copies of module ids on the heap.
fn immediate_friends_iter(
&self,
) -> impl DoubleEndedIterator<Item = (&AccountAddress, &IdentStr)> {
self.friend_decls().iter().map(|handle| {
let addr = self.address_identifier_at(handle.address);
let name = self.identifier_at(handle.name);
(addr, name)
})
}

fn find_struct_def(&self, idx: StructHandleIndex) -> Option<&StructDefinition> {
self.struct_defs().iter().find(|d| d.struct_handle == idx)
}
Expand Down Expand Up @@ -294,6 +325,20 @@ pub trait ScriptAccess: Sync {
})
.collect()
}

/// Returns an iterator that iterates over all immediate dependencies of the module.
///
/// This is more efficient than `immediate_dependencies` as it does not make new
/// copies of module ids on the heap.
fn immediate_dependencies_iter(
&self,
) -> impl DoubleEndedIterator<Item = (&AccountAddress, &IdentStr)> {
self.module_handles().iter().map(|handle| {
let addr = self.address_identifier_at(handle.address);
let name = self.identifier_at(handle.name);
(addr, name)
})
}
}

impl ModuleAccess for CompiledModule {
Expand Down
4 changes: 2 additions & 2 deletions language/move-bytecode-verifier/src/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,8 @@ impl Default for VerifierConfig {
max_back_edges_per_function: None,
max_back_edges_per_module: None,
max_basic_blocks_in_script: None,
/// General metering for the verifier. This defaults to a bound which should align
/// with production, so all existing test cases apply it.
// General metering for the verifier. This defaults to a bound which should align
// with production, so all existing test cases apply it.
max_per_fun_meter_units: Some(1000 * 8000),
max_per_mod_meter_units: Some(1000 * 8000),
}
Expand Down
15 changes: 14 additions & 1 deletion language/move-core/types/src/account_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@

use bech32::ToBase32;
use hex::FromHex;
use rand::{rngs::OsRng, Rng};
use openrpc_schema::schemars::{
gen::SchemaGenerator,
schema::{InstanceType, Schema, SchemaObject},
JsonSchema,
};
use rand::{rngs::OsRng, Rng};
use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer};
use std::{convert::TryFrom, fmt, str::FromStr};

Expand Down Expand Up @@ -76,6 +76,19 @@ impl AccountAddress {
Self(buf)
}

/// Returns whether the address is a "special" address. Addresses are considered
/// special if the first 63 characters of the hex string are zero. In other words,
/// an address is special if the first 31 bytes are zero and the last byte is
/// smaller than than `0b10000` (16). In other words, special is defined as an address
/// that matches the following regex: `^0x0{63}[0-9a-f]$`. In short form this means
/// the addresses in the range from `0x0` to `0xf` (inclusive) are special.
///
/// For more details see the v1 address standard defined as part of AIP-40:
/// <https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-40.md>
pub fn is_special(&self) -> bool {
self.0[..Self::LENGTH - 1].iter().all(|x| *x == 0) && self.0[Self::LENGTH - 1] < 0b10000
}

/// Return a canonical string representation of the address
/// Addresses are hex-encoded lowercase values of length ADDRESS_LENGTH (16, 20, or 32 depending on the Move platform)
/// e.g., 0000000000000000000000000000000a, *not* 0x0000000000000000000000000000000a, 0xa, or 0xA
Expand Down
2 changes: 1 addition & 1 deletion language/move-model/src/builder/exp_translator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ impl<'env, 'translator, 'module_translator> ExpTranslator<'env, 'translator, 'mo
node_counter_start,
accessed_locals: BTreeSet::new(),
outer_context_scopes: 0,
/// Following flags used to translate pure Move functions.
// Following flags used to translate pure Move functions.
translating_fun_as_spec_fun: false,
errors_generated: RefCell::new(false),
called_spec_funs: BTreeSet::new(),
Expand Down
3 changes: 3 additions & 0 deletions language/move-model/src/builder/model_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ pub(crate) struct StructEntry {
#[derive(Debug, Clone)]
pub(crate) struct FunEntry {
pub loc: Loc,
pub id_loc: Loc,
pub module_id: ModuleId,
pub fun_id: FunId,
pub visibility: FunctionVisibility,
Expand Down Expand Up @@ -269,6 +270,7 @@ impl<'env> ModelBuilder<'env> {
pub fn define_fun(
&mut self,
loc: Loc,
id_loc: Loc,
attributes: Vec<Attribute>,
name: QualifiedSymbol,
module_id: ModuleId,
Expand All @@ -281,6 +283,7 @@ impl<'env> ModelBuilder<'env> {
) {
let entry = FunEntry {
loc,
id_loc,
attributes,
module_id,
fun_id,
Expand Down
4 changes: 4 additions & 0 deletions language/move-model/src/builder/module_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use move_compiler::{
parser::ast as PA,
shared::{unique_map::UniqueMap, Name},
};
use move_compiler::shared::Identifier;
use move_ir_types::{ast::ConstantName, location::Spanned};

use crate::{
Expand Down Expand Up @@ -427,8 +428,10 @@ impl<'env, 'translator> ModuleBuilder<'env, 'translator> {
EA::Visibility::Internal => FunctionVisibility::Private,
};
let loc = et.to_loc(&def.loc);
let id_loc = et.to_loc(&name.loc());
et.parent.parent.define_fun(
loc.clone(),
id_loc,
attrs,
qsym.clone(),
et.parent.module_id,
Expand Down Expand Up @@ -3191,6 +3194,7 @@ impl<'env, 'translator> ModuleBuilder<'env, 'translator> {
def_idx,
name,
entry.loc.clone(),
entry.id_loc.clone(),
entry.attributes.clone(),
arg_names,
type_arg_names,
Expand Down
11 changes: 11 additions & 0 deletions language/move-model/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1169,6 +1169,7 @@ impl GlobalEnv {
def_idx: FunctionDefinitionIndex,
name: Symbol,
loc: Loc,
id_loc: Loc,
attributes: Vec<Attribute>,
arg_names: Vec<Symbol>,
type_arg_names: Vec<Symbol>,
Expand All @@ -1178,6 +1179,7 @@ impl GlobalEnv {
FunctionData {
name,
loc,
id_loc,
attributes,
def_idx,
handle_idx,
Expand Down Expand Up @@ -2925,6 +2927,9 @@ pub struct FunctionData {
/// Location of this function.
loc: Loc,

/// Location of the function identifier, suitable for error messages alluding to the function.
id_loc: Loc,

/// The definition index of this function in its module.
def_idx: FunctionDefinitionIndex,

Expand Down Expand Up @@ -2963,6 +2968,7 @@ impl FunctionData {
FunctionData {
name,
loc: Loc::default(),
id_loc: Loc::default(),
attributes: Vec::default(),
def_idx,
handle_idx,
Expand Down Expand Up @@ -3037,6 +3043,11 @@ impl<'env> FunctionEnv<'env> {
self.data.loc.clone()
}

/// Returns the location of this function identifier.
pub fn get_id_loc(&self) -> Loc {
self.data.id_loc.clone()
}

/// Returns the attributes of this function.
pub fn get_attributes(&self) -> &[Attribute] {
&self.data.attributes
Expand Down
Loading

0 comments on commit 905484b

Please sign in to comment.