Exercism track submissions
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

macros

+565
+5
.vscode/extensions.json
··· 1 + { 2 + "recommendations": [ 3 + "matklad.rust-analyzer" 4 + ] 5 + }
+35
rust/macros/.exercism/config.json
··· 1 + { 2 + "blurb": "Implement a macro using macros-by-example", 3 + "source": "Peter Goodspeed-Niklaus", 4 + "authors": [ 5 + "coriolinus" 6 + ], 7 + "contributors": [ 8 + "bantic", 9 + "cwhakes", 10 + "DarthStrom", 11 + "efx", 12 + "Emerentius", 13 + "ErikSchierboom", 14 + "lutostag", 15 + "pedantic79", 16 + "petertseng", 17 + "rofrol", 18 + "ssomers", 19 + "stringparser", 20 + "tjade273", 21 + "xakon", 22 + "ZapAnton" 23 + ], 24 + "files": { 25 + "solution": [ 26 + "src/lib.rs" 27 + ], 28 + "test": [ 29 + "tests/macros.rs" 30 + ], 31 + "example": [ 32 + ".meta/example.rs" 33 + ] 34 + } 35 + }
+8
rust/macros/.gitignore
··· 1 + # Generated by Cargo 2 + # will have compiled files and executables 3 + /target/ 4 + **/*.rs.bk 5 + 6 + # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 + # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 8 + Cargo.lock
+6
rust/macros/Cargo.toml
··· 1 + [package] 2 + edition = "2021" 3 + name = "macros" 4 + version = "0.1.0" 5 + 6 + [dependencies]
+85
rust/macros/HELP.md
··· 1 + # Help 2 + 3 + ## Running the tests 4 + 5 + Execute the tests with: 6 + 7 + ```bash 8 + $ cargo test 9 + ``` 10 + 11 + All but the first test have been ignored. After you get the first test to 12 + pass, open the tests source file which is located in the `tests` directory 13 + and remove the `#[ignore]` flag from the next test and get the tests to pass 14 + again. Each separate test is a function with `#[test]` flag above it. 15 + Continue, until you pass every test. 16 + 17 + If you wish to run _only ignored_ tests without editing the tests source file, use: 18 + 19 + ```bash 20 + $ cargo test -- --ignored 21 + ``` 22 + 23 + If you are using Rust 1.51 or later, you can run _all_ tests with 24 + 25 + ```bash 26 + $ cargo test -- --include-ignored 27 + ``` 28 + 29 + To run a specific test, for example `some_test`, you can use: 30 + 31 + ```bash 32 + $ cargo test some_test 33 + ``` 34 + 35 + If the specific test is ignored, use: 36 + 37 + ```bash 38 + $ cargo test some_test -- --ignored 39 + ``` 40 + 41 + To learn more about Rust tests refer to the online [test documentation][rust-tests]. 42 + 43 + [rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html 44 + 45 + ## Submitting your solution 46 + 47 + You can submit your solution using the `exercism submit src/lib.rs` command. 48 + This command will upload your solution to the Exercism website and print the solution page's URL. 49 + 50 + It's possible to submit an incomplete solution which allows you to: 51 + 52 + - See how others have completed the exercise 53 + - Request help from a mentor 54 + 55 + ## Need to get help? 56 + 57 + If you'd like help solving the exercise, check the following pages: 58 + 59 + - The [Rust track's documentation](https://exercism.org/docs/tracks/rust) 60 + - [Exercism's support channel on gitter](https://gitter.im/exercism/support) 61 + - The [Frequently Asked Questions](https://exercism.org/docs/using/faqs) 62 + 63 + Should those resources not suffice, you could submit your (incomplete) solution to request mentoring. 64 + 65 + ## Rust Installation 66 + 67 + Refer to the [exercism help page][help-page] for Rust installation and learning 68 + resources. 69 + 70 + ## Submitting the solution 71 + 72 + 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. 73 + 74 + ## Feedback, Issues, Pull Requests 75 + 76 + 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! 77 + 78 + If you want to know more about Exercism, take a look at the [contribution guide]. 79 + 80 + ## Submitting Incomplete Solutions 81 + It's possible to submit an incomplete solution so you can see how others have completed the exercise. 82 + 83 + [help-page]: https://exercism.io/tracks/rust/learning 84 + [github]: https://github.com/exercism/rust 85 + [contribution guide]: https://exercism.io/docs/community/contributors
+66
rust/macros/README.md
··· 1 + # Macros 2 + 3 + Welcome to Macros on Exercism's Rust Track. 4 + If you need help running the tests or submitting your code, check out `HELP.md`. 5 + 6 + ## Instructions 7 + 8 + 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! 9 + 10 + ## Context 11 + 12 + What is a macro? [Wikipedia](https://en.wikipedia.org/wiki/Macro_(computer_science)) describes it thus: 13 + 14 + > 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. 15 + 16 + 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. 17 + 18 + 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. 19 + 20 + ## Problem Statement 21 + 22 + 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. 23 + 24 + For example, a user of your library might write `hashmap!('a' => 3, 'b' => 11, 'z' => 32)`. This should expand to the following code: 25 + 26 + ```rust 27 + { 28 + let mut hm = HashMap::new(); 29 + hm.insert('a', 3); 30 + hm.insert('b', 11); 31 + hm.insert('z', 32); 32 + hm 33 + } 34 + ``` 35 + 36 + 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. 37 + 38 + Note that this exercise requires Rust 1.36 or later. 39 + 40 + ## Source 41 + 42 + ### Created by 43 + 44 + - @coriolinus 45 + 46 + ### Contributed to by 47 + 48 + - @bantic 49 + - @cwhakes 50 + - @DarthStrom 51 + - @efx 52 + - @Emerentius 53 + - @ErikSchierboom 54 + - @lutostag 55 + - @pedantic79 56 + - @petertseng 57 + - @rofrol 58 + - @ssomers 59 + - @stringparser 60 + - @tjade273 61 + - @xakon 62 + - @ZapAnton 63 + 64 + ### Based on 65 + 66 + Peter Goodspeed-Niklaus
+18
rust/macros/src/lib.rs
··· 1 + #[macro_export] 2 + macro_rules! hashmap { 3 + (@internal $($key:expr => $value:expr),*) => { 4 + { 5 + let mut hm = crate::HashMap::new(); 6 + $( 7 + hm.insert($key, $value); 8 + )* 9 + hm 10 + } 11 + }; 12 + ($($key:expr => $value:expr),+,) => { 13 + crate::hashmap!(@internal $($key => $value),*); 14 + }; 15 + ($($key:expr => $value:expr),*) => { 16 + crate::hashmap!(@internal $($key => $value),*); 17 + }; 18 + }
+55
rust/macros/tests/invalid/Cargo.toml
··· 1 + # 2 + # This Cargo.toml file is used by the simple-trybuild module. 3 + # When adding a new file, please name the [[bin]] name to match the file 4 + # it is used to produce an error message 5 + # 6 + 7 + [package] 8 + name = "macros-tests" 9 + version = "0.0.0" 10 + edition = "2021" 11 + publish = false 12 + 13 + [dependencies.macros] 14 + path = "../../" 15 + default-features = false 16 + 17 + [[bin]] 18 + name = "comma-sep-rs" 19 + path = "comma-sep.rs" 20 + 21 + [[bin]] 22 + name = "double-commas-rs" 23 + path = "double-commas.rs" 24 + 25 + [[bin]] 26 + name = "only-arrow-rs" 27 + path = "only-arrow.rs" 28 + 29 + [[bin]] 30 + name = "only-comma-rs" 31 + path = "only-comma.rs" 32 + 33 + [[bin]] 34 + name = "single-argument-rs" 35 + path = "single-argument.rs" 36 + 37 + [[bin]] 38 + name = "triple-arguments-rs" 39 + path = "triple-arguments.rs" 40 + 41 + [[bin]] 42 + name = "two-arrows-rs" 43 + path = "two-arrows.rs" 44 + 45 + [[bin]] 46 + name = "leading-comma-rs" 47 + path = "leading-comma.rs" 48 + 49 + [[bin]] 50 + name = "no-comma-rs" 51 + path = "no-comma.rs" 52 + 53 + [[bin]] 54 + name = "missing-argument-rs" 55 + path = "missing-argument.rs"
+7
rust/macros/tests/invalid/comma-sep.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + fn main() { 5 + // using only commas is invalid 6 + let _hm: HashMap<_, _> = hashmap!('a', 1); 7 + }
+7
rust/macros/tests/invalid/double-commas.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + fn main() { 5 + // a single trailing comma is okay, but two is not 6 + let _hm: HashMap<_, _> = hashmap!('a' => 2, ,); 7 + }
+7
rust/macros/tests/invalid/leading-comma.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + fn main() { 5 + // leading commas are not valid 6 + let _hm: HashMap<_, _> = hashmap!(, 'a' => 2); 7 + }
+7
rust/macros/tests/invalid/missing-argument.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + fn main() { 5 + // an argument should come between each pair of commas 6 + let _hm: HashMap<_, _> = hashmap!('a' => 1, , 'b' => 2); 7 + }
+7
rust/macros/tests/invalid/no-comma.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + fn main() { 5 + // Key value pairs must be separated by commas 6 + let _hm: HashMap<_, _> = hashmap!('a' => 1 'b' => 2); 7 + }
+7
rust/macros/tests/invalid/only-arrow.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + fn main() { 5 + // a single random arrow is not valid 6 + let _hm: HashMap<(), ()> = hashmap!(=>); 7 + }
+7
rust/macros/tests/invalid/only-comma.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + fn main() { 5 + // a single random comma is not valid 6 + let _hm: HashMap<(), ()> = hashmap!(,); 7 + }
+7
rust/macros/tests/invalid/single-argument.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + fn main() { 5 + // a single argument is invalid 6 + let _hm: HashMap<_, _> = hashmap!('a'); 7 + }
+7
rust/macros/tests/invalid/triple-arguments.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + fn main() { 5 + // three arguments are invalid 6 + hashmap!('a' => 1, 'b'); 7 + }
+7
rust/macros/tests/invalid/two-arrows.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + fn main() { 5 + // a trailing => isn't valid either 6 + hashmap!('a' => 2, =>); 7 + }
+217
rust/macros/tests/macros.rs
··· 1 + use macros::hashmap; 2 + use std::collections::HashMap; 3 + 4 + #[test] 5 + fn test_empty() { 6 + let expected: HashMap<u32, u32> = HashMap::new(); 7 + let computed: HashMap<u32, u32> = hashmap!(); 8 + assert_eq!(computed, expected); 9 + } 10 + 11 + #[test] 12 + #[ignore] 13 + fn test_single() { 14 + let mut expected = HashMap::new(); 15 + expected.insert(1, "one"); 16 + assert_eq!(hashmap!(1 => "one"), expected); 17 + } 18 + 19 + #[test] 20 + #[ignore] 21 + fn test_no_trailing_comma() { 22 + let mut expected = HashMap::new(); 23 + expected.insert(1, "one"); 24 + expected.insert(2, "two"); 25 + assert_eq!(hashmap!(1 => "one", 2 => "two"), expected); 26 + } 27 + 28 + #[test] 29 + #[ignore] 30 + fn test_trailing_comma() { 31 + let mut expected = HashMap::new(); 32 + expected.insert('h', 89); 33 + expected.insert('a', 1); 34 + expected.insert('s', 19); 35 + expected.insert('h', 8); 36 + assert_eq!( 37 + hashmap!( 38 + 'h' => 89, 39 + 'a' => 1, 40 + 's' => 19, 41 + 'h' => 8, 42 + ), 43 + expected 44 + ); 45 + } 46 + 47 + #[test] 48 + #[ignore] 49 + fn test_nested() { 50 + let mut expected = HashMap::new(); 51 + expected.insert("non-empty", { 52 + let mut subhashmap = HashMap::new(); 53 + subhashmap.insert(23, 623); 54 + subhashmap.insert(34, 21); 55 + subhashmap 56 + }); 57 + expected.insert("empty", HashMap::new()); 58 + assert_eq!( 59 + hashmap!( 60 + "non-empty" => hashmap!( 61 + 23 => 623, 62 + 34 => 21 63 + ), 64 + "empty" => hashmap!() 65 + ), 66 + expected 67 + ); 68 + } 69 + 70 + mod test { 71 + #[test] 72 + #[ignore] 73 + fn type_not_in_scope() { 74 + use macros::hashmap; 75 + 76 + let _empty: ::std::collections::HashMap<(), ()> = hashmap!(); 77 + let _without_comma = hashmap!(23=> 623, 34 => 21); 78 + let _with_trailing = hashmap!(23 => 623, 34 => 21,); 79 + } 80 + 81 + #[test] 82 + #[ignore] 83 + fn test_macro_out_of_scope() { 84 + let _empty: ::std::collections::HashMap<(), ()> = macros::hashmap!(); 85 + let _without_comma = macros::hashmap!(23=> 623, 34 => 21); 86 + let _with_trailing = macros::hashmap!(23 => 623, 34 => 21,); 87 + } 88 + } 89 + 90 + #[test] 91 + #[ignore] 92 + fn test_type_override() { 93 + // The macro should always use std::collections::HashMap and ignore crate::std::collections::HashMap 94 + mod std { 95 + pub mod collections { 96 + pub struct HashMap; 97 + 98 + impl HashMap { 99 + #[allow(dead_code)] 100 + pub fn new() -> Self { 101 + panic!("Do not allow users to override which HashMap is used"); 102 + } 103 + 104 + #[allow(dead_code)] 105 + pub fn insert<K, V>(&mut self, _key: K, _val: V) { 106 + panic!("Do not allow users to override which HashMap is used"); 107 + } 108 + } 109 + } 110 + } 111 + 112 + let _empty: ::std::collections::HashMap<(), ()> = hashmap!(); 113 + let _without_comma = hashmap!(1 => 2, 3 => 4); 114 + let _with_trailing = hashmap!(1 => 2, 3 => 4,); 115 + } 116 + 117 + #[test] 118 + #[ignore] 119 + fn test_compile_fails_comma_sep() { 120 + simple_trybuild::compile_fail("comma-sep.rs"); 121 + } 122 + 123 + #[test] 124 + #[ignore] 125 + fn test_compile_fails_double_commas() { 126 + simple_trybuild::compile_fail("double-commas.rs"); 127 + } 128 + 129 + #[test] 130 + #[ignore] 131 + fn test_compile_fails_only_comma() { 132 + simple_trybuild::compile_fail("only-comma.rs"); 133 + } 134 + 135 + #[test] 136 + #[ignore] 137 + fn test_compile_fails_single_argument() { 138 + simple_trybuild::compile_fail("single-argument.rs"); 139 + } 140 + 141 + #[test] 142 + #[ignore] 143 + fn test_compile_fails_triple_arguments() { 144 + simple_trybuild::compile_fail("triple-arguments.rs"); 145 + } 146 + 147 + #[test] 148 + #[ignore] 149 + fn test_compile_fails_only_arrow() { 150 + simple_trybuild::compile_fail("only-arrow.rs"); 151 + } 152 + 153 + #[test] 154 + #[ignore] 155 + fn test_compile_fails_two_arrows() { 156 + simple_trybuild::compile_fail("two-arrows.rs"); 157 + } 158 + 159 + #[test] 160 + #[ignore] 161 + fn test_compile_fails_leading_comma() { 162 + simple_trybuild::compile_fail("leading-comma.rs"); 163 + } 164 + 165 + #[test] 166 + #[ignore] 167 + fn test_compile_fails_no_comma() { 168 + simple_trybuild::compile_fail("no-comma.rs"); 169 + } 170 + 171 + #[test] 172 + #[ignore] 173 + fn test_compile_fails_missing_argument() { 174 + simple_trybuild::compile_fail("missing-argument.rs"); 175 + } 176 + 177 + mod simple_trybuild { 178 + use std::path::PathBuf; 179 + use std::process::Command; 180 + 181 + pub fn compile_fail(file_name: &str) { 182 + let invalid_path: PathBuf = ["tests", "invalid"].iter().collect::<PathBuf>(); 183 + 184 + let mut file_path = invalid_path.clone(); 185 + file_path.push(file_name); 186 + assert!( 187 + file_path.exists(), 188 + "{:?} does not exist.", 189 + file_path.into_os_string() 190 + ); 191 + 192 + let test_name = file_name.replace('.', "-"); 193 + let macros_dir = ["..", "..", "target", "tests", "macros"] 194 + .iter() 195 + .collect::<PathBuf>(); 196 + 197 + let result = Command::new("cargo") 198 + .current_dir(invalid_path) 199 + .arg("build") 200 + .arg("--offline") 201 + .arg("--target-dir") 202 + .arg(macros_dir) 203 + .arg("--bin") 204 + .arg(test_name) 205 + .output(); 206 + 207 + if let Ok(result) = result { 208 + assert!( 209 + !result.status.success(), 210 + "Expected {:?} to fail to compile, but it succeeded.", 211 + file_path 212 + ); 213 + } else { 214 + panic!("Running subprocess failed."); 215 + } 216 + } 217 + }