Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ license = "Apache-2.0"
build = "build.rs"
description = "Solang Solidity Compiler"
keywords = [ "solidity", "compiler", "solana", "polkadot", "substrate" ]
rust-version = "1.85.0"
rust-version = "1.87"
edition = "2021"
exclude = [ "/.*", "/docs", "/solana-library", "/tests", "/integration", "/vscode", "/testdata" ]

Expand Down Expand Up @@ -72,6 +72,7 @@ solang-forge-fmt = { version = "0.2.0", optional = true }
# build to work.
ethers-core = { version = "2.0.10", optional = true }
soroban-sdk = { version = "23.0.0-rc.2.2", features = ["testutils"], optional = true }
miden-vm = "=0.16.0"

[dev-dependencies]
num-derive = "0.4"
Expand Down
3 changes: 2 additions & 1 deletion src/bin/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ pub struct TargetArg {

#[derive(Args, Deserialize, Debug, PartialEq)]
pub struct CompileTargetArg {
#[arg(name = "TARGET", long = "target", value_parser = ["solana", "polkadot", "evm", "soroban"], help = "Target to build for [possible values: solana, polkadot]", num_args = 1, hide_possible_values = true)]
#[arg(name = "TARGET", long = "target", value_parser = ["solana", "polkadot", "evm", "soroban", "miden"], help = "Target to build for [possible values: solana, polkadot]", num_args = 1, hide_possible_values = true)]
pub name: Option<String>,

#[arg(name = "ADDRESS_LENGTH", help = "Address length on the Polkadot Parachain", long = "address-length", num_args = 1, value_parser = value_parser!(u64).range(4..1024))]
Expand Down Expand Up @@ -469,6 +469,7 @@ pub(crate) fn target_arg<T: TargetArgTrait>(target_arg: &T) -> Target {
},
"evm" => solang::Target::EVM,
"soroban" => solang::Target::Soroban,
"miden" => solang::Target::Miden,
_ => unreachable!(),
};

Expand Down
24 changes: 24 additions & 0 deletions src/codegen/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,12 @@ pub struct ControlFlowGraph {
pub array_lengths_temps: ArrayLengthVars,
/// Is this a modifier dispatch for which function number?
pub modifier: Option<usize>,

// POC(miden): mimic the miden target stack
pub miden_stack: Vec<String>,

// POC(miden): hold the miden instructions
pub miden_instrs: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand Down Expand Up @@ -495,6 +501,8 @@ impl ControlFlowGraph {
current: 0,
array_lengths_temps: IndexMap::new(),
modifier: None,
miden_stack: Vec::new(),
miden_instrs: Vec::new(),
};

cfg.new_basic_block("entry".to_string());
Expand All @@ -518,6 +526,8 @@ impl ControlFlowGraph {
current: 0,
array_lengths_temps: IndexMap::new(),
modifier: None,
miden_stack: Vec::new(),
miden_instrs: Vec::new(),
}
}

Expand Down Expand Up @@ -622,6 +632,16 @@ impl ControlFlowGraph {
}
}

/// POC(miden): Push value to miden stack
pub fn push_to_miden_stack(&mut self, value: String) {
self.miden_instrs.push(format!(" push.{}", value));
}

/// POC(miden): Push instr to miden instrs
pub fn push_miden_instr(&mut self, instr: String) {
self.miden_instrs.push(format!(" {}", instr));
}

pub fn expr_to_string(&self, contract: &Contract, ns: &Namespace, expr: &Expression) -> String {
match expr {
Expression::FunctionArg { arg_no, .. } => format!("(arg #{arg_no})"),
Expand Down Expand Up @@ -1819,6 +1839,10 @@ fn function_cfg(
None => pt::Loc::Codegen,
};
// add implicit return

// POC(Miden): for miden, the return instr returns the data on the stack
cfg.push_miden_instr("exec.sys::truncate_stack".to_string());

cfg.add(
&mut vartab,
Instr::Return {
Expand Down
1 change: 1 addition & 0 deletions src/codegen/dispatch/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ pub(super) fn function_dispatch(
polkadot::function_dispatch(contract_no, all_cfg, ns, opt)
}
Target::Soroban => soroban::function_dispatch(contract_no, all_cfg, ns, opt),
Target::Miden => Vec::new(),
}
}
2 changes: 1 addition & 1 deletion src/codegen/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ pub(super) fn new_event_emitter<'a>(
event_no,
}),

