🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉

# n0mn0m's solution

## to Macros in the Rust Track

Published at Nov 07 2020 · 0 comments
Instructions
Test suite
Solution

#### Note:

This exercise has changed since this solution was written.

Macros are a powerful part of a Rust programmer's toolkit, and macros by example are a relatively simple way to access this power. Let's write one!

## Context

What is a macro? Wikipedia 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 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 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` 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:

``````{
let mut hm = HashMap::new();
hm.insert('a', 3);
hm.insert('b', 11);
hm.insert('z', 32);
hm
}
``````

Note that the `maplit` crate 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.

## Compatibility

Note that this exercise requires Rust 1.36 or later.

## Rust Installation

Refer to the exercism help page for Rust installation and learning resources.

## Writing the Code

Execute the tests with:

``````\$ 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 all ignored tests without editing the tests source file, use:

``````\$ cargo test -- --ignored
``````

To run a specific test, for example `some_test`, you can use:

``````\$ cargo test some_test
``````

If the specific test is ignored use:

``````\$ cargo test some_test -- --ignored
``````

To learn more about Rust tests refer to the online test documentation

Make sure to read the Modules chapter if you haven't already, it will help you with organizing your files.

## Further improvements

After you have solved the exercise, please consider using the additional utilities, described in the installation guide, to further refine your final solution.

To format your solution, inside the solution directory use

``````cargo fmt
``````

To see, if your solution contains some common ineffective use cases, inside the solution directory use

``````cargo clippy --all-targets
``````

## 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 exercism/rust repository on 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.

## Source

Peter Goodspeed-Niklaus

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### Cargo.toml

``````#
# 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 = "2018"
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]]

### comma-sep.rs

``````use macros::hashmap;

fn main() {
// using only commas is invalid
let _hm: ::std::collections::HashMap<_, _> = hashmap!('a', 1);
}``````

### double-commas.rs

``````use macros::hashmap;

fn main() {
// a single trailing comma is okay, but two is not
let _hm: ::std::collections::HashMap<_, _> = hashmap!('a' => 2, ,);
}``````

``````use macros::hashmap;

fn main() {
// leading commas are not valid
let _hm: ::std::collections::HashMap<_, _> = hashmap!(, 'a' => 2);
}``````

### only-arrow.rs

``````use macros::hashmap;

fn main() {
// a single random arrow is not valid
let _hm: ::std::collections::HashMap<(), ()> = hashmap!(=>);
}``````

### only-comma.rs

``````use macros::hashmap;

fn main() {
// a single random comma is not valid
let _hm: ::std::collections::HashMap<(), ()> = hashmap!(,);
}``````

### single-argument.rs

``````use macros::hashmap;

fn main() {
// a single argument is invalid
let _hm: ::std::collections::HashMap<_, _> = hashmap!('a');
}``````

### triple-arguments.rs

``````use macros::hashmap;

fn main() {
// three arguments are invalid
hashmap!('a' => 1, 'b');
}``````

### two-arrows.rs

``````use macros::hashmap;

fn main() {
// a trailing => isn't valid either
hashmap!('a' => 2, =>);
}``````

### macros.rs

``````use macros::hashmap;
use std::collections::HashMap;

#[test]
fn test_empty() {
let expected: HashMap<u32, u32> = HashMap::new();
let computed: HashMap<u32, u32> = hashmap!();
assert_eq!(computed, expected);
}

#[test]
#[ignore]
fn test_single() {
let mut expected = HashMap::new();
expected.insert(1, "one");
assert_eq!(hashmap!(1 => "one"), expected);
}

#[test]
#[ignore]
fn test_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 test_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 test_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 test_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 test_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 {
pub fn new() -> Self {
panic!("Do not allow users to override which HashMap is used");
}

pub fn insert<K, V>(&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 test_compile_fails_comma_sep() {
simple_trybuild::compile_fail("comma-sep.rs");
}

#[test]
#[ignore]
fn test_compile_fails_double_commas() {
simple_trybuild::compile_fail("double-commas.rs");
}

#[test]
#[ignore]
fn test_compile_fails_only_comma() {
simple_trybuild::compile_fail("only-comma.rs");
}

#[test]
#[ignore]
fn test_compile_fails_single_argument() {
simple_trybuild::compile_fail("single-argument.rs");
}

#[test]
#[ignore]
fn test_compile_fails_triple_arguments() {
simple_trybuild::compile_fail("triple-arguments.rs");
}

#[test]
#[ignore]
fn test_compile_fails_only_arrow() {
simple_trybuild::compile_fail("only-arrow.rs");
}

#[test]
#[ignore]
fn test_compile_fails_two_arrows() {
simple_trybuild::compile_fail("two-arrows.rs");
}

#[test]
#[ignore]
}

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::<PathBuf>();

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::<PathBuf>();

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 {:?} to fail to compile, but it succeeded.",
file_path
);
} else {
panic!("Running subprocess failed.");
}
}
}``````
``````#[macro_export]
macro_rules! hashmap {
() => {
::std::collections::HashMap::default()
};
(\$(\$key:expr => \$value:expr),+ \$(,)?) => {
{
let mut map = ::std::collections::HashMap::new();
\$(map.insert(\$key, \$value);)*
map
}
};
}``````