ast.hpp (1198B)
1 // AST (Abstract Syntax Tree) types and functions 2 3 // Copyright (C) 2022, Mohammad-Reza Nabipoor 4 // SPDX-License-Identifier: GPL-3.0-or-later 5 6 #pragma once 7 8 #include <ostream> 9 #include <string> 10 #include <utility> 11 #include <variant> 12 13 #include <stlab/forest.hpp> 14 15 namespace ast { 16 17 struct Num 18 { 19 double num{}; 20 }; 21 22 struct Op 23 { 24 char op; 25 }; 26 27 struct Id 28 { 29 std::string id; 30 }; 31 32 struct Str 33 { 34 std::string str; 35 }; 36 37 struct Ass 38 { 39 Id id; 40 }; 41 42 struct Call 43 { 44 Id id; 45 }; 46 47 using Node = std::variant<Num, Op, Id, Str, Ass, Call>; 48 49 std::ostream& 50 operator<<(std::ostream& os, const Num& n); 51 52 std::ostream& 53 operator<<(std::ostream& os, const Op& o); 54 55 std::ostream& 56 operator<<(std::ostream& os, const Id& i); 57 58 std::ostream& 59 operator<<(std::ostream& os, const Str& s); 60 61 std::ostream& 62 operator<<(std::ostream& os, const Ass& a); 63 64 std::ostream& 65 operator<<(std::ostream& os, const Call& c); 66 67 std::ostream& 68 operator<<(std::ostream& os, const Node& n); 69 70 using Nodes = stlab::forest<Node>; 71 using NodesIter = Nodes::iterator; 72 73 Nodes 74 mknum(double n); 75 76 Nodes 77 mkop(Op op, Nodes lhs, Nodes rhs); 78 79 Nodes 80 mkid(Id id); 81 82 Nodes 83 mkstr(Str str); 84 85 Nodes 86 mkass(Id id, Nodes expr); 87 88 Nodes 89 mkcall(Id id, Nodes args); 90 91 } // namespace ast