Debian Codegraph @

src/utils/SkShaderUtils.cpp

raw
1 /*
2 * Copyright 2019 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/utils/SkShaderUtils.h"
9
10 #include "include/core/SkString.h"
11 #include "include/private/base/SkTArray.h"
12 #include "src/core/SkStringUtils.h"
13 #include "src/sksl/SkSLProgramSettings.h"
14 #include "src/sksl/SkSLString.h"
15
16 #include <cstddef>
17 #include <iomanip>
18 #include <sstream>
19
20 using namespace skia_private;
21
22 namespace SkShaderUtils {
23
24 class GLSLPrettyPrint {
25 public:
26 GLSLPrettyPrint() {}
27
28 std::string prettify(const std::string& string) {
29 fTabs = 0;
30 fFreshline = true;
31
32 // If a string breaks while in the middle 'parse until' we need to continue parsing on the
33 // next string
34 fInParseUntilNewline = false;
35 fInParseUntil = false;
36
37 int parensDepth = 0;
38
39 // setup pretty state
40 fIndex = 0;
41 fLength = string.length();
42 fInput = string.c_str();
43
44 while (fLength > fIndex) {
45 /* The heart and soul of our prettification algorithm. The rules should hopefully
46 * be self explanatory. For '#' and '//' tokens, we parse until we reach a newline.
47 *
48 * For long style comments like this one, we search for the ending token. We also
49 * preserve whitespace in these comments WITH THE CAVEAT that we do the newlines
50 * ourselves. This allows us to remain in control of line numbers, and matching
51 * tabs. Existing tabs in the input string are copied over too, but this will look
52 * funny.
53 *
54 * '{' and '}' are handled in basically the same way. We add a newline if we aren't
55 * on a fresh line, dirty the line, then add a second newline, i.e. braces are always
56 * on their own lines indented properly.
57 *
58 * '(' and ')' are basically ignored, except as a sign that we need to ignore ';', since
59 * we want to keep for loops on a single line.
60 *
61 * ';' means add a new line. If the previous character was a '}', we make sure that the
62 * semicolon comes directly after the brace, not on a newline.
63 *
64 * ',' doesn't add a new line, but does have special handling to ensure it is on the
65 * same line as a '}', much like the semicolon.
66 *
67 * '\t' and '\n' are ignored in general parsing for backwards compatibility with
68 * existing shader code. We also have a special case for handling whitespace at the
69 * beginning of fresh lines.
70 *
71 * Otherwise, just add the new character to the pretty string, indenting if
72 * necessary.
73 */
74 if (fInParseUntilNewline) {
75 this->parseUntilNewline();
76 continue;
77 }
78 if (fInParseUntil) {
79 this->parseUntil(fInParseUntilToken);
80 continue;
81 }
82 if (this->hasToken("#") || this->hasToken("//")) {
83 this->parseUntilNewline();
84 continue;
85 }
86 if (this->hasToken("/*")) {
87 this->parseUntil("*/");
88 continue;
89 }
90 if (fInput[fIndex] == '{') {
91 this->newline();
92 this->appendChar('{');
93 fTabs++;
94 this->newline();
95 continue;
96 }
97 if (fInput[fIndex] == '}') {
98 fTabs--;
99 this->newline();
100 this->appendChar('}');
101 this->newline();
102 continue;
103 }
104 if (fFreshline && fInput[fIndex] == ';') {
105 this->undoNewlineAfter('}');
106 this->appendChar(fInput[fIndex]);
107 this->newline();
108 continue;
109 }
110 if (fFreshline && fInput[fIndex] == ',') {
111 this->undoNewlineAfter('}');
112 this->appendChar(fInput[fIndex]);
113 continue;
114 }
115 if (this->hasToken(")")) {
116 parensDepth--;
117 continue;
118 }
119 if (this->hasToken("(")) {
120 parensDepth++;
121 continue;
122 }
123 if (this->hasToken(")")) {
124 parensDepth--;
125 continue;
126 }
127 if (!parensDepth && this->hasToken(";")) {
128 this->newline();
129 continue;
130 }
131 if (fInput[fIndex] == '\t' || fInput[fIndex] == '\n' ||
132 (fFreshline && fInput[fIndex] == ' ')) {
133 fIndex++;
134 continue;
135 }
136
137 this->appendChar(fInput[fIndex]);
138 }
139
140 return fPretty;
141 }
142
143 private:
144 void appendChar(char c) {
145 this->tabString();
146 fPretty += fInput[fIndex++];
147 fFreshline = false;
148 }
149
150 // hasToken automatically consumes the next token, if it is a match, and then tabs
151 // if necessary, before inserting the token into the pretty string
152 bool hasToken(const char* token) {
153 size_t i = fIndex;
154 for (size_t j = 0; token[j] && fLength > i; i++, j++) {
155 if (token[j] != fInput[i]) {
156 return false;
157 }
158 }
159 this->tabString();
160 fIndex = i;
161 fPretty.append(token);
162 fFreshline = false;
163 return true;
164 }
165
166 void parseUntilNewline() {
167 while (fLength > fIndex) {
168 if (fInput[fIndex] == '\n') {
169 fIndex++;
170 this->newline();
171 fInParseUntilNewline = false;
172 break;
173 }
174 fPretty += fInput[fIndex++];
175 fInParseUntilNewline = true;
176 }
177 }
178
179 // this code assumes it is not actually searching for a newline. If you need to search for a
180 // newline, then use the function above. If you do search for a newline with this function
181 // it will consume the entire string and the output will certainly not be prettified
182 void parseUntil(const char* token) {
183 while (fLength > fIndex) {
184 // For embedded newlines, this code will make sure to embed the newline in the
185 // pretty string, increase the linecount, and tab out the next line to the appropriate
186 // place
187 if (fInput[fIndex] == '\n') {
188 this->newline();
189 this->tabString();
190 fIndex++;
191 }
192 if (this->hasToken(token)) {
193 fInParseUntil = false;
194 break;
195 }
196 fFreshline = false;
197 fPretty += fInput[fIndex++];
198 fInParseUntil = true;
199 fInParseUntilToken = token;
200 }
201 }
202
203 // We only tab if on a newline, otherwise consider the line tabbed
204 void tabString() {
205 if (fFreshline) {
206 for (int t = 0; t < fTabs; t++) {
207 fPretty += '\t';
208 }
209 }
210 }
211
212 // newline is really a request to add a newline, if we are on a fresh line there is no reason
213 // to add another newline
214 void newline() {
215 if (!fFreshline) {
216 fFreshline = true;
217 fPretty += '\n';
218 }
219 }
220
221 // undoNewlineAfter() attempts to undo the effects of newline(), if the last character before
222 // the newline matches `c`.
223 void undoNewlineAfter(char c) {
224 if (fFreshline) {
225 if (fPretty.size() >= 2 && fPretty.rbegin()[0] == '\n' && fPretty.rbegin()[1] == c) {
226 fFreshline = false;
227 fPretty.pop_back();
228 }
229 }
230 }
231
232 bool fFreshline;
233 int fTabs;
234 size_t fIndex, fLength;
235 const char* fInput;
236 std::string fPretty;
237
238 // Some helpers for parseUntil when we go over a string length
239 bool fInParseUntilNewline;
240 bool fInParseUntil;
241 const char* fInParseUntilToken;
242 };
243
244 std::string PrettyPrint(const std::string& string) {
245 GLSLPrettyPrint pp;
246 return pp.prettify(string);
247 }
248
249 void VisitLineByLine(const std::string& text,
250 const std::function<void(int lineNumber, const char* lineText)>& visitFn) {
251 TArray<SkString> lines;
252 SkStrSplit(text.c_str(), "\n", kStrict_SkStrSplitMode, &lines);
253 for (int i = 0; i < lines.size(); ++i) {
254 visitFn(i + 1, lines[i].c_str());
255 }
256 }
257
258 std::string SpirvAsHexStream(SkSpan<const uint32_t> spirv) {
259 std::ostringstream result;
260 result << "Paste the following SPIR-V binary in https://www.khronos.org/spir/visualizer/\n";
261 result << " or pass to `spirv-dis` (optionally with `--comment --nested-indent`)\n";
262
263 constexpr size_t kIndicesPerRow = 10;
264 size_t rowOffset = 0;
265 for (size_t index = 0; index < spirv.size(); ++index, ++rowOffset) {
266 if (rowOffset == kIndicesPerRow) {
267 result << "\n";
268 rowOffset = 0;
269 }
270 result << "0x" << std::uppercase << std::setfill('0') << std::setw(8) << std::hex
271 << spirv[index] << ",";
272 }
273
274 return result.str();
275 }
276
277 std::string BuildShaderErrorMessage(const char* shader, const char* errors) {
278 std::string abortText{"Shader compilation error\n"
279 "------------------------\n"};
280 VisitLineByLine(shader, [&](int lineNumber, const char* lineText) {
281 SkSL::String::appendf(&abortText, "%4i\t%s\n", lineNumber, lineText);
282 });
283 SkSL::String::appendf(&abortText, "Errors:\n%s", errors);
284 return abortText;
285 }
286
287 void PrintShaderBanner(SkSL::ProgramKind programKind) {
288 const char* typeName = "Unknown";
289 if (SkSL::ProgramConfig::IsVertex(programKind)) {
290 typeName = "Vertex";
291 } else if (SkSL::ProgramConfig::IsFragment(programKind)) {
292 typeName = "Fragment";
293 }
294 SkDebugf("---- %s shader ----------------------------------------------------\n", typeName);
295 }
296
297 } // namespace SkShaderUtils