P4C
The P4 Compiler
Loading...
Searching...
No Matches
sourceCodeBuilder.h
1/*
2 * SPDX-FileCopyrightText: 2013 Barefoot Networks, Inc.
3 * Copyright 2013-present Barefoot Networks, Inc.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8#ifndef LIB_SOURCECODEBUILDER_H_
9#define LIB_SOURCECODEBUILDER_H_
10
11#include <ctype.h>
12
13#include "absl/strings/cord.h"
14#include "absl/strings/str_format.h"
15#include "lib/cstring.h"
16#include "lib/exceptions.h"
17#include "lib/stringify.h"
18
19namespace P4::Util {
20class SourceCodeBuilder {
21 int indentLevel; // current indent level
22 unsigned indentAmount;
23
24 absl::Cord buffer;
25 bool endsInSpace;
26 bool supressSemi = false;
27
28 public:
29 SourceCodeBuilder() : indentLevel(0), indentAmount(4), endsInSpace(false) {}
30
31 void increaseIndent() { indentLevel += indentAmount; }
32 void decreaseIndent() {
33 indentLevel -= indentAmount;
34 if (indentLevel < 0) BUG("Negative indent");
35 }
36 void newline() {
37 buffer.Append("\n");
38 endsInSpace = true;
39 }
40 void spc() {
41 if (!endsInSpace) buffer.Append(" ");
42 endsInSpace = true;
43 }
44
45 void append(cstring str) { append(str.c_str()); }
46 void appendLine(const char *str) {
47 append(str);
48 newline();
49 }
50 void appendLine(cstring str) {
51 append(str);
52 newline();
53 }
54 void append(const std::string &str) {
55 if (str.empty()) return;
56 endsInSpace = ::isspace(str.back());
57 buffer.Append(str);
58 }
59 [[deprecated("use string / char* version instead")]]
60 void append(char c) {
61 std::string str(1, c);
62 append(str);
63 }
64 void append(const char *str) {
65 if (str == nullptr) BUG("Null argument to append");
66 if (strlen(str) == 0) return;
67 endsInSpace = ::isspace(str[strlen(str) - 1]);
68 buffer.Append(str);
69 }
70
71 template <typename... Args>
72 void appendFormat(const absl::FormatSpec<Args...> &format, Args &&...args) {
73 // FIXME: Sink directly to cord
74 append(absl::StrFormat(format, std::forward<Args>(args)...));
75 }
76 void append(unsigned u) { appendFormat("%d", u); }
77 void append(int u) { appendFormat("%d", u); }
78
79 void endOfStatement(bool addNl = false) {
80 if (!supressSemi) append(";");
81 supressSemi = false;
82 if (addNl) newline();
83 }
84 void supressStatementSemi() { supressSemi = true; }
85
86 void blockStart() {
87 append("{");
88 newline();
89 increaseIndent();
90 }
91
92 void emitIndent() {
93 buffer.Append(std::string(indentLevel, ' '));
94 if (indentLevel > 0) endsInSpace = true;
95 }
96
97 void blockEnd(bool nl) {
98 decreaseIndent();
99 emitIndent();
100 append("}");
101 if (nl) newline();
102 }
103
104 std::string toString() const { return std::string(buffer); }
105 void commentStart() { append("/* "); }
106 void commentEnd() { append(" */"); }
107 bool lastIsSpace() const { return endsInSpace; }
108};
109} // namespace P4::Util
110
111#endif /* LIB_SOURCECODEBUILDER_H_ */
Definition cstring.h:76