commit 8c7d89b7392e899d22b16cb4de7a00394c66fe62
parent d99f4e654cadc0842009f5bef92ded798d3871d8
Author: Mohammad-Reza Nabipoor <m.nabipoor@yahoo.com>
Date: Sun, 20 Sep 2020 22:36:54 +0430
README.md: Update Chap. 3
Diffstat:
| M | README.md | | | 52 | +++++++++++++++++++++++++++++++++++++++++++++++++++- |
1 file changed, 51 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
@@ -179,11 +179,14 @@ Token{
}
```
+
## Chapter 2: Kaleidoscope: Implementing a Parser and AST
- **Implementation** `kaleidoscope_ast.hpp`, `kaleidoscope_ast.cpp`
- **Test** `tests/kaleidoscope_ast.test.cpp`
+### `ASTNode` class
+
Each node of AST (Abstract Syntax Tree) can be saved in `ASTNode` class. It's a
polymorphic type that accepts an instance of type `T` that satisfies the
following requirements:
@@ -214,6 +217,27 @@ the benefits of this design, you can watch
If you're impatient you can go directly to time
[49:13](https://youtu.be/QGcVXgEVMJg?t=49m13s).
+### `kal::cast` function template
+
+```c++
+template<typename T>
+bool
+cast(const ASTNode& n, T& val);
+```
+
+This function will copy the value type inside the polymorphic type `n` to `val`.
+On successful copy, this will return `true`.
+
+#### Parameters
+
+- `n` Polymorphic type `ASTNode` that (possibly) contains the value of type `T`
+- `val` Destination value of type `T` (this is an output)
+
+#### Return value
+
+Returns `true` on success (when `dynamic_cast` can casts to `T`).
+
+### Concrete types for AST nodes
Current implementation provides the following [regular][regular] types for AST
nodes:
@@ -237,8 +261,34 @@ nodes:
All of these types are implemented as `struct` (all members are `public`).
Because there's no invariant to establish.
-(See C++ Core Guidelines C.2).
+[See C++ Core Guidelines C.2][cppcore_c2].
+
+### Example of usage
+```
+#include "kaleidoscope_ast.hpp"
+
+using namespace kal;
+
+int
+main()
+{
+ Number n{ 3.14 };
+ Variable v{ "var1" };
+ BinaryOp b{ '+', n, v }; // 3.14 + var1
+
+ Variable x{ "x" };
+ Variable y{ "y" };
+ Call c{ "tan2", { x, y } }; // tan2(x, y)
+
+ Prototype p{ "add3", { "x", "y", "z" } }; // extern add3(x, y, z)
+
+ Variable z{ "z" };
+ Function f{ p, BinaryOp{ '+', BinaryOp{ '+', x, y }, z } };
+
+ return 0;
+}
+```
[regular]: https://en.cppreference.com/w/cpp/concepts/regular
[cppcore_c2]: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c2-use-class-if-the-class-has-an-invariant-use-struct-if-the-data-members-can-vary-independently