Skip to content

Commit 0eca7f6

Browse files
New concept exercise top-secret (concept: ast) (#930)
Co-authored-by: Jie <[email protected]>
1 parent b909c02 commit 0eca7f6

File tree

17 files changed

+744
-1
lines changed

17 files changed

+744
-1
lines changed

concepts/ast/.meta/config.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"blurb": "The Abstract Syntax Tree is a way to represent Elixir code as data.",
3+
"authors": [
4+
"angelikatyborska"
5+
],
6+
"contributors": [
7+
]
8+
}

concepts/ast/about.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# About
2+
3+
The Abstract Syntax Tree (AST), also called a [_quoted expression_][getting-started-quote], is a way to represent code as data.
4+
5+
Each node in the AST is a three-element tuple.
6+
7+
```elixir
8+
# AST representation of:
9+
# 2 + 3
10+
{:+, [], [2, 3]}
11+
```
12+
13+
The first element, an atom, is the operation. The second element, a keyword list, is the metadata. The third element is a list of arguments, which contains other nodes. Literal values such as integers, atoms, and strings are represented in the AST as themselves instead of three-element tuples.
14+
15+
## Turning code into ASTs
16+
17+
Changing Elixir code to ASTs and ASTs back to code is part of the standard library. You can find functions for working with ASTs in the modules `Code` (e.g. [to change a string with code to an AST][doc-code-string-to-quoted]) and `Macro` (e.g. [to traverse the AST or change it to a string][macro-prewalk]).
18+
19+
Note that all of the functions in the standard library use the name "quoted" to mean the AST (short for _quoted expression_).
20+
21+
The special form for turning code into an AST is called [`quote`][doc-quote]. It accepts a code block and returns its AST.
22+
23+
```elixir
24+
quote do
25+
2 + 3 - 1
26+
end
27+
28+
# => {:-, [], [
29+
# {:+, [], [2, 3]},
30+
# 1
31+
# ]}
32+
```
33+
34+
## Use cases
35+
36+
The ability to represent code as an AST is at the heart of metaprogramming in Elixir. _Macros_, which is a way to write Elixir code that produces Elixir code, work by returning ASTs as output.
37+
38+
Another use case for ASTs is static code analysis, like Exercism's own tool, the Analyzer, which you might already know as the little bot that leaves comments on your solutions.
39+
40+
[getting-started-quote]: https://elixir-lang.org/getting-started/meta/quote-and-unquote.html#quoting
41+
[doc-quote]: https://hexdocs.pm/elixir/Kernel.SpecialForms.html#quote/2
42+
[doc-code-string-to-quoted]: https://hexdocs.pm/elixir/Code.html#string_to_quoted/2
43+
[macro-prewalk]: https://hexdocs.pm/elixir/Macro.html#prewalk/3

concepts/ast/introduction.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Introduction
2+
3+
The Abstract Syntax Tree (AST), also called a _quoted expression_, is a way to represent code as data.
4+
5+
Each node in the AST is a three-element tuple.
6+
7+
```elixir
8+
# AST representation of:
9+
# 2 + 3
10+
{:+, [], [2, 3]}
11+
```
12+
13+
The first element, an atom, is the operation. The second element, a keyword list, is the metadata. The third element is a list of arguments, which contains other nodes. Literal values such as integers, atoms, and strings are represented in the AST as themselves instead of three-element tuples.
14+
15+
## Turning code into ASTs
16+
17+
Changing Elixir code to ASTs and ASTs back to code is part of the standard library. You can find functions for working with ASTs in the modules `Code` (e.g. to change a string with code to an AST) and `Macro` (e.g. to traverse the AST or change it to a string).
18+
19+
Note that all of the functions in the standard library use the name "quoted" to mean the AST (short for _quoted expression_).
20+
21+
The special form for turning code into an AST is called `quote`. It accepts a code block and returns its AST.
22+
23+
```elixir
24+
quote do
25+
2 + 3 - 1
26+
end
27+
28+
# => {:-, [], [
29+
# {:+, [], [2, 3]},
30+
# 1
31+
# ]}
32+
```
33+
34+
## Use cases
35+
36+
The ability to represent code as an AST is at the heart of metaprogramming in Elixir. _Macros_, which is a way to write Elixir code that produces Elixir code, work by returning ASTs as output.
37+
38+
Another use case for ASTs is static code analysis, like Exercism's own tool, the Analyzer, which you might already know as the little bot that leaves comments on your solutions.

