Skip to content

Commit

Permalink
feat: print works in soroban
Browse files Browse the repository at this point in the history
Signed-off-by: salaheldinsoliman <[email protected]>
  • Loading branch information
salaheldinsoliman committed Jul 24, 2024
1 parent 06798cd commit 2bbba8e
Show file tree
Hide file tree
Showing 5 changed files with 241 additions and 34 deletions.
59 changes: 35 additions & 24 deletions src/codegen/dispatch/soroban.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,35 +102,46 @@ pub fn function_dispatch(

wrapper_cfg.add(&mut vartab, placeholder);

// set the msb 8 bits of the return value to 6, the return value is 64 bits.
// FIXME: this assumes that the solidity function always returns one value.
let shifted = Expression::ShiftLeft {
loc: pt::Loc::Codegen,
ty: Type::Uint(64),
left: value[0].clone().into(),
right: Expression::NumberLiteral {
if value.len() == 1 {
// set the msb 8 bits of the return value to 6, the return value is 64 bits.
// FIXME: this assumes that the solidity function always returns one value.
let shifted = Expression::ShiftLeft {
loc: pt::Loc::Codegen,
ty: Type::Uint(64),
value: BigInt::from(8_u64),
}
.into(),
};
left: value[0].clone().into(),
right: Expression::NumberLiteral {
loc: pt::Loc::Codegen,
ty: Type::Uint(64),
value: BigInt::from(8_u64),
}
.into(),
};

let tag = Expression::NumberLiteral {
loc: pt::Loc::Codegen,
ty: Type::Uint(64),
value: BigInt::from(6_u64),
};
let tag = Expression::NumberLiteral {
loc: pt::Loc::Codegen,
ty: Type::Uint(64),
value: BigInt::from(6_u64),
};

let added = Expression::Add {
loc: pt::Loc::Codegen,
ty: Type::Uint(64),
overflowing: false,
left: shifted.into(),
right: tag.into(),
};
let added = Expression::Add {
loc: pt::Loc::Codegen,
ty: Type::Uint(64),
overflowing: false,
left: shifted.into(),
right: tag.into(),
};

wrapper_cfg.add(&mut vartab, Instr::Return { value: vec![added] });
} else {
// return 2 as numberliteral
let two = Expression::NumberLiteral {
loc: pt::Loc::Codegen,
ty: Type::Uint(64),
value: BigInt::from(2_u64),
};

wrapper_cfg.add(&mut vartab, Instr::Return { value: vec![added] });
wrapper_cfg.add(&mut vartab, Instr::Return { value: vec![two] });
}

vartab.finalize(ns, &mut wrapper_cfg);
cfg.public = false;
Expand Down
54 changes: 52 additions & 2 deletions src/emit/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ use inkwell::{AddressSpace, IntPredicate};
use num_bigint::Sign;
use num_traits::ToPrimitive;
use std::collections::HashMap;
use std::ops::Deref;
use inkwell::types::BasicTypeEnum;

/// The expression function recursively emits code for expressions. The BasicEnumValue it
/// returns depends on the context; if it is simple integer, bool or bytes32 expression, the value
Expand Down Expand Up @@ -1198,6 +1200,7 @@ pub(super) fn expression<'a, T: TargetRuntime<'a> + ?Sized>(
expr,
..
} => {
println!("bytes cast");
let e = expression(target, bin, expr, vartab, function, ns).into_int_value();

let size = e.get_type().get_bit_width() / 8;
Expand Down Expand Up @@ -1538,7 +1541,12 @@ pub(super) fn expression<'a, T: TargetRuntime<'a> + ?Sized>(
initializer,
..
} => {
if matches!(ty, Type::Slice(_)) {
println!("alloc dynamic bytes");
println!("TYYY {:?}", ty);
println!("SIZE {:?}", size);
println!("INITIALIZER {:?}", initializer);
if matches!(ty, Type::Slice(_)) {
println!("ty is slice");
let init = initializer.as_ref().unwrap();

let data = bin.emit_global_string("const_string", init, true);
Expand All @@ -1553,7 +1561,49 @@ pub(super) fn expression<'a, T: TargetRuntime<'a> + ?Sized>(
.into(),
])
.into()
} else {
}
else if let Expression::NumberLiteral{loc, ty, value} = size.clone().deref() {


//matches!(size.clone().deref(), Expression::NumberLiteral{loc, ty: sesa, value}) {

println!("size is number literal");
println!("ty {:?}", ty);

let init = initializer.as_ref().unwrap();

let data = bin.emit_global_string("const_string", init, true);


let typee = BasicTypeEnum::StructType(
bin.context.struct_type(
&[
bin.llvm_type(ty, ns)
.ptr_type(AddressSpace::default())
.into(),
bin.context
.custom_width_int_type(ns.target.ptr_size().into())
.into(),
],
false,
),
).into_struct_type();

println!("typee {:?}", typee);



typee.const_named_struct(&[
data.into(),
bin.context
.custom_width_int_type(ns.target.ptr_size().into())
.const_int(init.len() as u64, false)
.into(),
])
.into()

}
else {
let elem = match ty {
Type::Slice(_) | Type::String | Type::DynamicBytes => Type::Bytes(1),
_ => ty.array_elem(),
Expand Down
12 changes: 12 additions & 0 deletions src/emit/soroban/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use std::sync;
const SOROBAN_ENV_INTERFACE_VERSION: u64 = 90194313216;
pub const PUT_CONTRACT_DATA: &str = "l._";
pub const GET_CONTRACT_DATA: &str = "l.1";
pub const LOG_FROM_LINEAR_MEMORY: &str = "x._";

pub struct SorobanTarget;

Expand Down Expand Up @@ -231,12 +232,23 @@ impl SorobanTarget {
.i64_type()
.fn_type(&[ty.into(), ty.into()], false);

let log_function_ty = binary
.context
.i64_type()
.fn_type(&[ty.into(), ty.into(), ty.into(), ty.into()], false);

binary
.module
.add_function(PUT_CONTRACT_DATA, function_ty_1, Some(Linkage::External));
binary
.module
.add_function(GET_CONTRACT_DATA, function_ty, Some(Linkage::External));

binary.module.add_function(
LOG_FROM_LINEAR_MEMORY,
log_function_ty,
Some(Linkage::External),
);
}

fn emit_initializer(binary: &mut Binary, _ns: &ast::Namespace) {
Expand Down
144 changes: 139 additions & 5 deletions src/emit/soroban/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

use crate::codegen::cfg::HashTy;
use crate::codegen::Expression;
use crate::emit::binary::Binary;
use crate::emit::soroban::{SorobanTarget, GET_CONTRACT_DATA, PUT_CONTRACT_DATA};
use crate::emit::binary::{self, Binary};
use crate::emit::soroban::{
SorobanTarget, GET_CONTRACT_DATA, LOG_FROM_LINEAR_MEMORY, PUT_CONTRACT_DATA,
};
use crate::emit::ContractArgs;
use crate::emit::{TargetRuntime, Variable};
use crate::emit_context;
Expand All @@ -13,10 +15,11 @@ use crate::sema::ast::{Function, Namespace, Type};

use inkwell::types::{BasicTypeEnum, IntType};
use inkwell::values::{
ArrayValue, BasicMetadataValueEnum, BasicValue, BasicValueEnum, FunctionValue, IntValue,
PointerValue,
AnyValue, ArrayValue, AsValueRef, BasicMetadataValueEnum, BasicValue, BasicValueEnum,
FunctionValue, IntValue, PointerValue,
};

use inkwell::AddressSpace;
use solang_parser::pt::Loc;

use std::collections::HashMap;
Expand Down Expand Up @@ -236,7 +239,138 @@ impl<'a> TargetRuntime<'a> for SorobanTarget {

/// Prints a string
/// TODO: Implement this function, with a call to the `log` function in the Soroban runtime.
fn print(&self, bin: &Binary, string: PointerValue, length: IntValue) {}
fn print(&self, bin: &Binary, string: PointerValue, length: IntValue) {
if string.is_const() && length.is_const() {
println!("msg_pos: {:?}", string);
println!("length: {:?}", length);

let msg_pos = bin
.builder
.build_ptr_to_int(string, bin.context.i64_type(), "msg_pos")
.unwrap();
let msg_pos = msg_pos.const_cast(bin.context.i64_type(), false);

println!("msg_pos extracted: {:?}", msg_pos);
println!("=============================================================");

let length = length.const_cast(bin.context.i64_type(), false);

let eight = bin.context.i64_type().const_int(8, false);
let four = bin.context.i64_type().const_int(4, false);
let zero = bin.context.i64_type().const_int(0, false);
let thirty_two = bin.context.i64_type().const_int(32, false);

// encode msg_pos and length
let msg_pos_encoded = bin
.builder
.build_left_shift(msg_pos, thirty_two, "temp")
.unwrap();
let msg_pos_encoded = bin
.builder
.build_int_add(msg_pos_encoded, four, "msg_pos_encoded")
.unwrap();

let length_encoded = bin
.builder
.build_left_shift(length, thirty_two, "temp")
.unwrap();
let length_encoded = bin
.builder
.build_int_add(length_encoded, four, "length_encoded")
.unwrap();

let zero_encoded = bin.builder.build_left_shift(zero, eight, "temp").unwrap();

let eight_encoded = bin.builder.build_left_shift(eight, eight, "temp").unwrap();
let eight_encoded = bin
.builder
.build_int_add(eight_encoded, four, "eight_encoded")
.unwrap();

let call_res = bin
.builder
.build_call(
bin.module.get_function(LOG_FROM_LINEAR_MEMORY).unwrap(),
&[
msg_pos_encoded.into(),
length_encoded.into(),
msg_pos_encoded.into(),
four.into(),
],
"log",
)
.unwrap();
} else {
println!("in else: ");

println!("msg_pos: {:?}", string);
println!("length: {:?}", length);


/*println!("msg_pos: {:?}", string);
println!("length: {:?}", length);
let msg_pos = bin.builder.build_ptr_to_int(string, bin.context.i64_type(), "msg_pos").unwrap();
//let msg_pos = msg_pos.const_cast(bin.context.i64_type(), false);
println!("msg_pos extracted: {:?}", msg_pos);
println!("=============================================================");
//let length = length.const_cast(bin.context.i64_type(), false);
let eight = bin.context.i64_type().const_int(8, false);
let four = bin.context.i64_type().const_int(4, false);
let zero = bin.context.i64_type().const_int(0, false);
let thirty_two = bin.context.i64_type().const_int(32, false);
// encode msg_pos and length
let msg_pos_encoded = bin.builder.build_left_shift(msg_pos, thirty_two, "temp").unwrap();
let msg_pos_encoded = bin.builder.build_int_add(msg_pos_encoded, four, "msg_pos_encoded").unwrap();
println!("CAN MSG ENCODE");
//let length = bin.builder.build_int_z_extend(length, bin.context.i64_type(), "extended").unwrap();
let length_type = length.get_type();
println!("LENGTH TYPE: {:?}", length_type);
//let length = bin.builder.build_int_z_extend(length, bin.context.i64_type(), "extended").unwrap();
//let length = bin.builder.build_int_cast(length, bin.context.i64_type(), "extended").unwrap();
let length_encoded = bin.builder.build_left_shift(length, thirty_two, "temp").unwrap();
let length_encoded = bin.builder.build_int_add(length_encoded, four, "length_encoded").unwrap();
println!("CAN LENGTH ENCODE");
let zero_encoded = bin.builder.build_left_shift(zero, eight, "temp").unwrap();
let eight_encoded = bin.builder.build_left_shift(eight, eight, "temp").unwrap();
let eight_encoded = bin.builder.build_int_add(eight_encoded, four, "eight_encoded").unwrap();
let call_res = bin.builder.build_call(
bin.module.get_function(LOG_FROM_LINEAR_MEMORY).unwrap(),
&[
msg_pos_encoded.into(),
length_encoded.into(),
msg_pos_encoded.into(),
four.into(),
],
"log",
).unwrap();
*/
}
}

/// Return success without any result
fn return_empty_abi(&self, bin: &Binary) {
Expand Down
6 changes: 3 additions & 3 deletions src/linker/soroban_wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ use wasm_encoder::{
};
use wasmparser::{Global, Import, Parser, Payload::*, SectionLimited, TypeRef};

use crate::emit::soroban::GET_CONTRACT_DATA;
use crate::emit::soroban::PUT_CONTRACT_DATA;
use crate::emit::soroban::{GET_CONTRACT_DATA, LOG_FROM_LINEAR_MEMORY, PUT_CONTRACT_DATA};

pub fn link(input: &[u8], name: &str) -> Vec<u8> {
let dir = tempdir().expect("failed to create temp directory for linking");
Expand Down Expand Up @@ -82,7 +81,7 @@ fn generate_module(input: &[u8]) -> Vec<u8> {
module.finish()
}

/// Resolve all pallet contracts runtime imports
/// Resolve all soroban contracts runtime imports
fn generate_import_section(section: SectionLimited<Import>, module: &mut Module) {
let mut imports = ImportSection::new();
for import in section.into_iter().map(|import| import.unwrap()) {
Expand All @@ -98,6 +97,7 @@ fn generate_import_section(section: SectionLimited<Import>, module: &mut Module)
};
let module_name = match import.name {
GET_CONTRACT_DATA | PUT_CONTRACT_DATA => "l",
LOG_FROM_LINEAR_MEMORY => "x",
_ => panic!("got func {:?}", import),
};
// parse the import name to all string after the the first dot
Expand Down

0 comments on commit 2bbba8e

Please sign in to comment.