Target::Soroban => todo!(),
Target::Soroban | Target::Miden => todo!(),
}
}
38 changes: 36 additions & 2 deletions src/codegen/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1327,6 +1327,11 @@ fn post_incdec(
if ns.target == Target::Soroban {
value = soroban_encode_arg(value, cfg, vartab, ns);
}
// Poc(miden): For miden, set storage is "exec.account::set_item" and it expects the value to be
// on the stack top
let slot_miden_expr = dest.clone().to_miden_expr();
cfg.push_to_miden_stack(format!("STORAGE_SLOT_{}", slot_miden_expr));
cfg.push_miden_instr("exec.account::set_item".to_string());

cfg.add(
vartab,
Expand Down Expand Up @@ -1456,6 +1461,12 @@ fn pre_incdec(
value = soroban_encode_arg(value, cfg, vartab, ns)
}

// Poc(miden): For miden, set storage is "exec.account::set_item" and it expects the value to be
// on the stack top
let slot_miden_expr = dest.clone().to_miden_expr();
cfg.push_to_miden_stack(format!("STORAGE_SLOT_{}", slot_miden_expr));
cfg.push_miden_instr("exec.account::set_item".to_string());

cfg.add(
vartab,
Instr::SetStorage {
Expand Down Expand Up @@ -2920,12 +2931,20 @@ fn add(
right: &ast::Expression,
opt: &Options,
) -> Expression {
let right = Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt));
let left = Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt));

// POC(miden): Add expects the first argument to be on the stack top, and the second argument is provided as immediate
let miden_instr = format!("add.{}", right.clone().to_miden_expr());
cfg.push_miden_instr(miden_instr);
//cfg.miden_instrs.push(miden_instr);

Expression::Add {
loc: *loc,
ty: ty.clone(),
overflowing,
left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
left,
right,
}
}

Expand Down Expand Up @@ -3262,6 +3281,11 @@ pub fn assign_single(
value = soroban_encode_arg(value, cfg, vartab, ns);
}

// POC(miden): Push the storage slot to the Miden stack before the set_item call
let slot_miden_expr = dest.clone().to_miden_expr();
cfg.push_to_miden_stack(format!("STORAGE_SLOT_{}", slot_miden_expr));
cfg.push_miden_instr("exec.account::set_item".to_string());

cfg.add(
vartab,
Instr::SetStorage {
Expand Down Expand Up @@ -3797,6 +3821,7 @@ fn array_subscript(
ty: array_ty.clone(),
exprs: vec![array, index],
},
Target::Miden => unimplemented!(),
};
}

