Skip to content

Commit

Permalink
Move all the sway_to_ir tests from sway_core to the integration t…
Browse files Browse the repository at this point in the history
…ests. (FuelLabs#2211)
  • Loading branch information
otrho authored Jul 4, 2022
1 parent bf23aa4 commit 823707d
Show file tree
Hide file tree
Showing 124 changed files with 1,604 additions and 2,146 deletions.
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.

2 changes: 1 addition & 1 deletion forc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub mod utils;
#[cfg(feature = "test")]
pub mod test {
pub use crate::cli::{BuildCommand, DeployCommand, JsonAbiCommand, RunCommand};
pub use crate::ops::{forc_abi_json, forc_build, forc_deploy, forc_run};
pub use crate::ops::{forc_abi_json, forc_build, forc_check, forc_deploy, forc_run};
}

#[cfg(feature = "util")]
Expand Down
1 change: 0 additions & 1 deletion sway-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ itertools = "0.10"
lazy_static = "1.4"
petgraph = "0.6"
prettydiff = "0.5"
regex = "1"
serde = { version = "1.0", features = ["derive"] }
sha2 = "0.9"
smallvec = "1.7"
Expand Down
25 changes: 13 additions & 12 deletions sway-core/src/asm_generation/from_ir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ use sway_types::{span::Span, Spanned};

use either::Either;

pub fn compile_ir_to_asm(ir: &Context, build_config: &BuildConfig) -> CompileResult<FinalizedAsm> {
pub fn compile_ir_to_asm(
ir: &Context,
build_config: Option<&BuildConfig>,
) -> CompileResult<FinalizedAsm> {
let mut warnings: Vec<CompileWarning> = Vec::new();
let mut errors: Vec<CompileError> = Vec::new();

Expand Down Expand Up @@ -62,7 +65,10 @@ pub fn compile_ir_to_asm(ir: &Context, build_config: &BuildConfig) -> CompileRes
Kind::Library | Kind::Predicate => todo!("libraries and predicates coming soon!"),
};

if build_config.print_intermediate_asm {
if build_config
.map(|cfg| cfg.print_intermediate_asm)
.unwrap_or(false)
{
tracing::info!("{}", asm);
}

Expand All @@ -71,7 +77,10 @@ pub fn compile_ir_to_asm(ir: &Context, build_config: &BuildConfig) -> CompileRes
.allocate_registers(&mut reg_seqr)
.optimize();

if build_config.print_finalized_asm {
if build_config
.map(|cfg| cfg.print_finalized_asm)
.unwrap_or(false)
{
tracing::info!("{}", finalized_asm);
}

Expand Down Expand Up @@ -2463,15 +2472,7 @@ mod tests {
let expected = String::from_utf8_lossy(&expected_bytes);

let ir = parse(&input).expect("parsed ir");
let asm_result = compile_ir_to_asm(
&ir,
&BuildConfig {
canonical_root_module: std::sync::Arc::new("".into()),
print_intermediate_asm: false,
print_finalized_asm: false,
print_ir: true,
},
);
let asm_result = compile_ir_to_asm(&ir, None);

let mut warnings = Vec::new();
let mut errors = Vec::new();
Expand Down
2 changes: 1 addition & 1 deletion sway-core/src/asm_generation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub(crate) mod checks;
pub(crate) mod compiler_constants;
mod data_section;
mod finalized_asm;
pub(crate) mod from_ir;
pub mod from_ir;
mod instruction_set;
mod jump_optimized_asm_set;
mod register_allocated_asm_set;
Expand Down
134 changes: 1 addition & 133 deletions sway-core/src/ir_generation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use sway_types::span::Span;

pub(crate) use purity::PurityChecker;

pub(crate) fn compile_program(program: TypedProgram) -> Result<Context, CompileError> {
pub fn compile_program(program: TypedProgram) -> Result<Context, CompileError> {
let TypedProgram { kind, root, .. } = program;

let mut ctx = Context::default();
Expand All @@ -41,135 +41,3 @@ pub(crate) fn compile_program(program: TypedProgram) -> Result<Context, CompileE
ctx.verify()
.map_err(|ir_error| CompileError::InternalOwned(ir_error.to_string(), Span::dummy()))
}

#[cfg(test)]
mod tests {
use crate::semantic_analysis::{namespace, TypedProgram};
use std::path::PathBuf;

#[test]
fn sway_to_ir_tests() {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let dir: PathBuf = format!("{}/tests/sway_to_ir", manifest_dir).into();
for entry in std::fs::read_dir(dir).unwrap() {
// We're only interested in the `.sw` files here.
let path = entry.unwrap().path();
match path.extension().unwrap().to_str() {
Some("sw") => {
//
// Run the tests!
//
tracing::info!("---- Sway To IR: {:?} ----", path);
test_sway_to_ir(path);
}
Some("ir") | Some("disabled") => (),
_ => panic!(
"File with invalid extension in tests dir: {:?}",
path.file_name().unwrap_or(path.as_os_str())
),
}
}
}

fn test_sway_to_ir(sw_path: PathBuf) {
let input_bytes = std::fs::read(&sw_path).unwrap();
let input = String::from_utf8_lossy(&input_bytes);

let mut ir_path = sw_path.clone();
ir_path.set_extension("ir");

let expected_bytes = std::fs::read(&ir_path).unwrap();
let expected = String::from_utf8_lossy(&expected_bytes);

let typed_program = parse_to_typed_program(sw_path.clone(), &input);
let ir = super::compile_program(typed_program).unwrap();
let output = sway_ir::printer::to_string(&ir);

// Use a tricky regex to replace the local path in the metadata with something generic. It
// should convert, e.g.,
// `!0 = filepath "/usr/home/me/sway/sway-core/tests/sway_to_ir/foo.sw"`
// to `!0 = filepath "/path/to/foo.sw"`
let path_converter = regex::Regex::new(r#"(!\d = filepath ")(?:[^/]*/)*(.+)"#).unwrap();
let output = path_converter.replace_all(output.as_str(), "$1/path/to/$2");

if output != expected {
println!("{}", prettydiff::diff_lines(&expected, &output));
panic!("{} failed.", sw_path.display());
}
}

#[test]
fn ir_printer_parser_tests() {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let dir: PathBuf = format!("{}/tests/sway_to_ir", manifest_dir).into();
for entry in std::fs::read_dir(dir).unwrap() {
// We're only interested in the `.ir` files here.
let path = entry.unwrap().path();
match path.extension().unwrap().to_str() {
Some("ir") => {
//
// Run the tests!
//
tracing::info!("---- IR Print and Parse Test: {:?} ----", path);
test_printer_parser(path);
}
Some("sw") | Some("disabled") => (),
_ => panic!(
"File with invalid extension in tests dir: {:?}",
path.file_name().unwrap_or(path.as_os_str())
),
}
}
}

fn test_printer_parser(path: PathBuf) {
let input_bytes = std::fs::read(&path).unwrap();
let input = String::from_utf8_lossy(&input_bytes);

// Use another tricky regex to inject the proper metadata filepath back, so we can create
// spans in the parser. NOTE, if/when we refactor spans to not have the source string and
// just the path these tests should pass without needing this conversion.
let mut true_path = path.clone();
true_path.set_extension("sw");
let path_converter = regex::Regex::new(r#"(!\d = filepath )(?:.+)"#).unwrap();
let input = path_converter.replace_all(&input, format!("$1\"{}\"", true_path.display()));

let parsed_ctx = match sway_ir::parser::parse(&input) {
Ok(p) => p,
Err(e) => {
println!("{}: {}", path.display(), e);
panic!();
}
};
let printed = sway_ir::printer::to_string(&parsed_ctx);
if printed != input {
println!("{}", prettydiff::diff_lines(&input, &printed));
panic!("{} failed.", path.display());
}
}

fn parse_to_typed_program(path: PathBuf, input: &str) -> TypedProgram {
let root_module = std::sync::Arc::new(path);
let canonical_root_module = std::sync::Arc::new(root_module.canonicalize().unwrap());

let build_config = crate::build_config::BuildConfig {
canonical_root_module,
print_intermediate_asm: false,
print_finalized_asm: false,
print_ir: false,
};
let mut warnings = vec![];
let mut errors = vec![];
let src = std::sync::Arc::from(input);
let parsed_program =
crate::parse(src, Some(&build_config)).unwrap(&mut warnings, &mut errors);

let initial_namespace = namespace::Module::default();
let typed_program = TypedProgram::type_check(parsed_program, initial_namespace)
.unwrap(&mut warnings, &mut errors);

crate::perform_control_flow_analysis(&typed_program).unwrap(&mut warnings, &mut errors);

typed_program
}
}
5 changes: 3 additions & 2 deletions sway-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ mod concurrent_slab;
pub mod constants;
mod control_flow_analysis;
mod convert_parse_tree;
mod ir_generation;
pub mod ir_generation;
pub mod parse_tree;
pub mod semantic_analysis;
pub mod source_map;
mod style;
pub mod type_engine;

use crate::{error::*, source_map::SourceMap};
pub use asm_generation::from_ir::compile_ir_to_asm;
use asm_generation::FinalizedAsm;
pub use build_config::BuildConfig;
use control_flow_analysis::ControlFlowGraph;
Expand Down Expand Up @@ -444,7 +445,7 @@ pub(crate) fn compile_ast_to_ir_to_asm(
tracing::info!("{}", ir);
}

crate::asm_generation::from_ir::compile_ir_to_asm(&ir, build_config)
compile_ir_to_asm(&ir, Some(build_config))
}

fn inline_function_calls(ir: &mut Context, functions: &[Function]) -> CompileResult<()> {
Expand Down
34 changes: 0 additions & 34 deletions sway-core/tests/sway_to_ir/array_simple.ir

This file was deleted.

6 changes: 0 additions & 6 deletions sway-core/tests/sway_to_ir/array_simple.sw

This file was deleted.

25 changes: 0 additions & 25 deletions sway-core/tests/sway_to_ir/asm_block.ir

This file was deleted.

Loading

0 comments on commit 823707d

Please sign in to comment.