rustlings/src/exercise.rs

310 lines
9.6 KiB
Rust
Raw Normal View History

2024-03-31 10:55:33 -04:00
use anyhow::{Context, Result};
use serde::Deserialize;
2024-03-31 10:55:33 -04:00
use std::fmt::{self, Debug, Display, Formatter};
use std::fs::{self, File};
2024-03-24 13:34:46 -04:00
use std::io::{self, BufRead, BufReader};
use std::path::PathBuf;
2024-04-06 19:15:47 -04:00
use std::process::{Command, Output};
2024-03-31 10:55:33 -04:00
use std::{array, mem};
2024-03-24 17:22:55 -04:00
use winnow::ascii::{space0, Caseless};
2024-03-24 14:18:19 -04:00
use winnow::combinator::opt;
use winnow::Parser;
2024-04-07 16:43:59 -04:00
use crate::embedded::{WriteStrategy, EMBEDDED_FILES};
2024-03-31 10:55:33 -04:00
// The number of context lines above and below a highlighted line.
const CONTEXT: usize = 2;
2024-03-31 10:55:33 -04:00
// Check if the line contains the "I AM NOT DONE" comment.
fn contains_not_done_comment(input: &str) -> bool {
2024-03-24 14:18:19 -04:00
(
space0::<_, ()>,
"//",
opt('/'),
space0,
2024-03-24 17:22:55 -04:00
Caseless("I AM NOT DONE"),
2024-03-24 14:18:19 -04:00
)
.parse_next(&mut &*input)
.is_ok()
}
// The mode of the exercise.
2024-03-31 10:55:33 -04:00
#[derive(Deserialize, Copy, Clone)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
2024-03-31 10:55:33 -04:00
// The exercise should be compiled as a binary
Compile,
2024-03-31 10:55:33 -04:00
// The exercise should be compiled as a test harness
Test,
2024-03-31 10:55:33 -04:00
// The exercise should be linted with clippy
Clippy,
}
#[derive(Deserialize)]
2024-04-07 17:37:40 -04:00
pub struct InfoFile {
pub exercises: Vec<Exercise>,
}
2024-04-07 17:37:40 -04:00
impl InfoFile {
2024-03-31 10:55:33 -04:00
pub fn parse() -> Result<Self> {
// Read a local `info.toml` if it exists.
// Mainly to let the tests work for now.
if let Ok(file_content) = fs::read_to_string("info.toml") {
toml_edit::de::from_str(&file_content)
} else {
toml_edit::de::from_str(EMBEDDED_FILES.info_toml_content)
}
.context("Failed to parse `info.toml`")
}
}
// Deserialized from the `info.toml` file.
#[derive(Deserialize)]
pub struct Exercise {
// Name of the exercise
pub name: String,
// The path to the file containing the exercise's source code
pub path: PathBuf,
2024-03-31 10:55:33 -04:00
// The mode of the exercise
pub mode: Mode,
// The hint text associated with the exercise
pub hint: String,
}
2024-03-31 10:55:33 -04:00
// The state of an Exercise.
2024-03-26 12:47:33 -04:00
#[derive(PartialEq, Eq, Debug)]
pub enum State {
Done,
Pending(Vec<ContextLine>),
}
2024-03-31 10:55:33 -04:00
// The context information of a pending exercise.
2024-03-26 12:47:33 -04:00
#[derive(PartialEq, Eq, Debug)]
pub struct ContextLine {
2024-03-31 10:55:33 -04:00
// The source code line
pub line: String,
2024-03-31 10:55:33 -04:00
// The line number
pub number: usize,
2024-03-31 10:55:33 -04:00
// Whether this is important and should be highlighted
pub important: bool,
}
impl Exercise {
2024-03-31 10:55:33 -04:00
fn cargo_cmd(&self, command: &str, args: &[&str]) -> Result<Output> {
2024-03-31 20:11:52 -04:00
let mut cmd = Command::new("cargo");
cmd.arg(command);
// A hack to make `cargo run` work when developing Rustlings.
// Use `dev/Cargo.toml` when in the directory of the repository.
#[cfg(debug_assertions)]
if std::path::Path::new("tests").exists() {
cmd.arg("--manifest-path").arg("dev/Cargo.toml");
}
cmd.arg("--color")
2024-03-31 10:55:33 -04:00
.arg("always")
.arg("-q")
.arg("--bin")
.arg(&self.name)
.args(args)
.output()
2024-03-31 10:55:33 -04:00
.context("Failed to run Cargo")
}
2024-03-31 10:55:33 -04:00
pub fn run(&self) -> Result<Output> {
match self.mode {
Mode::Compile => self.cargo_cmd("run", &[]),
Mode::Test => self.cargo_cmd("test", &["--", "--nocapture", "--format", "pretty"]),
2024-03-31 10:55:33 -04:00
Mode::Clippy => self.cargo_cmd(
"clippy",
&["--", "-D", "warnings", "-D", "clippy::float_cmp"],
),
}
}
2024-03-31 12:25:54 -04:00
pub fn state(&self) -> Result<State> {
let source_file = File::open(&self.path)
.with_context(|| format!("Failed to open the exercise file {}", self.path.display()))?;
2024-03-24 13:34:46 -04:00
let mut source_reader = BufReader::new(source_file);
// Read the next line into `buf` without the newline at the end.
2024-03-24 13:34:46 -04:00
let mut read_line = |buf: &mut String| -> io::Result<_> {
let n = source_reader.read_line(buf)?;
if buf.ends_with('\n') {
buf.pop();
if buf.ends_with('\r') {
buf.pop();
}
}
Ok(n)
};
let mut current_line_number: usize = 1;
2024-03-25 21:26:26 -04:00
// Keep the last `CONTEXT` lines while iterating over the file lines.
2024-03-24 13:34:46 -04:00
let mut prev_lines: [_; CONTEXT] = array::from_fn(|_| String::with_capacity(256));
let mut line = String::with_capacity(256);
2024-03-24 13:34:46 -04:00
loop {
2024-04-06 19:15:47 -04:00
let n = read_line(&mut line).with_context(|| {
format!("Failed to read the exercise file {}", self.path.display())
})?;
// Reached the end of the file and didn't find the comment.
if n == 0 {
2024-03-31 12:25:54 -04:00
return Ok(State::Done);
}
if contains_not_done_comment(&line) {
let mut context = Vec::with_capacity(2 * CONTEXT + 1);
2024-03-25 21:26:26 -04:00
// Previous lines.
for (ind, prev_line) in prev_lines
.into_iter()
.take(current_line_number - 1)
.enumerate()
.rev()
{
context.push(ContextLine {
line: prev_line,
number: current_line_number - 1 - ind,
important: false,
});
}
2024-03-24 13:34:46 -04:00
2024-03-25 21:26:26 -04:00
// Current line.
context.push(ContextLine {
line,
number: current_line_number,
important: true,
});
2024-03-25 21:26:26 -04:00
// Next lines.
for ind in 0..CONTEXT {
let mut next_line = String::with_capacity(256);
let Ok(n) = read_line(&mut next_line) else {
2024-03-25 21:26:26 -04:00
// If an error occurs, just ignore the next lines.
break;
};
2024-03-25 21:26:26 -04:00
// Reached the end of the file.
if n == 0 {
break;
2024-03-24 13:34:46 -04:00
}
context.push(ContextLine {
line: next_line,
number: current_line_number + 1 + ind,
important: false,
});
2024-03-24 13:34:46 -04:00
}
2024-03-31 12:25:54 -04:00
return Ok(State::Pending(context));
2024-03-24 13:34:46 -04:00
}
current_line_number += 1;
2024-03-25 21:26:26 -04:00
// Add the current line as a previous line and shift the older lines by one.
for prev_line in &mut prev_lines {
mem::swap(&mut line, prev_line);
}
2024-03-25 21:26:26 -04:00
// The current line now contains the oldest previous line.
// Recycle it for reading the next line.
line.clear();
}
}
// Check that the exercise looks to be solved using self.state()
// This is not the best way to check since
// the user can just remove the "I AM NOT DONE" string from the file
// without actually having solved anything.
// The only other way to truly check this would to compile and run
// the exercise; which would be both costly and counterintuitive
2024-03-31 12:25:54 -04:00
pub fn looks_done(&self) -> Result<bool> {
self.state().map(|state| state == State::Done)
}
2024-04-07 16:43:59 -04:00
pub fn reset(&self) -> Result<()> {
EMBEDDED_FILES
.write_exercise_to_disk(&self.path, WriteStrategy::Overwrite)
.with_context(|| format!("Failed to reset the exercise {self}"))
}
}
impl Display for Exercise {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2024-03-31 10:55:33 -04:00
self.path.fmt(f)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_pending_state() {
let exercise = Exercise {
2019-11-11 11:28:19 -05:00
name: "pending_exercise".into(),
2024-03-30 15:48:30 -04:00
path: PathBuf::from("tests/fixture/state/exercises/pending_exercise.rs"),
mode: Mode::Compile,
2019-11-11 11:28:19 -05:00
hint: String::new(),
};
let state = exercise.state();
let expected = vec![
ContextLine {
line: "// fake_exercise".to_string(),
number: 1,
important: false,
},
ContextLine {
line: "".to_string(),
number: 2,
important: false,
},
ContextLine {
line: "// I AM NOT DONE".to_string(),
number: 3,
important: true,
},
ContextLine {
line: "".to_string(),
number: 4,
important: false,
},
ContextLine {
line: "fn main() {".to_string(),
number: 5,
important: false,
},
];
2024-03-31 12:25:54 -04:00
assert_eq!(state.unwrap(), State::Pending(expected));
}
#[test]
fn test_finished_exercise() {
let exercise = Exercise {
2019-11-11 11:28:19 -05:00
name: "finished_exercise".into(),
2024-03-30 15:48:30 -04:00
path: PathBuf::from("tests/fixture/state/exercises/finished_exercise.rs"),
mode: Mode::Compile,
2019-11-11 11:28:19 -05:00
hint: String::new(),
};
2024-03-31 12:25:54 -04:00
assert_eq!(exercise.state().unwrap(), State::Done);
}
2024-03-24 14:18:19 -04:00
#[test]
fn test_not_done() {
assert!(contains_not_done_comment("// I AM NOT DONE"));
assert!(contains_not_done_comment("/// I AM NOT DONE"));
assert!(contains_not_done_comment("// I AM NOT DONE"));
assert!(contains_not_done_comment("/// I AM NOT DONE"));
assert!(contains_not_done_comment("// I AM NOT DONE "));
assert!(contains_not_done_comment("// I AM NOT DONE!"));
assert!(contains_not_done_comment("// I am not done"));
assert!(contains_not_done_comment("// i am NOT done"));
assert!(!contains_not_done_comment("I AM NOT DONE"));
assert!(!contains_not_done_comment("// NOT DONE"));
assert!(!contains_not_done_comment("DONE"));
2024-03-24 14:18:19 -04:00
}
}