ConstantExpression.h revision 19ca75ae47df5cd9447b232c31c5df1d110e85d9
1/* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#ifndef CONSTANT_EXPRESSION_H_ 18 19#define CONSTANT_EXPRESSION_H_ 20 21#include <android-base/macros.h> 22#include <string> 23#include "ScalarType.h" 24 25namespace android { 26 27/** 28 * A constant expression is represented by a tree. 29 */ 30struct ConstantExpression { 31 32 enum ConstExprType { 33 kConstExprLiteral, 34 kConstExprUnknown, 35 kConstExprUnary, 36 kConstExprBinary, 37 kConstExprTernary 38 }; 39 40 /* Literals, identifiers */ 41 ConstantExpression(const char *value, ConstExprType type); 42 /* binary operations */ 43 ConstantExpression(const ConstantExpression *value1, 44 const char *op, const ConstantExpression* value2); 45 /* unary operations */ 46 ConstantExpression(const char *op, const ConstantExpression *value); 47 /* ternary ?: */ 48 ConstantExpression(const ConstantExpression *cond, 49 const ConstantExpression *trueVal, 50 const ConstantExpression *falseVal); 51 52 /* Original expression. */ 53 const char *expr() const; 54 /* Evaluated result in a string form. */ 55 const char *value() const; 56 /* Evaluated result in a string form, with given contextual kind. */ 57 const char *cppValue(ScalarType::Kind castKind) const; 58 /* Evaluated result in a string form, with given contextual kind. */ 59 const char *javaValue(ScalarType::Kind castKind) const; 60 /* Original expression with type. */ 61 const char *description() const; 62 63private: 64 /* The formatted expression. */ 65 std::string mFormatted; 66 /* The type of the expression. Hints on its original form. */ 67 ConstExprType mType; 68 /* The kind of the result value. 69 * Is valid only when mType != kConstExprUnknown. */ 70 ScalarType::Kind mValueKind; 71 /* The stored result value. 72 * Is valid only when mType != kConstExprUnknown. */ 73 uint64_t mValue; 74 /* Return the value casted to the given type. 75 * First cast it according to mValueKind, then cast it to T. 76 * Assumes mType != kConstExprUnknown */ 77 template <typename T> T cast() const; 78 /* Helper function for value(ScalarType::Kind) */ 79 const char *value0(ScalarType::Kind castKind) const; 80 81 DISALLOW_COPY_AND_ASSIGN(ConstantExpression); 82}; 83 84} // namespace android 85 86#endif // CONSTANT_EXPRESSION_H_ 87