File size: 11,746 Bytes
d5bfab8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
use loda_rust_core::parser::ParsedProgram;
use crate::lodacpp::{LodaCpp, LodaCppEvalStepsExecute, LodaCppEvalSteps};
use crate::common::SimpleLog;
use std::path::Path;
use std::time::Duration;
use std::time::Instant;
use std::fs::File;
use std::io::Write;
use std::fs;
use anyhow::Context;
pub enum StatusOfExistingProgram {
CompareNewWithExisting,
NoExistingProgram,
IgnoreExistingProgram { ignore_reason: String },
}
#[derive(Debug, PartialEq)]
pub enum CompareTwoProgramsResult {
Program0,
Program1,
}
pub struct CompareTwoPrograms;
impl CompareTwoPrograms {
pub fn compare(
simple_log: SimpleLog,
lodacpp: &LodaCpp,
path_program0: &Path,
path_program1: &Path,
status_of_existing_program: &StatusOfExistingProgram,
path_comparison: &Path,
time_limit: Duration,
term_count: usize
) -> anyhow::Result<CompareTwoProgramsResult> {
if !path_program0.is_file() {
return Err(anyhow::anyhow!("Expected a file, but got none. path_program0: {:?}", path_program0));
}
match status_of_existing_program {
StatusOfExistingProgram::NoExistingProgram => {
simple_log.println("compare_two_programs: Keeping. This is a new program. There is no previous implementation.");
return Ok(CompareTwoProgramsResult::Program0);
},
StatusOfExistingProgram::IgnoreExistingProgram { ignore_reason } => {
return Self::ignore_existing_program(
simple_log,
path_program0,
path_program1,
ignore_reason
);
},
StatusOfExistingProgram::CompareNewWithExisting => {
return Self::compare_new_with_existing(
simple_log,
lodacpp,
path_program0,
path_program1,
path_comparison,
time_limit,
term_count
);
}
}
}
fn ignore_existing_program(
simple_log: SimpleLog,
path_program0: &Path,
path_program1: &Path,
ignore_reason: &String,
) -> anyhow::Result<CompareTwoProgramsResult> {
let is_identical: bool = Self::is_identical(path_program0, path_program1)
.context("ignore_existing_program")?;
if is_identical {
simple_log.println("compare_two_programs.ignore_existing_program: The two programs are identical. Keeping the existing program as it is.");
return Ok(CompareTwoProgramsResult::Program1);
}
simple_log.println(format!("compare_two_programs.ignore_existing_program: Keeping the mined program. There is a problem with the previous implementation: {}", ignore_reason));
Ok(CompareTwoProgramsResult::Program0)
}
fn compare_new_with_existing(
simple_log: SimpleLog,
lodacpp: &LodaCpp,
path_program0: &Path,
path_program1: &Path,
path_comparison: &Path,
time_limit: Duration,
term_count: usize
) -> anyhow::Result<CompareTwoProgramsResult> {
let is_identical: bool = Self::is_identical(path_program0, path_program1)
.context("compare_new_with_existing")?;
if is_identical {
simple_log.println("compare_two_programs.compare_new_with_existing: The two programs are identical. Keeping the existing program as it is.");
return Ok(CompareTwoProgramsResult::Program1);
}
simple_log.println("compare_two_programs.compare_new_with_existing: Comparing new program with existing program, and choosing the best.");
let mut file = File::create(path_comparison)?;
writeln!(&mut file, "program0, measuring steps: {:?}", path_program0)?;
let start0 = Instant::now();
let result0 = lodacpp.eval_steps(
term_count,
&path_program0,
time_limit
);
let result_steps0: LodaCppEvalSteps = match result0 {
Ok(value) => {
let elapsed: u128 = start0.elapsed().as_millis();
// debug!("program0 steps:\n{:?}", value.steps());
writeln!(&mut file, "program0, elapsed: {:?}ms", elapsed)?;
// writeln!(&mut file, "program0, steps\n{:?}", value.steps())?;
value
},
Err(error) => {
// error!("Unable to compute steps for program0: {:?}", error);
writeln!(&mut file, "Unable to compute steps for program0: {:?}", error)?;
return Ok(CompareTwoProgramsResult::Program1);
}
};
if result_steps0.steps().len() != term_count {
writeln!(&mut file, "ERROR: Problem with program0. Expected {} steps, but got {}", term_count, result_steps0.steps().len())?;
return Ok(CompareTwoProgramsResult::Program1);
}
writeln!(&mut file, "\n\nprogram1, measuring steps: {:?}", path_program1)?;
let start1 = Instant::now();
let result1 = lodacpp.eval_steps(
term_count,
&path_program1,
time_limit
);
let result_steps1: LodaCppEvalSteps = match result1 {
Ok(value) => {
let elapsed: u128 = start1.elapsed().as_millis();
// debug!("program1 steps:\n{:?}", value.steps());
writeln!(&mut file, "program1, elapsed: {:?}ms", elapsed)?;
// writeln!(&mut file, "program1, steps\n{:?}", value.steps())?;
value
},
Err(error) => {
// debug!("Unable to compute steps for program1: {:?}", error);
writeln!(&mut file, "Unable to compute steps for program1: {:?}", error)?;
return Ok(CompareTwoProgramsResult::Program0);
}
};
if result_steps1.steps().len() != term_count {
writeln!(&mut file, "ERROR: Problem with program1. Expected {} steps, but got {}", term_count, result_steps1.steps().len())?;
return Ok(CompareTwoProgramsResult::Program0);
}
write!(&mut file, "\n\nComparing terms:\nprogram0 vs program1\n")?;
let step_items0: &Vec<u64> = result_steps0.steps();
let step_items1: &Vec<u64> = result_steps1.steps();
assert!(step_items0.len() == step_items1.len());
let sum0: usize = step_items0.iter().map(|&x| x as usize).sum();
let sum1: usize = step_items1.iter().map(|&x| x as usize).sum();
writeln!(&mut file, "sum0: {} sum1: {}", sum0, sum1)?;
// let mut step0_less_than_step1: usize = 0;
let mut last_slice_step0_greater_than_step1: usize = 0;
// let mut step0_same_step1: usize = 0;
// let mut step0_greater_than_step1: usize = 0;
let mut identical: bool = true;
for index in 0..step_items0.len() {
let step0: u64 = step_items0[index];
let step1: u64 = step_items1[index];
let mut comparison_symbol = " ";
if step0 == step1 {
// step0_same_step1 += 1;
comparison_symbol = " = ";
}
if step0 > step1 {
// step0_greater_than_step1 += 1;
comparison_symbol = " >";
identical = false;
if index > 15 {
last_slice_step0_greater_than_step1 += 1;
}
}
if step0 < step1 {
// step0_less_than_step1 += 1;
comparison_symbol = "< ";
identical = false;
}
writeln!(&mut file, "{:>10} {} {}", step0, comparison_symbol, step1)?;
}
if identical {
writeln!(&mut file, "identical number of steps as the existing program. Keep the existing program.")?;
return Ok(CompareTwoProgramsResult::Program1);
}
if sum0 == sum1 {
writeln!(&mut file, "same sum as the existing program. Keep the existing program.")?;
return Ok(CompareTwoProgramsResult::Program1);
}
if sum0 > sum1 {
writeln!(&mut file, "total sum of new program is greater than existing program. Keep the existing program.")?;
return Ok(CompareTwoProgramsResult::Program1);
}
if last_slice_step0_greater_than_step1 > 0 {
writeln!(&mut file, "last slice of the new program is greater than existing program. Keep the existing program.")?;
return Ok(CompareTwoProgramsResult::Program1);
}
if sum0 < sum1 {
writeln!(&mut file, "the new program is faster than the existing program. Keep the new program.")?;
return Ok(CompareTwoProgramsResult::Program0);
}
error!("uncaught scenario. Using existing program");
writeln!(&mut file, "uncaught scenario. Using existing program")?;
Ok(CompareTwoProgramsResult::Program1)
}
/// Check if two programs are identical. If so, then pick existing program.
fn is_identical(
path_program0: &Path,
path_program1: &Path,
) -> anyhow::Result<bool> {
if !path_program0.is_file() {
return Err(anyhow::anyhow!("Expected a file, but got none. path_program0: {:?}", path_program0));
}
if !path_program1.is_file() {
return Err(anyhow::anyhow!("Expected a file, but got none. path_program1: {:?}", path_program1));
}
let contents0: String = fs::read_to_string(path_program0)?;
let contents1: String = fs::read_to_string(path_program1)?;
let mut parsed_program0: ParsedProgram = ParsedProgram::parse_program(&contents0)
.map_err(|e| anyhow::anyhow!("Unable to parse program0. path: {:?} error: {:?}", path_program0, e))?;
let mut parsed_program1: ParsedProgram = ParsedProgram::parse_program(&contents1)
.map_err(|e| anyhow::anyhow!("Unable to parse program1. path: {:?} error: {:?}", path_program1, e))?;
parsed_program0.assign_zero_line_numbers();
parsed_program1.assign_zero_line_numbers();
Ok(parsed_program0 == parsed_program1)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn test_10000_is_identical_yes() -> anyhow::Result<()> {
// Arrange
let tempdir = tempfile::tempdir().unwrap();
let basedir = PathBuf::from(&tempdir.path()).join("test_10000_is_identical_yes");
fs::create_dir(&basedir)?;
let path0: PathBuf = basedir.join("program0.asm");
let path1: PathBuf = basedir.join("program1.asm");
fs::write(&path0, b"; hi\n\nadd $0,1\n\nsub $0,1 ; hi")?;
fs::write(&path1, b"add $0,1\nsub $0,1")?;
// Act
let is_identical: bool = CompareTwoPrograms::is_identical(&path0, &path1)?;
// Assert
assert_eq!(is_identical, true);
Ok(())
}
#[test]
fn test_10001_is_identical_no() -> anyhow::Result<()> {
// Arrange
let tempdir = tempfile::tempdir().unwrap();
let basedir = PathBuf::from(&tempdir.path()).join("test_10001_is_identical_no");
fs::create_dir(&basedir)?;
let path0: PathBuf = basedir.join("program0.asm");
let path1: PathBuf = basedir.join("program1.asm");
fs::write(&path0, b"add $0,-1")?;
fs::write(&path1, b"sub $0,1")?;
// Act
let is_identical: bool = CompareTwoPrograms::is_identical(&path0, &path1)?;
// Assert
assert_eq!(is_identical, false);
Ok(())
}
}
|