Skip to content

Commit

Permalink
exercise: add macros
Browse files Browse the repository at this point in the history
  • Loading branch information
ruancomelli committed Mar 30, 2024
1 parent f939bab commit 1f17e12
Show file tree
Hide file tree
Showing 19 changed files with 563 additions and 0 deletions.
39 changes: 39 additions & 0 deletions exercism/rust/macros/.exercism/config.json
Original file line number Diff line number Diff line change
@@ -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."
}
}
1 change: 1 addition & 0 deletions exercism/rust/macros/.exercism/metadata.json
Original file line number Diff line number Diff line change
@@ -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}
8 changes: 8 additions & 0 deletions exercism/rust/macros/.gitignore
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions exercism/rust/macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
edition = "2021"
name = "macros"
version = "0.1.0"

[dependencies]
86 changes: 86 additions & 0 deletions exercism/rust/macros/HELP.md
Original file line number Diff line number Diff line change
@@ -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
64 changes: 64 additions & 0 deletions exercism/rust/macros/README.md
Original file line number Diff line number Diff line change
@@ -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
18 changes: 18 additions & 0 deletions exercism/rust/macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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))*
]
)
};
}
55 changes: 55 additions & 0 deletions exercism/rust/macros/tests/invalid/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
7 changes: 7 additions & 0 deletions exercism/rust/macros/tests/invalid/comma-sep.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use macros::hashmap;
use std::collections::HashMap;

fn main() {
// using only commas is invalid
let _hm: HashMap<_, _> = hashmap!('a', 1);
}
7 changes: 7 additions & 0 deletions exercism/rust/macros/tests/invalid/double-commas.rs
Original file line number Diff line number Diff line change
@@ -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, ,);
}
7 changes: 7 additions & 0 deletions exercism/rust/macros/tests/invalid/leading-comma.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use macros::hashmap;
use std::collections::HashMap;

fn main() {
// leading commas are not valid
let _hm: HashMap<_, _> = hashmap!(, 'a' => 2);
}
7 changes: 7 additions & 0 deletions exercism/rust/macros/tests/invalid/missing-argument.rs
Original file line number Diff line number Diff line change
@@ -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);
}
7 changes: 7 additions & 0 deletions exercism/rust/macros/tests/invalid/no-comma.rs
Original file line number Diff line number Diff line change
@@ -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);
}
7 changes: 7 additions & 0 deletions exercism/rust/macros/tests/invalid/only-arrow.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use macros::hashmap;
use std::collections::HashMap;

fn main() {
// a single random arrow is not valid
let _hm: HashMap<(), ()> = hashmap!(=>);
}
7 changes: 7 additions & 0 deletions exercism/rust/macros/tests/invalid/only-comma.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use macros::hashmap;
use std::collections::HashMap;

fn main() {
// a single random comma is not valid
let _hm: HashMap<(), ()> = hashmap!(,);
}
7 changes: 7 additions & 0 deletions exercism/rust/macros/tests/invalid/single-argument.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use macros::hashmap;
use std::collections::HashMap;

fn main() {
// a single argument is invalid
let _hm: HashMap<_, _> = hashmap!('a');
}
7 changes: 7 additions & 0 deletions exercism/rust/macros/tests/invalid/triple-arguments.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use macros::hashmap;
use std::collections::HashMap;

fn main() {
// three arguments are invalid
hashmap!('a' => 1, 'b');
}
7 changes: 7 additions & 0 deletions exercism/rust/macros/tests/invalid/two-arrows.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use macros::hashmap;
use std::collections::HashMap;

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

0 comments on commit 1f17e12

Please sign in to comment.