aboutsummaryrefslogtreecommitdiff
path: root/dot-dsl
diff options
context:
space:
mode:
Diffstat (limited to 'dot-dsl')
-rw-r--r--dot-dsl/.exercism/metadata.json1
-rw-r--r--dot-dsl/.gitignore8
-rw-r--r--dot-dsl/Cargo.toml7
-rw-r--r--dot-dsl/README.md121
-rw-r--r--dot-dsl/src/lib.rs119
-rw-r--r--dot-dsl/tests/dot-dsl.rs138
6 files changed, 394 insertions, 0 deletions
diff --git a/dot-dsl/.exercism/metadata.json b/dot-dsl/.exercism/metadata.json
new file mode 100644
index 0000000..5399056
--- /dev/null
+++ b/dot-dsl/.exercism/metadata.json
@@ -0,0 +1 @@
{"track":"rust","exercise":"dot-dsl","id":"57ca2e502fdf482aa52e91c4f4f7f51e","url":"https://exercism.io/my/solutions/57ca2e502fdf482aa52e91c4f4f7f51e","handle":"dyamon","is_requester":true,"auto_approve":false} \ No newline at end of file
diff --git a/dot-dsl/.gitignore b/dot-dsl/.gitignore
new file mode 100644
index 0000000..db7f315
--- /dev/null
+++ b/dot-dsl/.gitignore
@@ -0,0 +1,8 @@
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
8Cargo.lock
diff --git a/dot-dsl/Cargo.toml b/dot-dsl/Cargo.toml
new file mode 100644
index 0000000..3da0d67
--- /dev/null
+++ b/dot-dsl/Cargo.toml
@@ -0,0 +1,7 @@
1[package]
2edition = "2018"
3name = "dot-dsl"
4version = "0.1.0"
5
6[dependencies]
7maplit = "1.0.1"
diff --git a/dot-dsl/README.md b/dot-dsl/README.md
new file mode 100644
index 0000000..29e0e7a
--- /dev/null
+++ b/dot-dsl/README.md
@@ -0,0 +1,121 @@
1# DOT DSL
2
3A [Domain Specific Language (DSL)](https://en.wikipedia.org/wiki/Domain-specific_language) is a
4small language optimized for a specific domain. Since a DSL is
5targeted, it can greatly impact productivity/understanding by allowing the
6writer to declare *what* they want rather than *how*.
7
8One problem area where they are applied are complex customizations/configurations.
9
10For example the [DOT language](https://en.wikipedia.org/wiki/DOT_(graph_description_language)) allows
11you to write a textual description of a graph which is then transformed into a picture by one of
12the [Graphviz](http://graphviz.org/) tools (such as `dot`). A simple graph looks like this:
13
14 graph {
15 graph [bgcolor="yellow"]
16 a [color="red"]
17 b [color="blue"]
18 a -- b [color="green"]
19 }
20
21Putting this in a file `example.dot` and running `dot example.dot -T png
22-o example.png` creates an image `example.png` with red and blue circle
23connected by a green line on a yellow background.
24
25Write a Domain Specific Language similar to the Graphviz dot language.
26
27Our DSL is similar to the Graphviz dot language in that our DSL will be used
28to create graph data structures. However, unlike the DOT Language, our DSL will
29be an internal DSL for use only in our language.
30
31More information about the difference between internal and external DSLs can be
32found [here](https://martinfowler.com/bliki/DomainSpecificLanguage.html).
33
34## Builder pattern
35
36This exercise expects you to build several structs using `builder pattern`.
37In short, this pattern allows you to split the construction function of your struct, that contains a lot of arguments, into
38several separate functions. This approach gives you the means to make compact but highly-flexible struct construction and
39configuration.
40You can read more about it on the [following page](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html).
41
42
43## Rust Installation
44
45Refer to the [exercism help page][help-page] for Rust installation and learning
46resources.
47
48## Writing the Code
49
50Execute the tests with:
51
52```bash
53$ cargo test
54```
55
56All but the first test have been ignored. After you get the first test to
57pass, open the tests source file which is located in the `tests` directory
58and remove the `#[ignore]` flag from the next test and get the tests to pass
59again. Each separate test is a function with `#[test]` flag above it.
60Continue, until you pass every test.
61
62If you wish to run all ignored tests without editing the tests source file, use:
63
64```bash
65$ cargo test -- --ignored
66```
67
68To run a specific test, for example `some_test`, you can use:
69
70```bash
71$ cargo test some_test
72```
73
74If the specific test is ignored use:
75
76```bash
77$ cargo test some_test -- --ignored
78```
79
80To learn more about Rust tests refer to the [online test documentation][rust-tests]
81
82Make sure to read the [Modules][modules] chapter if you
83haven't already, it will help you with organizing your files.
84
85## Further improvements
86
87After you have solved the exercise, please consider using the additional utilities, described in the [installation guide](https://exercism.io/tracks/rust/installation), to further refine your final solution.
88
89To format your solution, inside the solution directory use
90
91```bash
92cargo fmt
93```
94
95To see, if your solution contains some common ineffective use cases, inside the solution directory use
96
97```bash
98cargo clippy --all-targets
99```
100
101## Submitting the solution
102
103Generally 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.
104
105## Feedback, Issues, Pull Requests
106
107The [exercism/rust](https://github.com/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!
108
109If you want to know more about Exercism, take a look at the [contribution guide](https://github.com/exercism/docs/blob/master/contributing-to-language-tracks/README.md).
110
111[help-page]: https://exercism.io/tracks/rust/learning
112[modules]: https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html
113[cargo]: https://doc.rust-lang.org/book/ch14-00-more-about-cargo.html
114[rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html
115
116## Source
117
118Wikipedia [https://en.wikipedia.org/wiki/DOT_(graph_description_language)](https://en.wikipedia.org/wiki/DOT_(graph_description_language))
119
120## Submitting Incomplete Solutions
121It's possible to submit an incomplete solution so you can see how others have completed the exercise.
diff --git a/dot-dsl/src/lib.rs b/dot-dsl/src/lib.rs
new file mode 100644
index 0000000..654ee09
--- /dev/null
+++ b/dot-dsl/src/lib.rs
@@ -0,0 +1,119 @@
1pub mod graph {
2
3 use graph_items::edge::Edge;
4 use graph_items::node::Node;
5 use std::collections::HashMap;
6
7 pub mod graph_items {
8
9 pub mod node {
10
11 use std::collections::HashMap;
12
13 #[derive(Default, Debug, PartialEq, Eq, Clone)]
14 pub struct Node<'a> {
15 pub name: &'a str,
16 attrs: HashMap<String, String>,
17 }
18
19 impl<'a> Node<'a> {
20 pub fn new(name: &'a str) -> Node<'a> {
21 Node {
22 name,
23 ..Default::default()
24 }
25 }
26
27 pub fn with_attrs(mut self, attrs: &[(&'a str, &'a str)]) -> Node<'a> {
28 for (key, value) in attrs {
29 self.attrs.insert(key.to_string(), value.to_string());
30 }
31 self
32 }
33
34 pub fn get_attr(&self, key: &str) -> Option<&str> {
35 self.attrs.get(key).map(|s| &s[..])
36 }
37 }
38 }
39
40 pub mod edge {
41
42 use std::collections::HashMap;
43
44 #[derive(Default, Debug, PartialEq, Eq, Clone)]
45 pub struct Edge<'a> {
46 pub x: &'a str,
47 pub y: &'a str,
48 attrs: HashMap<String, String>,
49 }
50
51 impl<'a> Edge<'a> {
52 pub fn new(x: &'a str, y: &'a str) -> Edge<'a> {
53 Edge {
54 x,
55 y,
56 ..Default::default()
57 }
58 }
59
60 pub fn with_attrs(mut self, attrs: &[(&'a str, &'a str)]) -> Edge<'a> {
61 for (key, value) in attrs {
62 self.attrs.insert(key.to_string(), value.to_string());
63 }
64 self
65 }
66
67 pub fn get_attr(&self, key: &str) -> Option<&str> {
68 self.attrs.get(key).map(|s| &s[..])
69 }
70 }
71 }
72 }
73
74 #[derive(Default, Debug)]
75 pub struct Graph<'a> {
76 pub nodes: Vec<Node<'a>>,
77 pub edges: Vec<Edge<'a>>,
78 pub attrs: HashMap<String, String>,
79 }
80
81 impl<'a> Graph<'a> {
82 pub fn new() -> Self {
83 Default::default()
84 }
85
86 pub fn with_attrs(mut self, attrs: &[(&'a str, &'a str)]) -> Graph<'a> {
87 for (key, value) in attrs {
88 self.attrs.insert(key.to_string(), value.to_string());
89 }
90 self
91 }
92
93 pub fn with_nodes(mut self, nodes: &[Node<'a>]) -> Graph<'a> {
94 for node in nodes {
95 self.nodes.push(node.clone());
96 }
97 self
98 }
99
100 pub fn with_edges(mut self, edges: &[Edge<'a>]) -> Graph<'a> {
101 for edge in edges {
102 self.edges.push(edge.clone())
103 }
104 self
105 }
106
107 pub fn get_node(&self, name: &str) -> Option<&Node<'a>> {
108 self.nodes.iter().find(|&node| node.name == name)
109 }
110
111 pub fn get_edge(&self, x: &str, y: &str) -> Option<&Edge<'a>> {
112 self.edges.iter().find(|&edge| edge.x == x && edge.y == y)
113 }
114
115 pub fn get_attr(&self, key: &str) -> Option<&str> {
116 self.attrs.get(key).map(|s| &s[..])
117 }
118 }
119}
diff --git a/dot-dsl/tests/dot-dsl.rs b/dot-dsl/tests/dot-dsl.rs
new file mode 100644
index 0000000..ae469b7
--- /dev/null
+++ b/dot-dsl/tests/dot-dsl.rs
@@ -0,0 +1,138 @@
1use dot_dsl::graph::graph_items::edge::Edge;
2use dot_dsl::graph::graph_items::node::Node;
3use dot_dsl::graph::Graph;
4use maplit::hashmap;
5
6#[test]
7fn test_empty_graph() {
8 let graph = Graph::new();
9
10 assert!(graph.nodes.is_empty());
11
12 assert!(graph.edges.is_empty());
13
14 assert!(graph.attrs.is_empty());
15}
16
17#[test]
18fn test_graph_with_one_node() {
19 let nodes = vec![Node::new("a")];
20
21 let graph = Graph::new().with_nodes(&nodes);
22
23 assert!(graph.edges.is_empty());
24
25 assert!(graph.attrs.is_empty());
26
27 assert_eq!(graph.nodes, vec![Node::new("a")]);
28}
29
30#[test]
31fn test_graph_with_one_node_with_keywords() {
32 let nodes = vec![Node::new("a").with_attrs(&[("color", "green")])];
33
34 let graph = Graph::new().with_nodes(&nodes);
35
36 assert!(graph.edges.is_empty());
37
38 assert!(graph.attrs.is_empty());
39
40 assert_eq!(
41 graph.nodes,
42 vec![Node::new("a").with_attrs(&[("color", "green")])]
43 );
44}
45
46#[test]
47fn test_graph_with_one_edge() {
48 let edges = vec![Edge::new("a", "b")];
49
50 let graph = Graph::new().with_edges(&edges);
51
52 assert!(graph.nodes.is_empty());
53
54 assert!(graph.attrs.is_empty());
55
56 assert_eq!(graph.edges, vec![Edge::new("a", "b")]);
57}
58
59#[test]
60fn test_graph_with_one_attribute() {
61 let graph = Graph::new().with_attrs(&[("foo", "1")]);
62
63 let expected_attrs = hashmap! {
64 "foo".to_string() => "1".to_string(),
65 };
66
67 assert!(graph.nodes.is_empty());
68
69 assert!(graph.edges.is_empty());
70
71 assert_eq!(graph.attrs, expected_attrs);
72}
73
74#[test]
75fn test_graph_with_attributes() {
76 let nodes = vec![
77 Node::new("a").with_attrs(&[("color", "green")]),
78 Node::new("c"),
79 Node::new("b").with_attrs(&[("label", "Beta!")]),
80 ];
81
82 let edges = vec![
83 Edge::new("b", "c"),
84 Edge::new("a", "b").with_attrs(&[("color", "blue")]),
85 ];
86
87 let attrs = vec![("foo", "1"), ("title", "Testing Attrs"), ("bar", "true")];
88
89 let expected_attrs = hashmap! {
90 "foo".to_string() => "1".to_string(),
91 "title".to_string() => "Testing Attrs".to_string(),
92 "bar".to_string() => "true".to_string(),
93 };
94
95 let graph = Graph::new()
96 .with_nodes(&nodes)
97 .with_edges(&edges)
98 .with_attrs(&attrs);
99
100 assert_eq!(
101 graph.nodes,
102 vec![
103 Node::new("a").with_attrs(&[("color", "green")]),
104 Node::new("c"),
105 Node::new("b").with_attrs(&[("label", "Beta!")]),
106 ]
107 );
108
109 assert_eq!(
110 graph.edges,
111 vec![
112 Edge::new("b", "c"),
113 Edge::new("a", "b").with_attrs(&[("color", "blue")]),
114 ]
115 );
116
117 assert_eq!(graph.attrs, expected_attrs);
118}
119
120#[test]
121fn test_graph_stores_attributes() {
122 let attributes = [("foo", "bar"), ("bat", "baz"), ("bim", "bef")];
123 let graph = Graph::new().with_nodes(
124 &["a", "b", "c"]
125 .iter()
126 .zip(attributes.iter())
127 .map(|(name, &attr)| Node::new(&name).with_attrs(&[attr]))
128 .collect::<Vec<_>>(),
129 );
130
131 assert_eq!(
132 graph
133 .get_node("c")
134 .expect("node must be stored")
135 .get_attr("bim"),
136 Some("bef")
137 );
138}