blob: 319e06f97dfb7e7c6dbcbfd3b76a22dd483035bf [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
2 * Copyright 2016 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_INDEX
9#define SKSL_INDEX
10
11#include "SkSLExpression.h"
12#include "SkSLUtil.h"
13
14namespace SkSL {
15
16/**
17 * Given a type, returns the type that will result from extracting an array value from it.
18 */
ethannicholasd598f792016-07-25 10:08:54 -070019static const Type& index_type(const Context& context, const Type& type) {
ethannicholasb3058bd2016-07-01 08:22:01 -070020 if (type.kind() == Type::kMatrix_Kind) {
ethannicholasd598f792016-07-25 10:08:54 -070021 if (type.componentType() == *context.fFloat_Type) {
ethannicholasb12b3c62016-09-26 11:58:52 -070022 switch (type.rows()) {
ethannicholasd598f792016-07-25 10:08:54 -070023 case 2: return *context.fVec2_Type;
24 case 3: return *context.fVec3_Type;
25 case 4: return *context.fVec4_Type;
ethannicholasb3058bd2016-07-01 08:22:01 -070026 default: ASSERT(false);
27 }
28 } else {
ethannicholasd598f792016-07-25 10:08:54 -070029 ASSERT(type.componentType() == *context.fDouble_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -070030 switch (type.columns()) {
ethannicholasd598f792016-07-25 10:08:54 -070031 case 2: return *context.fDVec2_Type;
32 case 3: return *context.fDVec3_Type;
33 case 4: return *context.fDVec4_Type;
ethannicholasb3058bd2016-07-01 08:22:01 -070034 default: ASSERT(false);
35 }
36 }
37 }
38 return type.componentType();
39}
40
41/**
42 * An expression which extracts a value from an array or matrix, as in 'm[2]'.
43 */
44struct IndexExpression : public Expression {
ethannicholasd598f792016-07-25 10:08:54 -070045 IndexExpression(const Context& context, std::unique_ptr<Expression> base,
46 std::unique_ptr<Expression> index)
47 : INHERITED(base->fPosition, kIndex_Kind, index_type(context, base->fType))
ethannicholasb3058bd2016-07-01 08:22:01 -070048 , fBase(std::move(base))
49 , fIndex(std::move(index)) {
ethannicholasb12b3c62016-09-26 11:58:52 -070050 ASSERT(fIndex->fType == *context.fInt_Type || fIndex->fType == *context.fUInt_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -070051 }
52
53 std::string description() const override {
54 return fBase->description() + "[" + fIndex->description() + "]";
55 }
56
57 const std::unique_ptr<Expression> fBase;
58 const std::unique_ptr<Expression> fIndex;
59
60 typedef Expression INHERITED;
61};
62
63} // namespace
64
65#endif