Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix, forc build -o, and forc parse-bytecode #68

Merged
merged 8 commits into from
Jun 2, 2021
Merged
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
21 changes: 17 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion core_lang/src/asm_generation/finalized_asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ fn to_bytecode<'sc>(
// The below invariant is introduced to word-align the data section.
// A noop is inserted in ASM generation if there is an odd number of ops.
assert_eq!(program_section.ops.len() & 1, 0);
let offset_to_data_section = (program_section.ops.len() * 4) as u64;
// this points at the byte (*4*8) address immediately following (+1) the last instruction
let offset_to_data_section = ((program_section.ops.len() + 1) * 4) as u64;

// each op is four bytes, so the length of the buf is then number of ops times four.
let mut buf = vec![0; (program_section.ops.len() * 4) + 4];
Expand Down
3 changes: 1 addition & 2 deletions example_project/fuel_project/src/main.sw
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
predicate;
script;
struct Rgb {
red: u64,
green: u64,
Expand Down Expand Up @@ -63,4 +63,3 @@ fn main() {
trait Color {
fn rgb(self) -> Rgb;
}

2 changes: 2 additions & 0 deletions forc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ structopt = "0.3"
termcolor = "1.1"
toml = "0.5"
whoami = "1.1"
fuel-asm = { git = "ssh://[email protected]/FuelLabs/fuel-asm.git" }
term-table = "1.3"
17 changes: 8 additions & 9 deletions forc/src/cli/commands/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,18 @@ use structopt::{self, StructOpt};

use crate::ops::forc_build;
#[derive(Debug, StructOpt)]
pub(crate) struct Command {
pub struct Command {
#[structopt(short = "p")]
pub path: Option<String>,
/// Whether to compile to bytecode (false) or to print out the generated ASM (true).
#[structopt(long = "asm")]
pub asm: bool,
#[structopt(long = "print-asm")]
pub print_asm: bool,
/// Whether to output a binary file representing the script bytes
#[structopt(short = "o")]
pub binary_outfile: Option<String>,
}

pub(crate) fn exec(command: Command) -> Result<(), String> {
if command.asm {
forc_build::print_asm(command.path)
} else {
forc_build::build(command.path)?;
Ok(())
}
forc_build::build(command)?;
Ok(())
}
1 change: 1 addition & 0 deletions forc/src/cli/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod build;
pub mod coverage;
pub mod deploy;
pub mod init;
pub mod parse_bytecode;
pub mod publish;
pub mod serve;
pub mod test;
77 changes: 77 additions & 0 deletions forc/src/cli/commands/parse_bytecode.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use std::convert::TryInto;
use std::fs::{self, File};
use std::io::Read;
use structopt::{self, StructOpt};
use term_table::row::Row;
use term_table::table_cell::{Alignment, TableCell};

#[derive(Debug, StructOpt)]
pub(crate) struct Command {
file_path: String,
}

/// Parses the bytecode into a debug format.
pub(crate) fn exec(command: Command) -> Result<(), String> {
let mut f = File::open(&command.file_path)
.map_err(|_| format!("{}: file not found", command.file_path))?;
let metadata = fs::metadata(&command.file_path)
.map_err(|_| format!("{}: file not found", command.file_path))?;
let mut buffer = vec![0; metadata.len() as usize];
f.read(&mut buffer).expect("buffer overflow");
let mut instructions = vec![];

for i in (0..buffer.len() - 4).step_by(4) {
let i = i as usize;
let raw = &buffer[i..i + 4];
let op = fuel_asm::Opcode::from_bytes_unchecked(raw.try_into().unwrap());
instructions.push((raw, op));
}
// println!("word\tbyte\top\t\traw\tnotes");
let mut table = term_table::Table::new();
table.add_row(Row::new(vec![
TableCell::new("half-word"),
TableCell::new("byte"),
TableCell::new("op"),
TableCell::new("raw"),
TableCell::new("notes"),
]));
table.style = term_table::TableStyle::blank();
for (word_ix, instruction) in instructions.iter().enumerate() {
use fuel_asm::Opcode::*;
let notes = match instruction.1 {
JI(num) => match instructions.get(num as usize) {
Some(op) => format!("jumps to {:?}", op.1),
None => format!("invalid jump: destination out of range"),
},
JNEI(_, _, num) => match instructions.get(num as usize) {
Some(op) => format!("conditionally jumps to {:?}", op.1),
None => format!("invalid jump: destination out of range"),
},
Undefined if word_ix == 2 || word_ix == 3 => {
let parsed_raw = u32::from_be_bytes([
instruction.0[0],
instruction.0[1],
instruction.0[2],
instruction.0[3],
]);
format!(
"data section offset {} ({})",
if word_ix == 2 { "lo" } else { "hi" },
parsed_raw
)
}
_ => "".into(),
};
table.add_row(Row::new(vec![
TableCell::new_with_alignment(word_ix, 1, Alignment::Right),
TableCell::new(word_ix * 4),
TableCell::new(format!("{:?}", instruction.1)),
TableCell::new(format!("{:?}", instruction.0)),
TableCell::new(notes),
]));
}

println!("{}", table.render());

Ok(())
}
9 changes: 7 additions & 2 deletions forc/src/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
use structopt::StructOpt;

mod commands;
use self::commands::{analysis, benchmark, build, coverage, deploy, init, publish, serve, test};
use self::commands::{
analysis, benchmark, build, coverage, deploy, init, parse_bytecode, publish, serve, test,
};

use analysis::Command as AnalysisCommand;
use benchmark::Command as BenchmarkCommand;
use build::Command as BuildCommand;
pub use build::Command as BuildCommand;
use coverage::Command as CoverageCommand;
use deploy::Command as DeployCommand;
use init::Command as InitCommand;
use parse_bytecode::Command as ParseBytecodeCommand;
use publish::Command as PublishCommand;
use serve::Command as ServeCommand;
use test::Command as TestCommand;
Expand All @@ -32,6 +35,7 @@ enum Forc {
Publish(PublishCommand),
Serve(ServeCommand),
Test(TestCommand),
ParseBytecode(ParseBytecodeCommand),
}

pub(crate) fn run_cli() -> Result<(), String> {
Expand All @@ -46,6 +50,7 @@ pub(crate) fn run_cli() -> Result<(), String> {
Forc::Publish(command) => publish::exec(command),
Forc::Serve(command) => serve::exec(command),
Forc::Test(command) => test::exec(command),
Forc::ParseBytecode(command) => parse_bytecode::exec(command),
}?;
/*
let content = fs::read_to_string(opt.input.clone())?;
Expand Down
2 changes: 1 addition & 1 deletion forc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![allow(dead_code)]
mod cli;
pub mod cli;
pub mod ops;
mod utils;

Expand Down
21 changes: 17 additions & 4 deletions forc/src/ops/forc_build.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use crate::cli::BuildCommand;
use line_col::LineColLookup;
use source_span::{
fmt::{Color, Formatter, Style},
Position, Span,
};
use std::fs::File;
use std::io::{self, Write};
use termcolor::{BufferWriter, Color as TermColor, ColorChoice, ColorSpec, WriteColor};

Expand Down Expand Up @@ -39,14 +41,16 @@ pub fn print_asm(path: Option<String>) -> Result<(), String> {

// now, compile this program with all of its dependencies
let main_file = get_main_file(&manifest, &manifest_dir)?;
let main = compile_to_asm(main_file, &manifest.project.name, &namespace)?;

println!("{}", main);

Ok(())
}

pub fn build(path: Option<String>) -> Result<Vec<u8>, String> {
pub fn build(command: BuildCommand) -> Result<Vec<u8>, String> {
let BuildCommand {
path,
binary_outfile,
print_asm,
} = command;
// find manifest directory, even if in subdirectory
let this_dir = if let Some(path) = path {
PathBuf::from(path)
Expand Down Expand Up @@ -78,7 +82,16 @@ pub fn build(path: Option<String>) -> Result<Vec<u8>, String> {

// now, compile this program with all of its dependencies
let main_file = get_main_file(&manifest, &manifest_dir)?;
if print_asm {
let main = compile_to_asm(main_file, &manifest.project.name, &namespace)?;
println!("{}", main);
}

let main = compile(main_file, &manifest.project.name, &namespace)?;
if let Some(outfile) = binary_outfile {
let mut file = File::create(outfile).map_err(|e| e.to_string())?;
file.write_all(main.as_slice()).map_err(|e| e.to_string())?;
}

println!("Bytecode size is {} bytes.", main.len());

Expand Down
23 changes: 10 additions & 13 deletions test_suite/src/e2e_vm_tests/harness.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use forc;
use forc::cli::BuildCommand;

use fuel_core::interpreter::Interpreter;
use fuel_tx::Transaction;
Expand Down Expand Up @@ -34,17 +35,13 @@ pub(crate) fn runs_in_vm(file_name: &str) {
pub(crate) fn compile_to_bytes(file_name: &str) -> Vec<u8> {
println!("Compiling {}", file_name);
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let res = forc::ops::forc_build::build(Some(format!(
"{}/src/e2e_vm_tests/test_programs/{}",
manifest_dir, file_name
)));
match res {
Ok(bytes) => bytes,
Err(_) => {
panic!(
"TEST FAILURE: Project \"{}\" failed to compile. ",
file_name
);
}
}
forc::ops::forc_build::build(BuildCommand {
path: Some(format!(
"{}/src/e2e_vm_tests/test_programs/{}",
manifest_dir, file_name
)),
print_asm: false,
binary_outfile: None,
})
.unwrap()
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ script;
// This test tests two-pass compilation and allowing usages before declarations.

fn main() -> bool {
let a = 42;
// fn before decl
let x = the_number_five();
// enum before decl
Expand Down