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