| 1 | /* |
| 2 | * Copyright 2017 Google Inc. |
| 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 | #ifndef SKSL_ENUM |
| 9 | #define SKSL_ENUM |
| 10 | |
| 11 | #include "src/sksl/ir/SkSLExpression.h" |
| 12 | #include "src/sksl/ir/SkSLProgramElement.h" |
| 13 | #include "src/sksl/ir/SkSLSymbolTable.h" |
| 14 | #include "src/sksl/ir/SkSLVariable.h" |
| 15 | |
| 16 | #include <algorithm> |
| 17 | #include <vector> |
| 18 | |
| 19 | namespace SkSL { |
| 20 | |
| 21 | struct Symbol; |
| 22 | |
| 23 | struct Enum : public ProgramElement { |
| 24 | Enum(int offset, StringFragment typeName, std::shared_ptr<SymbolTable> symbols) |
| 25 | : INHERITED(offset, kEnum_Kind) |
| 26 | , fTypeName(typeName) |
| 27 | , fSymbols(std::move(symbols)) {} |
| 28 | |
| 29 | std::unique_ptr<ProgramElement> clone() const override { |
| 30 | return std::unique_ptr<ProgramElement>(new Enum(fOffset, fTypeName, fSymbols)); |
| 31 | } |
| 32 | |
| 33 | String code() const { |
| 34 | String result = "enum class " + fTypeName + " {\n" ; |
| 35 | String separator; |
| 36 | std::vector<const Symbol*> sortedSymbols; |
| 37 | for (const auto& pair : *fSymbols) { |
| 38 | sortedSymbols.push_back(pair.second); |
| 39 | } |
| 40 | std::sort(sortedSymbols.begin(), sortedSymbols.end(), |
| 41 | [](const Symbol* a, const Symbol* b) { return a->fName < b->fName; }); |
| 42 | for (const auto& s : sortedSymbols) { |
| 43 | const Expression& initialValue = *((Variable*) s)->fInitialValue; |
| 44 | SkASSERT(initialValue.fKind == Expression::kIntLiteral_Kind); |
| 45 | result += separator + " " + s->fName + " = " + |
| 46 | to_string(((IntLiteral&) initialValue).fValue); |
| 47 | separator = ",\n" ; |
| 48 | } |
| 49 | result += "\n};" ; |
| 50 | return result; |
| 51 | } |
| 52 | |
| 53 | #ifdef SK_DEBUG |
| 54 | String description() const override { |
| 55 | return this->code(); |
| 56 | } |
| 57 | #endif |
| 58 | |
| 59 | bool fBuiltin = false; |
| 60 | const StringFragment fTypeName; |
| 61 | const std::shared_ptr<SymbolTable> fSymbols; |
| 62 | |
| 63 | typedef ProgramElement INHERITED; |
| 64 | }; |
| 65 | |
| 66 | } // namespace |
| 67 | |
| 68 | #endif |
| 69 | |