blob: 9c25668fdf3430b1b1001a8ae0fae1b8fead26f6 [file] [log] [blame]
Ethan Nicholas6f4eee22021-01-11 12:37:42 -05001/*
2 * Copyright 2021 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/sksl/SkSLMetalCodeGenerator.h"
9
10namespace SkSL {
11
12String Mangler::uniqueName(String baseName, SymbolTable* symbolTable) {
13 SkASSERT(symbolTable);
14 // The inliner runs more than once, so the base name might already have been mangled and have a
15 // prefix like "_123_x". Let's strip that prefix off to make the generated code easier to read.
16 if (baseName.startsWith("_")) {
17 // Determine if we have a string of digits.
18 int offset = 1;
19 while (isdigit(baseName[offset])) {
20 ++offset;
21 }
22 // If we found digits, another underscore, and anything else, that's the mangler prefix.
23 // Strip it off.
24 if (offset > 1 && baseName[offset] == '_' && baseName[offset + 1] != '\0') {
25 baseName.erase(0, offset + 1);
26 } else {
27 // This name doesn't contain a mangler prefix, but it does start with an underscore.
28 // OpenGL disallows two consecutive underscores anywhere in the string, and we'll be
29 // adding one as part of the mangler prefix, so strip the leading underscore.
30 baseName.erase(0, 1);
31 }
32 }
33
34 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
35 // we're not reusing an existing name. (Note that within a single compilation pass, this check
36 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
37 String uniqueName;
38 for (;;) {
39 uniqueName = String::printf("_%d_%s", fCounter++, baseName.c_str());
40 StringFragment frag{uniqueName.data(), uniqueName.length()};
41 if ((*symbolTable)[frag] == nullptr) {
42 break;
43 }
44 }
45
46 return uniqueName;
47}
48
49} // namespace SkSL