Quetzal-CoaTL
The Coalescence Template Library
Loading...
Searching...
No Matches
ast.hpp
1// Copyright 2022 Arnaud Becheler <abechele@umich.edu>
2
3/*********************************************************************** * This program is free software; you can
4 *redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free
5 *Software Foundation; either version 2 of the License, or * (at your option) any later version. *
6 * *
7 ***************************************************************************/
8
9#pragma once
10
11#include <boost/spirit/home/x3.hpp>
12#include <boost/spirit/home/x3/support/ast/variant.hpp>
13
14#include <boost/fusion/adapted/struct/adapt_struct.hpp>
15#include <boost/fusion/include/adapt_struct.hpp>
16
17#include <iomanip>
18
19namespace quetzal::format::newick::ast
20{
21
25using nodes = std::vector<struct node>;
26
29struct node
30{
34 using vertex_property = std::string;
35
39 using edge_property = double;
40
44 nodes children;
45
50
55};
56
60static inline std::ostream &print_subtree(node const &node, const std::string &prefix, std::ostream &os)
61{
62 // if tree is more than a simple root node
63 if (!node.children.empty())
64 {
65 // print a prefix growing with depth
66 os << prefix;
67
68 size_t nb_children = node.children.size();
69
70 // Bifurcation if more than 1 child
71 if (nb_children > 1)
72 os << "├──";
73
74 for (size_t i = 0; i < nb_children; ++i)
75 {
76 const auto &child = node.children[i];
77 // If not the last child
78 if (i < nb_children - 1)
79 {
80 // If not the first child
81 if (i > 0)
82 os << prefix << "├──";
83
84 bool should_print_branch = nb_children > 1 && !child.children.empty();
85 auto new_prefix = prefix + (should_print_branch ? "│\t" : "\t");
86 os << child.distance_to_parent << "──" << std::quoted(child.name) << "\n";
87 print_subtree(child, new_prefix, os);
88 }
89 // If the last child
90 else
91 {
92 if (nb_children > 1)
93 os << prefix;
94 os << "└──" << child.distance_to_parent << "──" << std::quoted(child.name) << "\n";
95 print_subtree(child, prefix + "\t", os);
96 }
97 }
98 }
99 return os;
100}
101
105static inline std::ostream &operator<<(std::ostream &os, node const &n)
106{
107 os << std::quoted(n.name) << "\n";
108 return print_subtree(n, "", os);
109}
110
111} // namespace quetzal::format::newick::ast
112
113BOOST_FUSION_ADAPT_STRUCT(quetzal::format::newick::ast::node, children, name, distance_to_parent)
Abstract Syntax Tree structure.
Definition ast.hpp:30
double edge_property
The type of edge described by the AST.
Definition ast.hpp:39
nodes children
A container of nodes.
Definition ast.hpp:44
vertex_property name
the name of the node
Definition ast.hpp:49
std::string vertex_property
The type of vertex described by the AST.
Definition ast.hpp:34
edge_property distance_to_parent
the length of the branch
Definition ast.hpp:54