Expand Down Expand Up @@ -4192,6 +4217,15 @@ pub fn load_storage(
) -> Expression {
let res = vartab.temp_anonymous(ty);

//POC(Miden): storage load in miden is "exec.account::get_item", and expects the key to be on the stack
let storage_slot_miden_expr = format!("STORAGE_SLOT_{}", storage.clone().to_miden_expr());

// push the storage slot expression onto the stack
cfg.push_to_miden_stack(storage_slot_miden_expr);

// add the storage load instruction
cfg.push_miden_instr("exec.account::get_item".to_string());

cfg.add(
vartab,
Instr::LoadStorage {
Expand Down
12 changes: 12 additions & 0 deletions src/codegen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -950,6 +950,18 @@ impl RetrieveType for Expression {
}

impl Expression {
/// POC(miden): Convert expression to miden expression string
/// This is a very naive implementation and only handles a few cases.
pub fn to_miden_expr(self) -> String {
match self {
Expression::NumberLiteral { value, .. } => value.to_string(),
_ => {
// For unsupported expressions, return a placeholder
"UNSUPPORTED_EXPR".to_string()
}
}
}

/// Increment an expression by some value.
pub(crate) fn add_u32(self, other: Expression) -> Self {
Expression::Add {
Expand Down
3 changes: 3 additions & 0 deletions src/codegen/statements/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,9 @@ fn returns(
.map(|(left, right)| try_load_and_cast(&right.loc(), &right, &left.ty, ns, cfg, vartab))
.collect();

//POC(Miden): for miden, the return instr returns the data on the stack
cfg.push_miden_instr("exec.sys::truncate_stack".to_string());

cfg.add(vartab, Instr::Return { value: cast_values });
}

Expand Down
24 changes: 24 additions & 0 deletions src/emit/binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ use inkwell::OptimizationLevel;
use once_cell::sync::OnceCell;
use solang_parser::pt;

use super::miden;
#[cfg(feature = "soroban")]
use super::soroban;

Expand Down Expand Up @@ -170,6 +171,8 @@ pub struct Binary<'a> {
global_constant_strings: RefCell<HashMap<Vec<u8>, PointerValue<'a>>>,

pub return_data: RefCell<Option<PointerValue<'a>>>,
// POC(Miden): store the generated instructions as strings
pub miden_instrs: Option<RefCell<Vec<String>>>,
}

impl<'a> Binary<'a> {
Expand All @@ -191,6 +194,11 @@ impl<'a> Binary<'a> {
Target::Soroban => {
soroban::SorobanTarget::build(context, &std_lib, contract, ns, opt, _contract_no)
}

Target::Miden => {
miden::Midentarget::build(context, &std_lib, contract, ns, opt, _contract_no)
}

_ => unimplemented!("target not implemented"),
}
}
Expand All @@ -200,6 +208,17 @@ impl<'a> Binary<'a> {
/// each time a bin of this type is created).
/// Pass our module to llvm for optimization and compilation
pub fn code(&self, generate: Generate) -> Result<Vec<u8>, String> {
if self.ns.target == Target::Miden {
return Ok(self
.miden_instrs
.as_ref()
.unwrap()
.borrow()
.join("\n")
.as_bytes()
.to_vec());
}

// return cached result if available
if !self.code.borrow().is_empty() {
return Ok(self.code.borrow().clone());
Expand Down Expand Up @@ -442,6 +461,11 @@ impl<'a> Binary<'a> {
vector_init_empty: context.ptr_type(AddressSpace::default()).const_null(),
global_constant_strings: RefCell::new(HashMap::new()),
return_data: RefCell::new(None),
miden_instrs: if ns.target == Target::Miden {
Some(RefCell::new(Vec::new()))
} else {
None
},
}
}

Expand Down
109 changes: 109 additions & 0 deletions src/emit/miden/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// SPDX-License-Identifier: Apache-2.0

use crate::codegen::cfg::Instr;
use crate::codegen::Expression;
use crate::codegen::{cfg::ControlFlowGraph, Options};

use crate::{emit::Binary, sema::ast};
use inkwell::{context::Context, module::Module};
pub(super) mod target;

pub struct Midentarget;

impl Midentarget {
pub fn build<'a>(
context: &'a Context,
std_lib: &Module<'a>,
contract: &'a ast::Contract,
ns: &'a ast::Namespace,
opt: &'a Options,
_contract_no: usize,
) -> Binary<'a> {
let filename = ns.files[contract.loc.file_no()].file_name();
let mut bin = Binary::new(
context,
ns,
&contract.id.name,
&filename,
opt,
std_lib,
None,
);

// for each cfg, wrap its instructions in a function and copy it to the binary
for cfg in &contract.cfg {
if cfg.name == "storage_initializer" {
Self::emit_storage_initializer(cfg, &mut bin);
continue;
}

if cfg.name.contains("constructor") {
continue;
}

let name = cfg.name.split("::").last().unwrap();
bin.miden_instrs
.as_ref()
.unwrap()
.borrow_mut()
.push(format!("export.{}", name));

for miden_instr in cfg.miden_instrs.iter() {
bin.miden_instrs
.as_ref()
.unwrap()
.borrow_mut()
.push(miden_instr.to_string());
}
bin.miden_instrs
.as_ref()
.unwrap()
.borrow_mut()
.push("end".to_string());
}

bin
}

pub fn emit_storage_initializer(cfg: &ControlFlowGraph, bin: &mut Binary) {
let use_miden_account = "use.miden::account";
let use_miden_sys = "use.std::sys";

bin.miden_instrs
.as_ref()
.unwrap()
.borrow_mut()
.insert(0, use_miden_account.to_string());
bin.miden_instrs
.as_ref()
.unwrap()
.borrow_mut()
.insert(1, use_miden_sys.to_string());

for instr in cfg.blocks[0].instr.iter().enumerate() {
if let Instr::SetStorage {
ty: _ty,
value: _value,
storage,
storage_type: _storage_type,
} = instr.1
{
if let Expression::NumberLiteral {
loc: _loc,
ty: _ty,
value,
} = storage
{
println!("Set storage at slot: {}", value);

let miden_instr = format!("const.STORAGE_SLOT_{}={}", value, value);
bin.miden_instrs
.as_ref()
.unwrap()
.borrow_mut()
.insert(instr.0 + 2, miden_instr);
}
}
}
}
}
Loading
Loading