concepts/ast/links.json

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[
2+
{
3+
"url": "https://elixir-lang.org/getting-started/meta/quote-and-unquote.html#quoting",
4+
"description": "Getting Started - quoting"
5+
},
6+
{
7+
"url": "https://dorgan.ar/posts/2021/04/the_elixir_ast/",
8+
"description": "Introduction to Elixir AST by Lucas San Román"
9+
},
10+
{
11+
"url": "https://hexdocs.pm/elixir/Code.html",
12+
"description": "The Code module"
13+
},
14+
{
15+
"url": "https://hexdocs.pm/elixir/Macro.html",
16+
"description": "The Macro module"
17+
}
18+
]

config.json

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -596,6 +596,23 @@
596596
"dates-and-time"
597597
],
598598
"status": "beta"
599+
},
600+
{
601+
"slug": "top-secret",
602+
"name": "Top Secret",
603+
"uuid": "4caa7349-836b-4d6e-b3cb-b3133c305013",
604+
"concepts": [
605+
"ast"
606+
],
607+
"prerequisites": [
608+
"atoms",
609+
"tuples",
610+
"strings",
611+
"pattern-matching",
612+
"guards",
613+
"enum"
614+
],
615+
"status": "beta"
599616
}
600617
],
601618
"practice": [
@@ -2647,7 +2664,8 @@
26472664
"errors",
26482665
"exceptions",
26492666
"keyword-lists",
2650-
"nil"
2667+
"nil",
2668+
"ast"
26512669
],
26522670
"practices": [
26532671
"keyword-lists"
@@ -2874,6 +2892,11 @@
28742892
"slug": "anonymous-functions",
28752893
"name": "Anonymous Functions"
28762894
},
2895+
{
2896+
"uuid": "550fac1f-c1dc-4eb5-92f2-5ac0e893be2a",
2897+
"slug": "ast",
2898+
"name": "AST"
2899+
},
28772900
{
28782901
"uuid": "0bc1ad03-5ec7-4269-ad33-df6decbb5ee2",
28792902
"slug": "atoms",
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Hints
2+
3+
## General
4+
5+
- Read about quoting in the [official Getting Started guide][getting-started-quote].
6+
- Read the [introduction to Elixir AST by Lucas San Román][ast-intro-lucas].
7+
- Read [the official documentation for `quote`][doc-quote].
8+
- Inspect the output of [`quote`][doc-quote] to familiarize yourself with how ASTs look like for specific code snippets.
9+
10+
## 1. Turn code into data
11+
12+
- There is a [built-in function][doc-code-string-to-quoted] that turns a string with code into an AST.
13+
14+
## 2. Parse a single AST node
15+
16+
- Inspect the output of [`quote`][doc-quote] to familiarize yourself with how ASTs look like for specific code snippets.
17+
- The operations that define a function are `:def` and `:defp`.
18+
- The operation is the first element in a three-element AST node tuple.
19+
- You can ignore the second element in the tuple in this exercise completely.
20+
- The third element in the tuple is the argument list of the operation that defines the function.
21+
- The first element on that list is the function's name, and the second element is the function's body.
22+
23+
## 3. Decode the secret message part from function definition
24+
25+
- Inspect the output of [`quote`][doc-quote] to familiarize yourself with how ASTs look like for specific code snippets.
26+
- The AST node that contains the function's name also contains the function's argument list as the third element.
27+
- The arity of a function is the length of its argument list.
28+
- There is a [built-in function in the `String` module][string-slice] that can get the first `n` characters from a string.
29+
- A function without arguments written without parentheses will not have a list as argument but an atom.
30+
31+
## 4. Fix the decoding for functions with guards
32+
33+
- Inspect the output of [`quote`][doc-quote] to familiarize yourself with how ASTs look like for specific code snippets.
34+
- When a function has a guard, the third element in the tuple for the `:def/:defp` operation is a bit different.
35+
- That third element is a list with two elements, the first one is the tuple for the `:when` operation, and the second one is the function's body.
36+
- The `:when` operation's arguments are a two-element list, where the first argument is the function's name, and the second is the guard expression.
37+
38+
## 5. Decode the full secret message
39+
40+
- Use the function `to_ast/1` that you implemented in the first task to create the AST.
41+
- There is a [built-in function][macro-prewalk] that can visit each node in an AST with an accumulator.
42+
- Use the function `decode_secret_message_part/2` that you implemented in previous tasks to prewalk the AST.
43+
- To reverse the accumulator at the end and turn it into a string, refresh your knowledge of the [`Enum` module][enum].
44+
45+
[getting-started-quote]: https://elixir-lang.org/getting-started/meta/quote-and-unquote.html#quoting
46+
[doc-quote]: https://hexdocs.pm/elixir/Kernel.SpecialForms.html#quote/2
47+
[ast-intro-lucas]: https://dorgan.ar/posts/2021/04/the_elixir_ast/
48+
[doc-code-string-to-quoted]: https://hexdocs.pm/elixir/Code.html#string_to_quoted/2
49+
[string-slice]: https://hexdocs.pm/elixir/String.html#slice/2
50+
[macro-prewalk]: https://hexdocs.pm/elixir/Macro.html#prewalk/3
51+
[enum]: https://hexdocs.pm/elixir/Enum.html
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Instructions
2+
3+
You're part of a task force fighting against corporate espionage. You have a secret informer at Shady Company X, which you suspect of stealing secrets from its competitors.
4+
5+
Your informer, Agent Ex, is an Elixir developer. She is encoding secret messages in her code.
6+
7+
To decode her secret messages:
8+
9+
- Take all functions (public and private) in the order they're defined in.
10+
- For each function, take the first `n` characters from its name, where `n` is the function's arity.
11+
12+
## 1. Turn code into data
13+
14+
Implement the `TopSecret.to_ast/1` function. It should take a string with Elixir code and return its AST.
15+
16+
```elixir
17+
TopSecret.to_ast("div(4, 3)")
18+
# => {:div, [line: 1], [4, 3]}
19+
```
20+
21+
## 2. Parse a single AST node
22+
23+
Implement the `TopSecret.decode_secret_message_part/2` function. It should take an AST node and an accumulator for the secret message (a list). It should return a tuple with the AST node unchanged as the first element, and the accumulator as the second element.
24+
25+
If the operation of the AST node is defining a function (`def` or `defp`), prepend the function name (changed to a string) to the accumulator. If the operation is something else, return the accumulator unchanged.
26+
27+
```elixir
28+
ast_node = TopSecret.to_ast("defp cat(a, b, c), do: nil")
29+
TopSecret.decode_secret_message_part(ast_node, ["day"])
30+
# => {ast_node, ["cat", "day"]}
31+
32+
ast_node = TopSecret.to_ast("10 + 3")
33+
TopSecret.decode_secret_message_part(ast_node, ["day"])
34+
# => {ast_node, ["day"]}
35+
```
36+
37+
This function doesn't need to do any recursive calls to check the whole AST, only the given node. We will traverse the whole AST with built-in tools in the last step.
38+
39+
## 3. Decode the secret message part from function definition
40+
41+
Extend the `TopSecret.decode_secret_message_part/2` function. If the operation in the AST node is defining a function, don't return the whole function name. Instead, check the function's arity. Then, return only first `n` character from the name, where `n` is the arity.
42+
43+
```elixir
44+
ast_node = TopSecret.to_ast("defp cat(a, b), do: nil")
45+
TopSecret.decode_secret_message_part(ast_node, ["day"])
46+
# => {ast_node, ["ca", "day"]}
47+
48+
ast_node = TopSecret.to_ast("defp cat(), do: nil")
49+
TopSecret.decode_secret_message_part(ast_node, ["day"])
50+
# => {ast_node, ["", "day"]}
51+
```
52+
53+
## 4. Fix the decoding for functions with guards
54+
55+
Extend the `TopSecret.decode_secret_message_part/2` function. Make sure the function's name and arity is correctly detected for function definitions that use guards.
56+
57+
```elixir
58+
ast_node = TopSecret.to_ast("defp cat(a, b) when is_nil(a), do: nil")
59+
TopSecret.decode_secret_message_part(ast_node, ["day"])
60+
# => {ast_node, ["ca", "day"]}
61+
```
62+
63+
## 5. Decode the full secret message
64+
65+
Implement the `TopSecret.decode_secret_message/1` function. It should take a string with Elixir code and return the secret message as a string decoded from all function definitions found in the code. Make sure to reuse functions defined in previous steps.
66+
67+
```elixir
68+
code = """
69+
defmodule MyCalendar do
70+
def busy?(date, time) do
71+
Date.day_of_week(date) != 7 and
72+
time.hour in 10..16
73+
end
74+
75+
def yesterday?(date) do
76+
Date.diff(Date.utc_today, date)
77+
end
78+
end
79+
"""
80+
81+
TopSecret.decode_secret_message(code)
82+
# => "buy"
83+
```
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Introduction
2+
3+
## AST
4+
5+
The Abstract Syntax Tree (AST), also called a _quoted expression_, is a way to represent code as data.
6+
7+
Each node in the AST is a three-element tuple.
8+
9+
```elixir
10+
# AST representation of:
11+
# 2 + 3
12+
{:+, [], [2, 3]}
13+
```
14+
15+
The first element, an atom, is the operation. The second element, a keyword list, is the metadata. The third element is a list of arguments, which contains other nodes. Literal values such as integers, atoms, and strings are represented in the AST as themselves instead of three-element tuples.
16+
17+
### Turning code into ASTs
18+
19+
Changing Elixir code to ASTs and ASTs back to code is part of the standard library. You can find functions for working with ASTs in the modules `Code` (e.g. to change a string with code to an AST) and `Macro` (e.g. to traverse the AST or change it to a string).
20+
21+
Note that all of the functions in the standard library use the name "quoted" to mean the AST (short for _quoted expression_).
22+
23+
The special form for turning code into an AST is called `quote`. It accepts a code block and returns its AST.
24+
25+
```elixir
26+
quote do
27+
2 + 3 - 1
28+
end
29+
30+
# => {:-, [], [
31+
# {:+, [], [2, 3]},
32+
# 1
33+
# ]}
34+
```
35+
36+
### Use cases
37+
38+
The ability to represent code as an AST is at the heart of metaprogramming in Elixir. _Macros_, which is a way to write Elixir code that produces Elixir code, work by returning ASTs as output.
39+
40+
Another use case for ASTs is static code analysis, like Exercism's own tool, the Analyzer, which you might already know as the little bot that leaves comments on your solutions.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Used by "mix format"
2+
[
3+
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
4+
]
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# The directory Mix will write compiled artifacts to.
2+
/_build/
3+
4+
# If you run "mix test --cover", coverage assets end up here.
5+
/cover/
6+
7+
# The directory Mix downloads your dependencies sources to.
8+
/deps/
9+
10+
# Where third-party dependencies like ExDoc output generated docs.
11+
/doc/
12+
13+
# Ignore .fetch files in case you like to edit your project deps locally.
14+
/.fetch
15+
16+
# If the VM crashes, it generates a dump, let's ignore it too.
17+
erl_crash.dump
18+
19+
# Also ignore archive artifacts (built via "mix archive.build").
20+
*.ez
21+
22+
# Ignore package tarball (built via "mix hex.build").
23+
maps-*.tar
24+

0 commit comments

Comments
 (0)