ConstantExpression.h revision 5788697381666844eeb23e04e5c6f83ec6ec8b44
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    /* Original expression with type. */
59    const char *description() const;
60
61private:
62    /* The formatted expression. */
63    std::string mFormatted;
64    /* The type of the expression. Hints on its original form. */
65    ConstExprType mType;
66    /* The kind of the result value.
67     * Is valid only when mType != kConstExprUnknown. */
68    ScalarType::Kind mValueKind;
69    /* The stored result value.
70     * Is valid only when mType != kConstExprUnknown. */
71    uint64_t mValue;
72    /* Return a signed int64_t value.
73     * First cast it according to mValueKind, then cast it to int64_t. */
74    int64_t int64Value() const;
75    /* Helper function for value(ScalarType::Kind) */
76    const char *value0(ScalarType::Kind castKind) const;
77
78    DISALLOW_COPY_AND_ASSIGN(ConstantExpression);
79};
80
81}  // namespace android
82
83#endif  // CONSTANT_EXPRESSION_H_
84