From 1f17e1296b769d1097952b7cd9f9cf4dfbfb3ddb Mon Sep 17 00:00:00 2001 From: Ruan Comelli Date: Sat, 30 Mar 2024 16:21:45 -0300 Subject: [PATCH] exercise: add `macros` --- exercism/rust/macros/.exercism/config.json | 39 ++++ exercism/rust/macros/.exercism/metadata.json | 1 + exercism/rust/macros/.gitignore | 8 + exercism/rust/macros/Cargo.toml | 6 + exercism/rust/macros/HELP.md | 86 +++++++ exercism/rust/macros/README.md | 64 ++++++ exercism/rust/macros/src/lib.rs | 18 ++ exercism/rust/macros/tests/invalid/Cargo.toml | 55 +++++ .../rust/macros/tests/invalid/comma-sep.rs | 7 + .../macros/tests/invalid/double-commas.rs | 7 + .../macros/tests/invalid/leading-comma.rs | 7 + .../macros/tests/invalid/missing-argument.rs | 7 + .../rust/macros/tests/invalid/no-comma.rs | 7 + .../rust/macros/tests/invalid/only-arrow.rs | 7 + .../rust/macros/tests/invalid/only-comma.rs | 7 + .../macros/tests/invalid/single-argument.rs | 7 + .../macros/tests/invalid/triple-arguments.rs | 7 + .../rust/macros/tests/invalid/two-arrows.rs | 7 + exercism/rust/macros/tests/macros.rs | 216 ++++++++++++++++++ 19 files changed, 563 insertions(+) create mode 100644 exercism/rust/macros/.exercism/config.json create mode 100644 exercism/rust/macros/.exercism/metadata.json create mode 100644 exercism/rust/macros/.gitignore create mode 100644 exercism/rust/macros/Cargo.toml create mode 100644 exercism/rust/macros/HELP.md create mode 100644 exercism/rust/macros/README.md create mode 100644 exercism/rust/macros/src/lib.rs create mode 100644 exercism/rust/macros/tests/invalid/Cargo.toml create mode 100644 exercism/rust/macros/tests/invalid/comma-sep.rs create mode 100644 exercism/rust/macros/tests/invalid/double-commas.rs create mode 100644 exercism/rust/macros/tests/invalid/leading-comma.rs create mode 100644 exercism/rust/macros/tests/invalid/missing-argument.rs create mode 100644 exercism/rust/macros/tests/invalid/no-comma.rs create mode 100644 exercism/rust/macros/tests/invalid/only-arrow.rs create mode 100644 exercism/rust/macros/tests/invalid/only-comma.rs create mode 100644 exercism/rust/macros/tests/invalid/single-argument.rs create mode 100644 exercism/rust/macros/tests/invalid/triple-arguments.rs create mode 100644 exercism/rust/macros/tests/invalid/two-arrows.rs create mode 100644 exercism/rust/macros/tests/macros.rs diff --git a/exercism/rust/macros/.exercism/config.json b/exercism/rust/macros/.exercism/config.json new file mode 100644 index 0000000..c28e17b --- /dev/null +++ b/exercism/rust/macros/.exercism/config.json @@ -0,0 +1,39 @@ +{ + "authors": [ + "coriolinus" + ], + "contributors": [ + "bantic", + "cwhakes", + "DarthStrom", + "efx", + "Emerentius", + "ErikSchierboom", + "lutostag", + "pedantic79", + "petertseng", + "rofrol", + "ssomers", + "stringparser", + "tjade273", + "xakon", + "ZapAnton" + ], + "files": { + "solution": [ + "src/lib.rs", + "Cargo.toml" + ], + "test": [ + "tests/macros.rs" + ], + "example": [ + ".meta/example.rs" + ] + }, + "blurb": "Implement a macro using macros-by-example", + "source": "Peter Goodspeed-Niklaus", + "custom": { + "allowed-to-not-compile": "Stub doesn't compile because there is no rule for the macro forms in the test file. Providing these rules would reduce student learning, so we do not." + } +} diff --git a/exercism/rust/macros/.exercism/metadata.json b/exercism/rust/macros/.exercism/metadata.json new file mode 100644 index 0000000..4f8f352 --- /dev/null +++ b/exercism/rust/macros/.exercism/metadata.json @@ -0,0 +1 @@ +{"track":"rust","exercise":"macros","id":"19dcf7afc6274f279bf88233f51e3edf","url":"https://exercism.org/tracks/rust/exercises/macros","handle":"ruancomelli","is_requester":true,"auto_approve":false} diff --git a/exercism/rust/macros/.gitignore b/exercism/rust/macros/.gitignore new file mode 100644 index 0000000..db7f315 --- /dev/null +++ b/exercism/rust/macros/.gitignore @@ -0,0 +1,8 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ +**/*.rs.bk + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock +Cargo.lock diff --git a/exercism/rust/macros/Cargo.toml b/exercism/rust/macros/Cargo.toml new file mode 100644 index 0000000..8c82d2e --- /dev/null +++ b/exercism/rust/macros/Cargo.toml @@ -0,0 +1,6 @@ +[package] +edition = "2021" +name = "macros" +version = "0.1.0" + +[dependencies] diff --git a/exercism/rust/macros/HELP.md b/exercism/rust/macros/HELP.md new file mode 100644 index 0000000..a76544a --- /dev/null +++ b/exercism/rust/macros/HELP.md @@ -0,0 +1,86 @@ +# Help + +## Running the tests + +Execute the tests with: + +```bash +$ cargo test +``` + +All but the first test have been ignored. After you get the first test to +pass, open the tests source file which is located in the `tests` directory +and remove the `#[ignore]` flag from the next test and get the tests to pass +again. Each separate test is a function with `#[test]` flag above it. +Continue, until you pass every test. + +If you wish to run _only ignored_ tests without editing the tests source file, use: + +```bash +$ cargo test -- --ignored +``` + +If you are using Rust 1.51 or later, you can run _all_ tests with + +```bash +$ cargo test -- --include-ignored +``` + +To run a specific test, for example `some_test`, you can use: + +```bash +$ cargo test some_test +``` + +If the specific test is ignored, use: + +```bash +$ cargo test some_test -- --ignored +``` + +To learn more about Rust tests refer to the online [test documentation][rust-tests]. + +[rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html + +## Submitting your solution + +You can submit your solution using the `exercism submit src/lib.rs Cargo.toml` command. +This command will upload your solution to the Exercism website and print the solution page's URL. + +It's possible to submit an incomplete solution which allows you to: + +- See how others have completed the exercise +- Request help from a mentor + +## Need to get help? + +If you'd like help solving the exercise, check the following pages: + +- The [Rust track's documentation](https://exercism.org/docs/tracks/rust) +- The [Rust track's programming category on the forum](https://forum.exercism.org/c/programming/rust) +- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5) +- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs) + +Should those resources not suffice, you could submit your (incomplete) solution to request mentoring. + +## Rust Installation + +Refer to the [exercism help page][help-page] for Rust installation and learning +resources. + +## Submitting the solution + +Generally you should submit all files in which you implemented your solution (`src/lib.rs` in most cases). If you are using any external crates, please consider submitting the `Cargo.toml` file. This will make the review process faster and clearer. + +## Feedback, Issues, Pull Requests + +The GitHub [track repository][github] is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help! + +If you want to know more about Exercism, take a look at the [contribution guide]. + +## Submitting Incomplete Solutions +It's possible to submit an incomplete solution so you can see how others have completed the exercise. + +[help-page]: https://exercism.org/tracks/rust/learning +[github]: https://github.com/exercism/rust +[contribution guide]: https://exercism.org/docs/community/contributors diff --git a/exercism/rust/macros/README.md b/exercism/rust/macros/README.md new file mode 100644 index 0000000..8b59c6b --- /dev/null +++ b/exercism/rust/macros/README.md @@ -0,0 +1,64 @@ +# Macros + +Welcome to Macros on Exercism's Rust Track. +If you need help running the tests or submitting your code, check out `HELP.md`. + +## Instructions + +Macros are a powerful part of a Rust programmer's toolkit, and [macros by example](https://doc.rust-lang.org/reference/macros-by-example.html) are a relatively simple way to access this power. Let's write one! + +## Context + +What is a macro? [Wikipedia](https://en.wikipedia.org/wiki/Macro_(computer_science)) describes it thus: + +> A macro (short for "macroinstruction", from Greek μακρός 'long') in computer science is a rule or pattern that specifies how a certain input sequence (often a sequence of characters) should be mapped to a replacement output sequence (also often a sequence of characters) according to a defined procedure. The mapping process that instantiates (transforms) a macro use into a specific sequence is known as macro expansion. + +Illuminating! But to be more concrete, macros are a special syntax which allows you to generate code at compile time. Macros can be used for compile-time calculation, but more often they're just another way to abstract your code. For example, you've probably already used `println!()` and `vec![]`. These each take an arbitrary number of arguments, so you can't express them as simple functions. On the other hand, they always expand to some amount of absolutely standard Rust code. If you're interested, you can use the [cargo expand](https://github.com/dtolnay/cargo-expand) subcommand to view the results of macro expansion in your code. + +For further information about macros in Rust, The Rust Book has a [good chapter](https://doc.rust-lang.org/book/ch19-06-macros.html) on them. + +## Problem Statement + +You can produce a `Vec` of arbitrary length inline by using the `vec![]` macro. However, Rust doesn't come with a way to produce a [`HashMap`](https://doc.rust-lang.org/std/collections/struct.HashMap.html) inline. Rectify this by writing a `hashmap!()` macro. + +For example, a user of your library might write `hashmap!('a' => 3, 'b' => 11, 'z' => 32)`. This should expand to the following code: + +```rust +{ + let mut hm = HashMap::new(); + hm.insert('a', 3); + hm.insert('b', 11); + hm.insert('z', 32); + hm +} +``` + +Note that the [`maplit` crate](https://crates.io/crates/maplit) provides a macro which perfectly solves this exercise. Please implement your own solution instead of using this crate; please make an attempt on your own before viewing its source. + +## Source + +### Created by + +- @coriolinus + +### Contributed to by + +- @bantic +- @cwhakes +- @DarthStrom +- @efx +- @Emerentius +- @ErikSchierboom +- @lutostag +- @pedantic79 +- @petertseng +- @rofrol +- @ssomers +- @stringparser +- @tjade273 +- @xakon +- @ZapAnton + +### Based on + +Peter Goodspeed-Niklaus diff --git a/exercism/rust/macros/src/lib.rs b/exercism/rust/macros/src/lib.rs new file mode 100644 index 0000000..d1b36f1 --- /dev/null +++ b/exercism/rust/macros/src/lib.rs @@ -0,0 +1,18 @@ +#[macro_export] +macro_rules! hashmap { + () => { + ::std::collections::HashMap::new() + }; + ( + $first_key:expr => $first_value:expr + $(, $key:expr => $value:expr )* + $(,)? // trailing comma allowed + ) => { + ::std::collections::HashMap::from( + [ + ($first_key, $first_value) + $(, ($key, $value))* + ] + ) + }; +} diff --git a/exercism/rust/macros/tests/invalid/Cargo.toml b/exercism/rust/macros/tests/invalid/Cargo.toml new file mode 100644 index 0000000..824de56 --- /dev/null +++ b/exercism/rust/macros/tests/invalid/Cargo.toml @@ -0,0 +1,55 @@ +# +# This Cargo.toml file is used by the simple-trybuild module. +# When adding a new file, please name the [[bin]] name to match the file +# it is used to produce an error message +# + +[package] +name = "macros-tests" +version = "0.0.0" +edition = "2021" +publish = false + +[dependencies.macros] +path = "../../" +default-features = false + +[[bin]] +name = "comma-sep-rs" +path = "comma-sep.rs" + +[[bin]] +name = "double-commas-rs" +path = "double-commas.rs" + +[[bin]] +name = "only-arrow-rs" +path = "only-arrow.rs" + +[[bin]] +name = "only-comma-rs" +path = "only-comma.rs" + +[[bin]] +name = "single-argument-rs" +path = "single-argument.rs" + +[[bin]] +name = "triple-arguments-rs" +path = "triple-arguments.rs" + +[[bin]] +name = "two-arrows-rs" +path = "two-arrows.rs" + +[[bin]] +name = "leading-comma-rs" +path = "leading-comma.rs" + +[[bin]] +name = "no-comma-rs" +path = "no-comma.rs" + +[[bin]] +name = "missing-argument-rs" +path = "missing-argument.rs" diff --git a/exercism/rust/macros/tests/invalid/comma-sep.rs b/exercism/rust/macros/tests/invalid/comma-sep.rs new file mode 100644 index 0000000..c9b6f44 --- /dev/null +++ b/exercism/rust/macros/tests/invalid/comma-sep.rs @@ -0,0 +1,7 @@ +use macros::hashmap; +use std::collections::HashMap; + +fn main() { + // using only commas is invalid + let _hm: HashMap<_, _> = hashmap!('a', 1); +} diff --git a/exercism/rust/macros/tests/invalid/double-commas.rs b/exercism/rust/macros/tests/invalid/double-commas.rs new file mode 100644 index 0000000..d52dec6 --- /dev/null +++ b/exercism/rust/macros/tests/invalid/double-commas.rs @@ -0,0 +1,7 @@ +use macros::hashmap; +use std::collections::HashMap; + +fn main() { + // a single trailing comma is okay, but two is not + let _hm: HashMap<_, _> = hashmap!('a' => 2, ,); +} diff --git a/exercism/rust/macros/tests/invalid/leading-comma.rs b/exercism/rust/macros/tests/invalid/leading-comma.rs new file mode 100644 index 0000000..bc03666 --- /dev/null +++ b/exercism/rust/macros/tests/invalid/leading-comma.rs @@ -0,0 +1,7 @@ +use macros::hashmap; +use std::collections::HashMap; + +fn main() { + // leading commas are not valid + let _hm: HashMap<_, _> = hashmap!(, 'a' => 2); +} diff --git a/exercism/rust/macros/tests/invalid/missing-argument.rs b/exercism/rust/macros/tests/invalid/missing-argument.rs new file mode 100644 index 0000000..893d609 --- /dev/null +++ b/exercism/rust/macros/tests/invalid/missing-argument.rs @@ -0,0 +1,7 @@ +use macros::hashmap; +use std::collections::HashMap; + +fn main() { + // an argument should come between each pair of commas + let _hm: HashMap<_, _> = hashmap!('a' => 1, , 'b' => 2); +} diff --git a/exercism/rust/macros/tests/invalid/no-comma.rs b/exercism/rust/macros/tests/invalid/no-comma.rs new file mode 100644 index 0000000..c4e6a92 --- /dev/null +++ b/exercism/rust/macros/tests/invalid/no-comma.rs @@ -0,0 +1,7 @@ +use macros::hashmap; +use std::collections::HashMap; + +fn main() { + // Key value pairs must be separated by commas + let _hm: HashMap<_, _> = hashmap!('a' => 1 'b' => 2); +} diff --git a/exercism/rust/macros/tests/invalid/only-arrow.rs b/exercism/rust/macros/tests/invalid/only-arrow.rs new file mode 100644 index 0000000..7f7d730 --- /dev/null +++ b/exercism/rust/macros/tests/invalid/only-arrow.rs @@ -0,0 +1,7 @@ +use macros::hashmap; +use std::collections::HashMap; + +fn main() { + // a single random arrow is not valid + let _hm: HashMap<(), ()> = hashmap!(=>); +} diff --git a/exercism/rust/macros/tests/invalid/only-comma.rs b/exercism/rust/macros/tests/invalid/only-comma.rs new file mode 100644 index 0000000..3b863b3 --- /dev/null +++ b/exercism/rust/macros/tests/invalid/only-comma.rs @@ -0,0 +1,7 @@ +use macros::hashmap; +use std::collections::HashMap; + +fn main() { + // a single random comma is not valid + let _hm: HashMap<(), ()> = hashmap!(,); +} diff --git a/exercism/rust/macros/tests/invalid/single-argument.rs b/exercism/rust/macros/tests/invalid/single-argument.rs new file mode 100644 index 0000000..f8ac092 --- /dev/null +++ b/exercism/rust/macros/tests/invalid/single-argument.rs @@ -0,0 +1,7 @@ +use macros::hashmap; +use std::collections::HashMap; + +fn main() { + // a single argument is invalid + let _hm: HashMap<_, _> = hashmap!('a'); +} diff --git a/exercism/rust/macros/tests/invalid/triple-arguments.rs b/exercism/rust/macros/tests/invalid/triple-arguments.rs new file mode 100644 index 0000000..54351ae --- /dev/null +++ b/exercism/rust/macros/tests/invalid/triple-arguments.rs @@ -0,0 +1,7 @@ +use macros::hashmap; +use std::collections::HashMap; + +fn main() { + // three arguments are invalid + hashmap!('a' => 1, 'b'); +} diff --git a/exercism/rust/macros/tests/invalid/two-arrows.rs b/exercism/rust/macros/tests/invalid/two-arrows.rs new file mode 100644 index 0000000..254a82e --- /dev/null +++ b/exercism/rust/macros/tests/invalid/two-arrows.rs @@ -0,0 +1,7 @@ +use macros::hashmap; +use std::collections::HashMap; + +fn main() { + // a trailing => isn't valid either + hashmap!('a' => 2, =>); +} diff --git a/exercism/rust/macros/tests/macros.rs b/exercism/rust/macros/tests/macros.rs new file mode 100644 index 0000000..8e21239 --- /dev/null +++ b/exercism/rust/macros/tests/macros.rs @@ -0,0 +1,216 @@ +use macros::hashmap; +use std::collections::HashMap; + +#[test] +fn empty() { + let expected: HashMap = HashMap::new(); + let computed: HashMap = hashmap!(); + assert_eq!(computed, expected); +} + +#[test] +#[ignore] +fn single() { + let mut expected = HashMap::new(); + expected.insert(1, "one"); + assert_eq!(hashmap!(1 => "one"), expected); +} + +#[test] +#[ignore] +fn no_trailing_comma() { + let mut expected = HashMap::new(); + expected.insert(1, "one"); + expected.insert(2, "two"); + assert_eq!(hashmap!(1 => "one", 2 => "two"), expected); +} + +#[test] +#[ignore] +fn trailing_comma() { + let mut expected = HashMap::new(); + expected.insert('h', 89); + expected.insert('a', 1); + expected.insert('s', 19); + expected.insert('h', 8); + assert_eq!( + hashmap!( + 'h' => 89, + 'a' => 1, + 's' => 19, + 'h' => 8, + ), + expected + ); +} + +#[test] +#[ignore] +fn nested() { + let mut expected = HashMap::new(); + expected.insert("non-empty", { + let mut subhashmap = HashMap::new(); + subhashmap.insert(23, 623); + subhashmap.insert(34, 21); + subhashmap + }); + expected.insert("empty", HashMap::new()); + assert_eq!( + hashmap!( + "non-empty" => hashmap!( + 23 => 623, + 34 => 21 + ), + "empty" => hashmap!() + ), + expected + ); +} + +mod test { + #[test] + #[ignore] + fn type_not_in_scope() { + use macros::hashmap; + + let _empty: ::std::collections::HashMap<(), ()> = hashmap!(); + let _without_comma = hashmap!(23=> 623, 34 => 21); + let _with_trailing = hashmap!(23 => 623, 34 => 21,); + } + + #[test] + #[ignore] + fn macro_out_of_scope() { + let _empty: ::std::collections::HashMap<(), ()> = macros::hashmap!(); + let _without_comma = macros::hashmap!(23=> 623, 34 => 21); + let _with_trailing = macros::hashmap!(23 => 623, 34 => 21,); + } +} + +#[test] +#[ignore] +fn type_override() { + // The macro should always use std::collections::HashMap and ignore crate::std::collections::HashMap + mod std { + pub mod collections { + pub struct HashMap; + + impl HashMap { + #[allow(dead_code)] + pub fn new() -> Self { + panic!("Do not allow users to override which HashMap is used"); + } + + #[allow(dead_code)] + pub fn insert(&mut self, _key: K, _val: V) { + panic!("Do not allow users to override which HashMap is used"); + } + } + } + } + + let _empty: ::std::collections::HashMap<(), ()> = hashmap!(); + let _without_comma = hashmap!(1 => 2, 3 => 4); + let _with_trailing = hashmap!(1 => 2, 3 => 4,); +} + +#[test] +#[ignore] +fn compile_fails_comma_sep() { + simple_trybuild::compile_fail("comma-sep.rs"); +} + +#[test] +#[ignore] +fn compile_fails_double_commas() { + simple_trybuild::compile_fail("double-commas.rs"); +} + +#[test] +#[ignore] +fn compile_fails_only_comma() { + simple_trybuild::compile_fail("only-comma.rs"); +} + +#[test] +#[ignore] +fn compile_fails_single_argument() { + simple_trybuild::compile_fail("single-argument.rs"); +} + +#[test] +#[ignore] +fn compile_fails_triple_arguments() { + simple_trybuild::compile_fail("triple-arguments.rs"); +} + +#[test] +#[ignore] +fn compile_fails_only_arrow() { + simple_trybuild::compile_fail("only-arrow.rs"); +} + +#[test] +#[ignore] +fn compile_fails_two_arrows() { + simple_trybuild::compile_fail("two-arrows.rs"); +} + +#[test] +#[ignore] +fn compile_fails_leading_comma() { + simple_trybuild::compile_fail("leading-comma.rs"); +} + +#[test] +#[ignore] +fn compile_fails_no_comma() { + simple_trybuild::compile_fail("no-comma.rs"); +} + +#[test] +#[ignore] +fn compile_fails_missing_argument() { + simple_trybuild::compile_fail("missing-argument.rs"); +} + +mod simple_trybuild { + use std::path::PathBuf; + use std::process::Command; + + pub fn compile_fail(file_name: &str) { + let invalid_path: PathBuf = ["tests", "invalid"].iter().collect::(); + + let mut file_path = invalid_path.clone(); + file_path.push(file_name); + assert!( + file_path.exists(), + "{:?} does not exist.", + file_path.into_os_string() + ); + + let test_name = file_name.replace('.', "-"); + let macros_dir = ["..", "..", "target", "tests", "macros"] + .iter() + .collect::(); + + let result = Command::new("cargo") + .current_dir(invalid_path) + .arg("build") + .arg("--offline") + .arg("--target-dir") + .arg(macros_dir) + .arg("--bin") + .arg(test_name) + .output(); + + if let Ok(result) = result { + assert!( + !result.status.success(), + "Expected {file_path:?} to fail to compile, but it succeeded." + ); + } else { + panic!("Running subprocess failed."); + } + } +}