slang-netlist  0.9.0
Loading...
Searching...
No Matches
Utilities.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "slang/ast/Compilation.h"
4#include "slang/text/FormatBuffer.h"
5#include "slang/text/SourceLocation.h"
6#include "slang/text/SourceManager.h"
7
8#include <algorithm>
9#include <cstddef>
10#include <string>
11#include <string_view>
12#include <vector>
13
14#include <fmt/format.h>
15
16namespace slang::netlist {
17
18struct Utilities {
19
21 static auto locationStr(ast::Compilation const &compilation,
22 SourceLocation location) {
23 if (location.buffer() != SourceLocation::NoLocation.buffer()) {
24 auto filename = compilation.getSourceManager()->getFileName(location);
25 auto line = compilation.getSourceManager()->getLineNumber(location);
26 auto column = compilation.getSourceManager()->getColumnNumber(location);
27 return fmt::format("{}:{}:{}", filename, line, column);
28 }
29 return std::string("?");
30 }
31
32 using Row = std::vector<std::string>;
33 using Table = std::vector<Row>;
34
36
37 // Spaces between columns
38 size_t padding;
39
41 };
42
44 static auto formatTable(FormatBuffer &buffer, const Row &header,
45 const Table &rows, TableFormatConfig cfg = {}) {
46
47 const std::size_t cols = header.size();
48
49 // Compute column widths: max of header and all rows for each column.
50 std::vector<std::size_t> widths(cols);
51
52 for (std::size_t col = 0; col < cols; ++col) {
53 std::size_t max_width = header[col].size();
54 for (const auto &row : rows) {
55 if (col < row.size()) {
56 max_width = std::max(max_width, row[col].size());
57 }
58 }
59 widths[col] = max_width;
60 }
61
62 auto appendRow = [&](const Row &row) {
63 for (std::size_t col = 0; col < cols; ++col) {
64 std::string_view value;
65 if (col < row.size()) {
66 value = row[col];
67 } else {
68 value = "";
69 }
70
71 // Left-align in a field of `widths[col]`.
72 buffer.format("{:<{}}", value, widths[col]);
73
74 // Padding between columns (except after the last).
75 if (col + 1 < cols && cfg.padding > 0) {
76 buffer.format("{: >{}}", "", cfg.padding);
77 }
78 }
79 buffer.format("\n");
80 };
81
82 appendRow(header);
83 for (const auto &row : rows) {
84 appendRow(row);
85 }
86 }
87};
88
89} // namespace slang::netlist
Definition Utilities.hpp:16
TableFormatConfig()
Definition Utilities.hpp:40
size_t padding
Definition Utilities.hpp:38
Definition Utilities.hpp:18
std::vector< Row > Table
Definition Utilities.hpp:33
static auto locationStr(ast::Compilation const &compilation, SourceLocation location)
Return a string representation of a slang SourceLocation.
Definition Utilities.hpp:21
static auto formatTable(FormatBuffer &buffer, const Row &header, const Table &rows, TableFormatConfig cfg={})
Format a table of data into the given format buffer.
Definition Utilities.hpp:44
std::vector< std::string > Row
Definition Utilities.hpp:32