blob: a025dd2350a8ebda643e3214b104862aaa6a4443 [file] [log] [blame]
Andreas Huber1aec3972016-08-26 09:26:32 -07001/*
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
Yifan Hong52165692016-08-12 18:06:40 -070017#include "ConstantExpression.h"
18
Yifan Hong57886972016-08-17 10:42:15 -070019#include <android-base/logging.h>
Timur Iskhakovb58f4182017-08-29 15:19:24 -070020#include <android-base/parseint.h>
21#include <stdio.h>
22#include <algorithm>
Timur Iskhakove8ee6a02017-09-06 11:42:10 -070023#include <iostream>
Yifan Hong57886972016-08-17 10:42:15 -070024#include <sstream>
Timur Iskhakovb58f4182017-08-29 15:19:24 -070025#include <string>
Yifan Hong57886972016-08-17 10:42:15 -070026
Yifan Hongf24fa852016-09-23 11:03:15 -070027#include "EnumType.h"
Timur Iskhakov7296af12017-08-09 21:52:48 +000028#include "Scope.h" // LocalIdentifier
Yifan Hongf24fa852016-09-23 11:03:15 -070029
Yifan Hong57886972016-08-17 10:42:15 -070030// The macros are really nasty here. Consider removing
31// as many macros as possible.
32
Timur Iskhakovd27580c2017-08-09 20:14:52 -070033#define OPEQ(__y__) (std::string(mOp) == std::string(__y__))
34#define COMPUTE_UNARY(__op__) if (op == std::string(#__op__)) return __op__ val;
35#define COMPUTE_BINARY(__op__) if (op == std::string(#__op__)) return lval __op__ rval;
Yifan Hong57886972016-08-17 10:42:15 -070036#define OP_IS_BIN_ARITHMETIC (OPEQ("+") || OPEQ("-") || OPEQ("*") || OPEQ("/") || OPEQ("%"))
37#define OP_IS_BIN_BITFLIP (OPEQ("|") || OPEQ("^") || OPEQ("&"))
38#define OP_IS_BIN_COMP (OPEQ("<") || OPEQ(">") || OPEQ("<=") || OPEQ(">=") || OPEQ("==") || OPEQ("!="))
39#define OP_IS_BIN_SHIFT (OPEQ(">>") || OPEQ("<<"))
40#define OP_IS_BIN_LOGICAL (OPEQ("||") || OPEQ("&&"))
41#define SK(__x__) ScalarType::Kind::KIND_##__x__
Yifan Hongf24fa852016-09-23 11:03:15 -070042#define SHOULD_NOT_REACH() CHECK(false) << __LINE__ << ": should not reach here: "
Yifan Hong57886972016-08-17 10:42:15 -070043
Chih-Hung Hsieh306cc4b2017-08-02 14:59:25 -070044// NOLINT to suppress missing parentheses warnings about __def__.
Yifan Hong57886972016-08-17 10:42:15 -070045#define SWITCH_KIND(__cond__, __action__, __def__) \
Yifan Hong2bd3c1f2016-09-22 13:20:05 -070046 switch(__cond__) { \
47 case SK(BOOL): __action__(bool) \
48 case SK(UINT8): __action__(uint8_t) \
49 case SK(INT8): __action__(int8_t) \
50 case SK(UINT16): __action__(uint16_t) \
51 case SK(INT16): __action__(int16_t) \
52 case SK(UINT32): __action__(uint32_t) \
53 case SK(INT32): __action__(int32_t) \
54 case SK(UINT64): __action__(uint64_t) \
55 case SK(INT64): __action__(int64_t) \
Chih-Hung Hsieh306cc4b2017-08-02 14:59:25 -070056 default: __def__ /* NOLINT */ \
57 }
Yifan Hong52165692016-08-12 18:06:40 -070058
59namespace android {
60
Yifan Hongf24fa852016-09-23 11:03:15 -070061static inline bool isSupported(ScalarType::Kind kind) {
Timur Iskhakov63f39902017-08-29 15:47:29 -070062 return SK(BOOL) == kind || ScalarType(kind, nullptr /* parent */).isValidEnumStorageType();
Yifan Hongf24fa852016-09-23 11:03:15 -070063}
64
Yifan Hong57886972016-08-17 10:42:15 -070065/* See docs at the end for details on integral promotion. */
66ScalarType::Kind integralPromotion(ScalarType::Kind in) {
Yifan Hong2bd3c1f2016-09-22 13:20:05 -070067 return SK(INT32) < in ? in : SK(INT32); // note that KIND_INT32 < KIND_UINT32
Yifan Hong52165692016-08-12 18:06:40 -070068}
69
Yifan Hong57886972016-08-17 10:42:15 -070070/* See docs at the end for details on usual arithmetic conversion. */
Yifan Hong2bd3c1f2016-09-22 13:20:05 -070071ScalarType::Kind usualArithmeticConversion(ScalarType::Kind lft,
72 ScalarType::Kind rgt) {
Yifan Hongf24fa852016-09-23 11:03:15 -070073 CHECK(isSupported(lft) && isSupported(rgt));
Yifan Hong2bd3c1f2016-09-22 13:20:05 -070074 // Kinds in concern: bool, (u)int[8|16|32|64]
75 if(lft == rgt) return lft; // easy case
76 if(lft == SK(BOOL)) return rgt;
77 if(rgt == SK(BOOL)) return lft;
78 bool isLftSigned = (lft == SK(INT8)) || (lft == SK(INT16))
79 || (lft == SK(INT32)) || (lft == SK(INT64));
80 bool isRgtSigned = (rgt == SK(INT8)) || (rgt == SK(INT16))
81 || (rgt == SK(INT32)) || (rgt == SK(INT64));
82 if(isLftSigned == isRgtSigned) return lft < rgt ? rgt : lft;
83 ScalarType::Kind unsignedRank = isLftSigned ? rgt : lft;
84 ScalarType::Kind signedRank = isLftSigned ? lft : rgt;
85 if(unsignedRank >= signedRank) return unsignedRank;
86 if(signedRank > unsignedRank) return signedRank;
Yifan Hong57886972016-08-17 10:42:15 -070087
Yifan Hong2bd3c1f2016-09-22 13:20:05 -070088 // Although there is such rule to return "the unsigned counterpart of
89 // the signed operand", it should not reach here in our HIDL grammar.
Steven Morelandcbff5612017-10-11 17:01:54 -070090 CHECK(false) << "Could not do usual arithmetic conversion for type " << lft << "and" << rgt;
Yifan Hong2bd3c1f2016-09-22 13:20:05 -070091 switch(signedRank) {
92 case SK(INT8): return SK(UINT8);
93 case SK(INT16): return SK(UINT16);
94 case SK(INT32): return SK(UINT32);
95 case SK(INT64): return SK(UINT64);
96 default: return SK(UINT64);
97 }
Yifan Hong52165692016-08-12 18:06:40 -070098}
Yifan Hong57886972016-08-17 10:42:15 -070099
100template <class T>
Timur Iskhakov7296af12017-08-09 21:52:48 +0000101T handleUnary(const std::string& op, T val) {
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700102 COMPUTE_UNARY(+)
103 COMPUTE_UNARY(-)
104 COMPUTE_UNARY(!)
105 COMPUTE_UNARY(~)
106 // Should not reach here.
Yifan Hongf24fa852016-09-23 11:03:15 -0700107 SHOULD_NOT_REACH() << "Could not handleUnary for " << op << " " << val;
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700108 return static_cast<T>(0xdeadbeef);
Yifan Hong57886972016-08-17 10:42:15 -0700109}
110
111template <class T>
Timur Iskhakov7296af12017-08-09 21:52:48 +0000112T handleBinaryCommon(T lval, const std::string& op, T rval) {
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700113 COMPUTE_BINARY(+)
114 COMPUTE_BINARY(-)
115 COMPUTE_BINARY(*)
116 COMPUTE_BINARY(/)
117 COMPUTE_BINARY(%)
118 COMPUTE_BINARY(|)
119 COMPUTE_BINARY(^)
120 COMPUTE_BINARY(&)
121 // comparison operators: return 0 or 1 by nature.
122 COMPUTE_BINARY(==)
123 COMPUTE_BINARY(!=)
124 COMPUTE_BINARY(<)
125 COMPUTE_BINARY(>)
126 COMPUTE_BINARY(<=)
127 COMPUTE_BINARY(>=)
128 // Should not reach here.
Yifan Hongf24fa852016-09-23 11:03:15 -0700129 SHOULD_NOT_REACH() << "Could not handleBinaryCommon for "
130 << lval << " " << op << " " << rval;
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700131 return static_cast<T>(0xdeadbeef);
Yifan Hong57886972016-08-17 10:42:15 -0700132}
133
134template <class T>
Timur Iskhakov7296af12017-08-09 21:52:48 +0000135T handleShift(T lval, const std::string& op, int64_t rval) {
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700136 // just cast rval to int64_t and it should fit.
137 COMPUTE_BINARY(>>)
138 COMPUTE_BINARY(<<)
139 // Should not reach here.
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700140 SHOULD_NOT_REACH() << "Could not handleShift for "
Yifan Hongf24fa852016-09-23 11:03:15 -0700141 << lval << " " << op << " " << rval;
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700142 return static_cast<T>(0xdeadbeef);
Yifan Hong57886972016-08-17 10:42:15 -0700143}
144
Timur Iskhakov7296af12017-08-09 21:52:48 +0000145bool handleLogical(bool lval, const std::string& op, bool rval) {
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700146 COMPUTE_BINARY(||);
147 COMPUTE_BINARY(&&);
148 // Should not reach here.
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700149 SHOULD_NOT_REACH() << "Could not handleLogical for "
Yifan Hongf24fa852016-09-23 11:03:15 -0700150 << lval << " " << op << " " << rval;
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700151 return false;
Yifan Hong57886972016-08-17 10:42:15 -0700152}
153
Timur Iskhakov7296af12017-08-09 21:52:48 +0000154std::unique_ptr<ConstantExpression> ConstantExpression::Zero(ScalarType::Kind kind) {
155 return ValueOf(kind, 0);
Yifan Hongf24fa852016-09-23 11:03:15 -0700156}
157
Timur Iskhakov7296af12017-08-09 21:52:48 +0000158std::unique_ptr<ConstantExpression> ConstantExpression::One(ScalarType::Kind kind) {
159 return ValueOf(kind, 1);
Yifan Hongf24fa852016-09-23 11:03:15 -0700160}
161
Timur Iskhakov7296af12017-08-09 21:52:48 +0000162std::unique_ptr<ConstantExpression> ConstantExpression::ValueOf(ScalarType::Kind kind,
163 uint64_t value) {
164 return std::make_unique<LiteralConstantExpression>(kind, value);
Yifan Hong30b5d1f2017-04-03 12:19:25 -0700165}
166
Timur Iskhakov7296af12017-08-09 21:52:48 +0000167bool ConstantExpression::isEvaluated() const {
168 return mIsEvaluated;
169}
170
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700171LiteralConstantExpression::LiteralConstantExpression(
172 ScalarType::Kind kind, uint64_t value, const std::string& expr) {
173
174 CHECK(!expr.empty());
Yifan Hong30b5d1f2017-04-03 12:19:25 -0700175 CHECK(isSupported(kind));
Steven Moreland77943692018-08-09 12:53:42 -0700176 mTrivialDescription = std::to_string(value) == expr;
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700177 mExpr = expr;
Timur Iskhakov7296af12017-08-09 21:52:48 +0000178 mValueKind = kind;
179 mValue = value;
180 mIsEvaluated = true;
Yifan Hongf24fa852016-09-23 11:03:15 -0700181}
182
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700183LiteralConstantExpression::LiteralConstantExpression(ScalarType::Kind kind, uint64_t value)
184 : LiteralConstantExpression(kind, value, std::to_string(value)) {}
185
186LiteralConstantExpression* LiteralConstantExpression::tryParse(const std::string& value) {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000187 CHECK(!value.empty());
Yifan Hongf24fa852016-09-23 11:03:15 -0700188
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700189 bool isLong = false, isUnsigned = false;
Timur Iskhakov7296af12017-08-09 21:52:48 +0000190 bool isHex = (value[0] == '0' && value.length() > 1 && (value[1] == 'x' || value[1] == 'X'));
191
192 auto rbegin = value.rbegin();
193 auto rend = value.rend();
194 for (; rbegin != rend && (*rbegin == 'u' || *rbegin == 'U' || *rbegin == 'l' || *rbegin == 'L');
195 ++rbegin) {
196 isUnsigned |= (*rbegin == 'u' || *rbegin == 'U');
197 isLong |= (*rbegin == 'l' || *rbegin == 'L');
Yifan Hong57886972016-08-17 10:42:15 -0700198 }
Timur Iskhakov7296af12017-08-09 21:52:48 +0000199 std::string newVal(value.begin(), rbegin.base());
200 CHECK(!newVal.empty());
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700201
202 uint64_t rawValue = 0;
203
204 bool parseOK = base::ParseUint(newVal, &rawValue);
205 if (!parseOK) {
206 return nullptr;
207 }
208
209 ScalarType::Kind kind;
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700210
211 // guess literal type.
212 if(isLong) {
213 if(isUnsigned) // ul
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700214 kind = SK(UINT64);
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700215 else // l
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700216 kind = SK(INT64);
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700217 } else { // no l suffix
218 if(isUnsigned) { // u
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700219 if(rawValue <= UINT32_MAX)
220 kind = SK(UINT32);
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700221 else
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700222 kind = SK(UINT64);
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700223 } else { // no suffix
224 if(isHex) {
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700225 if(rawValue <= INT32_MAX) // rawValue always >= 0
226 kind = SK(INT32);
227 else if(rawValue <= UINT32_MAX)
228 kind = SK(UINT32);
229 else if(rawValue <= INT64_MAX) // rawValue always >= 0
230 kind = SK(INT64);
231 else if(rawValue <= UINT64_MAX)
232 kind = SK(UINT64);
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700233 else
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700234 return nullptr;
235 } else {
236 if(rawValue <= INT32_MAX) // rawValue always >= 0
237 kind = SK(INT32);
238 else
239 kind = SK(INT64);
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700240 }
241 }
242 }
Steven Morelandd9d6dcb2017-09-20 15:55:39 -0700243
244 return new LiteralConstantExpression(kind, rawValue, value);
Yifan Hong57886972016-08-17 10:42:15 -0700245}
246
Timur Iskhakov7296af12017-08-09 21:52:48 +0000247void LiteralConstantExpression::evaluate() {
248 // Evaluated in constructor
249 CHECK(isEvaluated());
250}
Yifan Hongf24fa852016-09-23 11:03:15 -0700251
Timur Iskhakov7296af12017-08-09 21:52:48 +0000252void UnaryConstantExpression::evaluate() {
253 if (isEvaluated()) return;
Timur Iskhakov891a8662017-08-25 21:53:48 -0700254 CHECK(mUnary->isEvaluated());
Timur Iskhakov7296af12017-08-09 21:52:48 +0000255 mIsEvaluated = true;
256
Steven Morelandf21962d2018-08-09 12:44:40 -0700257 mExpr = std::string("(") + mOp + mUnary->mExpr + ")";
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700258 mValueKind = mUnary->mValueKind;
Timur Iskhakov7296af12017-08-09 21:52:48 +0000259
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700260#define CASE_UNARY(__type__) \
261 mValue = handleUnary(mOp, static_cast<__type__>(mUnary->mValue)); \
Timur Iskhakov7296af12017-08-09 21:52:48 +0000262 return;
Yifan Hong57886972016-08-17 10:42:15 -0700263
Yifan Hongf24fa852016-09-23 11:03:15 -0700264 SWITCH_KIND(mValueKind, CASE_UNARY, SHOULD_NOT_REACH(); return;)
Yifan Hong52165692016-08-12 18:06:40 -0700265}
Yifan Hong57886972016-08-17 10:42:15 -0700266
Timur Iskhakov7296af12017-08-09 21:52:48 +0000267void BinaryConstantExpression::evaluate() {
268 if (isEvaluated()) return;
Timur Iskhakov891a8662017-08-25 21:53:48 -0700269 CHECK(mLval->isEvaluated());
270 CHECK(mRval->isEvaluated());
Timur Iskhakov7296af12017-08-09 21:52:48 +0000271 mIsEvaluated = true;
272
Steven Morelandf21962d2018-08-09 12:44:40 -0700273 mExpr = std::string("(") + mLval->mExpr + " " + mOp + " " + mRval->mExpr + ")";
Yifan Hong57886972016-08-17 10:42:15 -0700274
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700275 bool isArithmeticOrBitflip = OP_IS_BIN_ARITHMETIC || OP_IS_BIN_BITFLIP;
276
277 // CASE 1: + - * / % | ^ & < > <= >= == !=
278 if(isArithmeticOrBitflip || OP_IS_BIN_COMP) {
279 // promoted kind for both operands.
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700280 ScalarType::Kind promoted = usualArithmeticConversion(integralPromotion(mLval->mValueKind),
281 integralPromotion(mRval->mValueKind));
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700282 // result kind.
283 mValueKind = isArithmeticOrBitflip
284 ? promoted // arithmetic or bitflip operators generates promoted type
285 : SK(BOOL); // comparison operators generates bool
286
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700287#define CASE_BINARY_COMMON(__type__) \
288 mValue = handleBinaryCommon(static_cast<__type__>(mLval->mValue), mOp, \
289 static_cast<__type__>(mRval->mValue)); \
Timur Iskhakov7296af12017-08-09 21:52:48 +0000290 return;
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700291
Yifan Hongf24fa852016-09-23 11:03:15 -0700292 SWITCH_KIND(promoted, CASE_BINARY_COMMON, SHOULD_NOT_REACH(); return;)
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700293 }
294
295 // CASE 2: << >>
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700296 std::string newOp = mOp;
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700297 if(OP_IS_BIN_SHIFT) {
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700298 mValueKind = integralPromotion(mLval->mValueKind);
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700299 // instead of promoting rval, simply casting it to int64 should also be good.
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700300 int64_t numBits = mRval->cast<int64_t>();
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700301 if(numBits < 0) {
302 // shifting with negative number of bits is undefined in C. In HIDL it
303 // is defined as shifting into the other direction.
Timur Iskhakov7296af12017-08-09 21:52:48 +0000304 newOp = OPEQ("<<") ? std::string(">>") : std::string("<<");
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700305 numBits = -numBits;
306 }
307
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700308#define CASE_SHIFT(__type__) \
309 mValue = handleShift(static_cast<__type__>(mLval->mValue), newOp, numBits); \
Timur Iskhakov7296af12017-08-09 21:52:48 +0000310 return;
Yifan Hong57886972016-08-17 10:42:15 -0700311
Yifan Hongf24fa852016-09-23 11:03:15 -0700312 SWITCH_KIND(mValueKind, CASE_SHIFT, SHOULD_NOT_REACH(); return;)
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700313 }
Yifan Hong57886972016-08-17 10:42:15 -0700314
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700315 // CASE 3: && ||
316 if(OP_IS_BIN_LOGICAL) {
317 mValueKind = SK(BOOL);
318 // easy; everything is bool.
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700319 mValue = handleLogical(mLval->mValue, mOp, mRval->mValue);
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700320 return;
321 }
Yifan Hong57886972016-08-17 10:42:15 -0700322
Yifan Hongf24fa852016-09-23 11:03:15 -0700323 SHOULD_NOT_REACH();
Yifan Hong57886972016-08-17 10:42:15 -0700324}
325
Timur Iskhakov7296af12017-08-09 21:52:48 +0000326void TernaryConstantExpression::evaluate() {
327 if (isEvaluated()) return;
Timur Iskhakov891a8662017-08-25 21:53:48 -0700328 CHECK(mCond->isEvaluated());
329 CHECK(mTrueVal->isEvaluated());
330 CHECK(mFalseVal->isEvaluated());
Timur Iskhakov7296af12017-08-09 21:52:48 +0000331 mIsEvaluated = true;
332
Steven Morelandf21962d2018-08-09 12:44:40 -0700333 mExpr = std::string("(") + mCond->mExpr + "?" + mTrueVal->mExpr + ":" + mFalseVal->mExpr + ")";
Yifan Hongf24fa852016-09-23 11:03:15 -0700334
Timur Iskhakov891a8662017-08-25 21:53:48 -0700335 // note: for ?:, unlike arithmetic ops, integral promotion is not processed.
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700336 mValueKind = usualArithmeticConversion(mTrueVal->mValueKind, mFalseVal->mValueKind);
Yifan Hong57886972016-08-17 10:42:15 -0700337
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700338#define CASE_TERNARY(__type__) \
339 mValue = mCond->mValue ? (static_cast<__type__>(mTrueVal->mValue)) \
340 : (static_cast<__type__>(mFalseVal->mValue)); \
Timur Iskhakov7296af12017-08-09 21:52:48 +0000341 return;
Yifan Hong57886972016-08-17 10:42:15 -0700342
Yifan Hongf24fa852016-09-23 11:03:15 -0700343 SWITCH_KIND(mValueKind, CASE_TERNARY, SHOULD_NOT_REACH(); return;)
Yifan Hong52165692016-08-12 18:06:40 -0700344}
345
Timur Iskhakov7296af12017-08-09 21:52:48 +0000346void ReferenceConstantExpression::evaluate() {
347 if (isEvaluated()) return;
Timur Iskhakov891a8662017-08-25 21:53:48 -0700348 CHECK(mReference->constExpr() != nullptr);
Timur Iskhakov7296af12017-08-09 21:52:48 +0000349
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700350 ConstantExpression* expr = mReference->constExpr();
Timur Iskhakov891a8662017-08-25 21:53:48 -0700351 CHECK(expr->isEvaluated());
Timur Iskhakov7296af12017-08-09 21:52:48 +0000352
353 mValueKind = expr->mValueKind;
354 mValue = expr->mValue;
355 mIsEvaluated = true;
Yifan Hong52165692016-08-12 18:06:40 -0700356}
Yifan Hong57886972016-08-17 10:42:15 -0700357
Timur Iskhakov7296af12017-08-09 21:52:48 +0000358std::unique_ptr<ConstantExpression> ConstantExpression::addOne(ScalarType::Kind baseKind) {
359 auto ret = std::make_unique<BinaryConstantExpression>(
360 this, "+", ConstantExpression::One(baseKind).release());
Timur Iskhakov7296af12017-08-09 21:52:48 +0000361 return ret;
Yifan Hongf24fa852016-09-23 11:03:15 -0700362}
363
Yifan Hongfc610cd2016-09-22 13:34:45 -0700364std::string ConstantExpression::value() const {
Steven Morelandf21962d2018-08-09 12:44:40 -0700365 return value(mValueKind);
Yifan Hongf24fa852016-09-23 11:03:15 -0700366}
367
Yifan Hongc07b2022016-11-08 12:44:24 -0800368std::string ConstantExpression::value(ScalarType::Kind castKind) const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000369 CHECK(isEvaluated());
Steven Morelandf21962d2018-08-09 12:44:40 -0700370 return rawValue(castKind) + descriptionSuffix();
Yifan Hongc07b2022016-11-08 12:44:24 -0800371}
372
Yifan Hongf24fa852016-09-23 11:03:15 -0700373std::string ConstantExpression::cppValue() const {
374 return cppValue(mValueKind);
Yifan Hong52165692016-08-12 18:06:40 -0700375}
376
Yifan Hongfc610cd2016-09-22 13:34:45 -0700377std::string ConstantExpression::cppValue(ScalarType::Kind castKind) const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000378 CHECK(isEvaluated());
Yifan Hongf24fa852016-09-23 11:03:15 -0700379 std::string literal(rawValue(castKind));
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700380 // this is a hack to translate
381 // enum x : int64_t { y = 1l << 63 };
382 // into
383 // enum class x : int64_t { y = (int64_t)-9223372036854775808ull };
384 // by adding the explicit cast.
385 // Because 9223372036854775808 is uint64_t, and
386 // -(uint64_t)9223372036854775808 == 9223372036854775808 could not
387 // be narrowed to int64_t.
388 if(castKind == SK(INT64) && (int64_t)mValue == INT64_MIN) {
Steven Morelandf21962d2018-08-09 12:44:40 -0700389 literal = "static_cast<" +
390 ScalarType(SK(INT64), nullptr /* parent */).getCppStackType() // "int64_t"
391 + ">(" + literal + "ull)";
392 } else {
393 // add suffix if necessary.
394 if (castKind == SK(UINT32) || castKind == SK(UINT64)) literal += "u";
395 if (castKind == SK(UINT64) || castKind == SK(INT64)) literal += "ll";
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700396 }
Yifan Hong57886972016-08-17 10:42:15 -0700397
Steven Morelandf21962d2018-08-09 12:44:40 -0700398 return literal + descriptionSuffix();
Yifan Hong57886972016-08-17 10:42:15 -0700399}
400
Yifan Hongf24fa852016-09-23 11:03:15 -0700401std::string ConstantExpression::javaValue() const {
402 return javaValue(mValueKind);
Yifan Hong19ca75a2016-08-31 10:20:03 -0700403}
404
Yifan Hongf24fa852016-09-23 11:03:15 -0700405std::string ConstantExpression::javaValue(ScalarType::Kind castKind) const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000406 CHECK(isEvaluated());
Steven Morelandf21962d2018-08-09 12:44:40 -0700407 std::string literal;
408
Yifan Hongf24fa852016-09-23 11:03:15 -0700409 switch(castKind) {
Steven Morelandf21962d2018-08-09 12:44:40 -0700410 case SK(UINT64):
411 literal = rawValue(SK(INT64)) + "L";
412 break;
413 case SK(INT64):
414 literal = rawValue(SK(INT64)) + "L";
415 break;
416 case SK(UINT32):
417 literal = rawValue(SK(INT32));
418 break;
419 case SK(UINT16):
420 literal = rawValue(SK(INT16));
421 break;
422 case SK(UINT8):
423 literal = rawValue(SK(INT8));
424 break;
Yifan Hongf24fa852016-09-23 11:03:15 -0700425 case SK(BOOL) :
Steven Morelandf21962d2018-08-09 12:44:40 -0700426 literal = this->cast<bool>() ? "true" : "false";
427 break;
428 default:
429 literal = rawValue(castKind);
430 break;
Yifan Hongf24fa852016-09-23 11:03:15 -0700431 }
Steven Morelandf21962d2018-08-09 12:44:40 -0700432
433 return literal + descriptionSuffix();
434}
435
436const std::string& ConstantExpression::expression() const {
437 CHECK(isEvaluated());
438 return mExpr;
439}
440
441std::string ConstantExpression::rawValue() const {
442 return rawValue(mValueKind);
Yifan Hongf24fa852016-09-23 11:03:15 -0700443}
444
445std::string ConstantExpression::rawValue(ScalarType::Kind castKind) const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000446 CHECK(isEvaluated());
Yifan Hong57886972016-08-17 10:42:15 -0700447
Yifan Hongfc610cd2016-09-22 13:34:45 -0700448#define CASE_STR(__type__) return std::to_string(this->cast<__type__>());
Yifan Hong57886972016-08-17 10:42:15 -0700449
Yi Kongd7f8ab32018-07-24 11:27:02 -0700450 SWITCH_KIND(castKind, CASE_STR, SHOULD_NOT_REACH(); return nullptr; );
Yifan Hong57886972016-08-17 10:42:15 -0700451}
452
Yifan Hong19ca75a2016-08-31 10:20:03 -0700453template<typename T>
454T ConstantExpression::cast() const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000455 CHECK(isEvaluated());
Yifan Hong57886972016-08-17 10:42:15 -0700456
Yifan Hong19ca75a2016-08-31 10:20:03 -0700457#define CASE_CAST_T(__type__) return static_cast<T>(static_cast<__type__>(mValue));
Yifan Hong57886972016-08-17 10:42:15 -0700458
Yifan Hongf24fa852016-09-23 11:03:15 -0700459 SWITCH_KIND(mValueKind, CASE_CAST_T, SHOULD_NOT_REACH(); return 0; );
Yifan Hong57886972016-08-17 10:42:15 -0700460}
461
Steven Morelandf21962d2018-08-09 12:44:40 -0700462std::string ConstantExpression::descriptionSuffix() const {
463 CHECK(isEvaluated());
464
465 if (!mTrivialDescription) {
466 CHECK(!mExpr.empty());
467
468 return " /* " + mExpr + " */";
469 }
470 return "";
471}
472
Yifan Honge77ca132016-09-27 10:49:05 -0700473size_t ConstantExpression::castSizeT() const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000474 CHECK(isEvaluated());
Yifan Honge77ca132016-09-27 10:49:05 -0700475 return this->cast<size_t>();
476}
477
Timur Iskhakova6d33882017-09-01 13:02:09 -0700478bool ConstantExpression::isReferenceConstantExpression() const {
479 return false;
480}
481
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700482std::vector<ConstantExpression*> ConstantExpression::getConstantExpressions() {
483 const auto& constRet = static_cast<const ConstantExpression*>(this)->getConstantExpressions();
484 std::vector<ConstantExpression*> ret(constRet.size());
485 std::transform(constRet.begin(), constRet.end(), ret.begin(),
486 [](const auto* ce) { return const_cast<ConstantExpression*>(ce); });
487 return ret;
488}
489
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700490std::vector<Reference<LocalIdentifier>*> ConstantExpression::getReferences() {
491 const auto& constRet = static_cast<const ConstantExpression*>(this)->getReferences();
492 std::vector<Reference<LocalIdentifier>*> ret(constRet.size());
493 std::transform(constRet.begin(), constRet.end(), ret.begin(),
494 [](const auto* ce) { return const_cast<Reference<LocalIdentifier>*>(ce); });
495 return ret;
496}
497
498std::vector<const Reference<LocalIdentifier>*> ConstantExpression::getReferences() const {
499 return {};
500}
501
Timur Iskhakov891a8662017-08-25 21:53:48 -0700502status_t ConstantExpression::recursivePass(const std::function<status_t(ConstantExpression*)>& func,
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700503 std::unordered_set<const ConstantExpression*>* visited,
504 bool processBeforeDependencies) {
Timur Iskhakov35930c42017-08-28 18:49:54 -0700505 if (mIsPostParseCompleted) return OK;
506
Timur Iskhakov891a8662017-08-25 21:53:48 -0700507 if (visited->find(this) != visited->end()) return OK;
508 visited->insert(this);
509
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700510 if (processBeforeDependencies) {
511 status_t err = func(this);
512 if (err != OK) return err;
513 }
514
Timur Iskhakov891a8662017-08-25 21:53:48 -0700515 for (auto* nextCE : getConstantExpressions()) {
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700516 status_t err = nextCE->recursivePass(func, visited, processBeforeDependencies);
Timur Iskhakov891a8662017-08-25 21:53:48 -0700517 if (err != OK) return err;
518 }
519
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700520 for (auto* nextRef : getReferences()) {
521 auto* nextCE = nextRef->shallowGet()->constExpr();
522 CHECK(nextCE != nullptr) << "Local identifier is not a constant expression";
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700523 status_t err = nextCE->recursivePass(func, visited, processBeforeDependencies);
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700524 if (err != OK) return err;
525 }
526
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700527 if (!processBeforeDependencies) {
528 status_t err = func(this);
529 if (err != OK) return err;
530 }
Timur Iskhakov891a8662017-08-25 21:53:48 -0700531
532 return OK;
533}
534
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700535status_t ConstantExpression::recursivePass(
536 const std::function<status_t(const ConstantExpression*)>& func,
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700537 std::unordered_set<const ConstantExpression*>* visited, bool processBeforeDependencies) const {
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700538 if (mIsPostParseCompleted) return OK;
539
540 if (visited->find(this) != visited->end()) return OK;
541 visited->insert(this);
542
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700543 if (processBeforeDependencies) {
544 status_t err = func(this);
545 if (err != OK) return err;
546 }
547
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700548 for (const auto* nextCE : getConstantExpressions()) {
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700549 status_t err = nextCE->recursivePass(func, visited, processBeforeDependencies);
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700550 if (err != OK) return err;
551 }
552
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700553 for (const auto* nextRef : getReferences()) {
554 const auto* nextCE = nextRef->shallowGet()->constExpr();
555 CHECK(nextCE != nullptr) << "Local identifier is not a constant expression";
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700556 status_t err = nextCE->recursivePass(func, visited, processBeforeDependencies);
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700557 if (err != OK) return err;
558 }
559
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700560 if (!processBeforeDependencies) {
561 status_t err = func(this);
562 if (err != OK) return err;
563 }
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700564
565 return OK;
566}
567
Timur Iskhakova6d33882017-09-01 13:02:09 -0700568ConstantExpression::CheckAcyclicStatus::CheckAcyclicStatus(
569 status_t status, const ConstantExpression* cycleEnd,
570 const ReferenceConstantExpression* lastReference)
571 : status(status), cycleEnd(cycleEnd), lastReference(lastReference) {
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700572 CHECK(cycleEnd == nullptr || status != OK);
Timur Iskhakova6d33882017-09-01 13:02:09 -0700573 CHECK((cycleEnd == nullptr) == (lastReference == nullptr));
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700574}
575
576ConstantExpression::CheckAcyclicStatus ConstantExpression::checkAcyclic(
577 std::unordered_set<const ConstantExpression*>* visited,
578 std::unordered_set<const ConstantExpression*>* stack) const {
579 if (stack->find(this) != stack->end()) {
Timur Iskhakova6d33882017-09-01 13:02:09 -0700580 CHECK(isReferenceConstantExpression())
581 << "Only reference constant expression could be the cycle end";
582
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700583 std::cerr << "ERROR: Cyclic declaration:\n";
Timur Iskhakova6d33882017-09-01 13:02:09 -0700584 return CheckAcyclicStatus(UNKNOWN_ERROR, this,
585 static_cast<const ReferenceConstantExpression*>(this));
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700586 }
587
588 if (visited->find(this) != visited->end()) return CheckAcyclicStatus(OK);
589 visited->insert(this);
590 stack->insert(this);
591
592 for (const auto* nextCE : getConstantExpressions()) {
593 auto err = nextCE->checkAcyclic(visited, stack);
594 if (err.status != OK) {
595 return err;
596 }
597 }
598
599 for (const auto* nextRef : getReferences()) {
600 const auto* nextCE = nextRef->shallowGet()->constExpr();
601 CHECK(nextCE != nullptr) << "Local identifier is not a constant expression";
602 auto err = nextCE->checkAcyclic(visited, stack);
603
604 if (err.status != OK) {
605 if (err.cycleEnd == nullptr) return err;
606
607 // Only ReferenceConstantExpression has references,
Timur Iskhakova6d33882017-09-01 13:02:09 -0700608 CHECK(isReferenceConstantExpression())
609 << "Only reference constant expression could have refereneces";
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700610
Timur Iskhakova6d33882017-09-01 13:02:09 -0700611 // mExpr is defined explicitly before evaluation
612 std::cerr << " '" << err.lastReference->mExpr << "' in '" << mExpr << "' at "
613 << nextRef->location() << "\n";
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700614
615 if (err.cycleEnd == this) {
616 return CheckAcyclicStatus(err.status);
617 }
Timur Iskhakova6d33882017-09-01 13:02:09 -0700618 return CheckAcyclicStatus(err.status, err.cycleEnd,
619 static_cast<const ReferenceConstantExpression*>(this));
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700620 }
621 }
622
623 CHECK(stack->find(this) != stack->end());
624 stack->erase(this);
625 return CheckAcyclicStatus(OK);
626}
627
Timur Iskhakov35930c42017-08-28 18:49:54 -0700628void ConstantExpression::setPostParseCompleted() {
629 CHECK(!mIsPostParseCompleted);
630 mIsPostParseCompleted = true;
631}
632
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700633std::vector<const ConstantExpression*> LiteralConstantExpression::getConstantExpressions() const {
Timur Iskhakov891a8662017-08-25 21:53:48 -0700634 return {};
635}
636
Timur Iskhakov7296af12017-08-09 21:52:48 +0000637UnaryConstantExpression::UnaryConstantExpression(const std::string& op, ConstantExpression* value)
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700638 : mUnary(value), mOp(op) {}
Timur Iskhakov7296af12017-08-09 21:52:48 +0000639
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700640std::vector<const ConstantExpression*> UnaryConstantExpression::getConstantExpressions() const {
Timur Iskhakov891a8662017-08-25 21:53:48 -0700641 return {mUnary};
642}
643
Timur Iskhakov7296af12017-08-09 21:52:48 +0000644BinaryConstantExpression::BinaryConstantExpression(ConstantExpression* lval, const std::string& op,
645 ConstantExpression* rval)
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700646 : mLval(lval), mRval(rval), mOp(op) {}
Timur Iskhakov7296af12017-08-09 21:52:48 +0000647
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700648std::vector<const ConstantExpression*> BinaryConstantExpression::getConstantExpressions() const {
Timur Iskhakov891a8662017-08-25 21:53:48 -0700649 return {mLval, mRval};
650}
651
Timur Iskhakov7296af12017-08-09 21:52:48 +0000652TernaryConstantExpression::TernaryConstantExpression(ConstantExpression* cond,
653 ConstantExpression* trueVal,
654 ConstantExpression* falseVal)
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700655 : mCond(cond), mTrueVal(trueVal), mFalseVal(falseVal) {}
Timur Iskhakov7296af12017-08-09 21:52:48 +0000656
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700657std::vector<const ConstantExpression*> TernaryConstantExpression::getConstantExpressions() const {
Timur Iskhakov891a8662017-08-25 21:53:48 -0700658 return {mCond, mTrueVal, mFalseVal};
659}
660
Timur Iskhakov7296af12017-08-09 21:52:48 +0000661ReferenceConstantExpression::ReferenceConstantExpression(const Reference<LocalIdentifier>& value,
662 const std::string& expr)
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700663 : mReference(value) {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000664 mExpr = expr;
Timur Iskhakov505e5612017-08-27 18:26:48 -0700665 mTrivialDescription = mExpr.empty();
Timur Iskhakov7296af12017-08-09 21:52:48 +0000666}
667
Timur Iskhakova6d33882017-09-01 13:02:09 -0700668bool ReferenceConstantExpression::isReferenceConstantExpression() const {
669 return true;
670}
671
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700672std::vector<const ConstantExpression*> ReferenceConstantExpression::getConstantExpressions() const {
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700673 // Returns reference instead
674 return {};
675}
676
677std::vector<const Reference<LocalIdentifier>*> ReferenceConstantExpression::getReferences() const {
678 return {&mReference};
Timur Iskhakov891a8662017-08-25 21:53:48 -0700679}
680
Yifan Hong57886972016-08-17 10:42:15 -0700681/*
682
683Evaluating expressions in HIDL language
684
685The following rules are mostly like that in:
686http://en.cppreference.com/w/cpp/language/operator_arithmetic
687http://en.cppreference.com/w/cpp/language/operator_logical
688http://en.cppreference.com/w/cpp/language/operator_comparison
689http://en.cppreference.com/w/cpp/language/operator_other
690
691The type of literal is the first type which the value
692can fit from the list of types depending on the suffix and bases.
693
694suffix decimal bases hexadecimal bases
695no suffix int32_t int32_t
696 int64_t uint32_t
697 int64_t
698 uint64_t
699
700u/U uint32_t (same as left)
701 uint64_t
702
703l/L int64_t int64_t
704
705ul/UL/uL/Ul uint64_t uint64_t
706
707
708Note: There are no negative integer literals.
709 -1 is the unary minus applied to 1.
710
711Unary arithmetic and bitwise operators (~ + -):
712 don't change the type of the argument.
713 (so -1u = -(1u) has type uint32_t)
714
715Binary arithmetic and bitwise operators (except shifts) (+ - * / % & | ^):
7161. Integral promotion is first applied on both sides.
7172. If both operands have the same type, no promotion is necessary.
7183. Usual arithmetic conversions.
719
720Integral promotion: if an operand is of a type with less than 32 bits,
721(including bool), it is promoted to int32_t.
722
723Usual arithmetic conversions:
7241. If operands are both signed or both unsigned, lesser conversion rank is
725 converted to greater conversion rank.
7262. Otherwise, if unsigned's rank >= signed's rank, -> unsigned's type
7273. Otherwise, if signed's type can hold all values in unsigned's type,
728 -> signed's type
7294. Otherwise, both converted to the unsigned counterpart of the signed operand's
730 type.
731rank: bool < int8_t < int16_t < int32_t < int64_t
732
733
734Shift operators (<< >>):
7351. Integral promotion is applied on both sides.
7362. For unsigned a, a << b discards bits that shifts out.
737 For signed non-negative a, a << b is legal if no bits shifts out, otherwise error.
738 For signed negative a, a << b gives error.
7393. For unsigned and signed non-negative a, a >> b discards bits that shifts out.
740 For signed negative a, a >> b discards bits that shifts out, and the signed
741 bit gets extended. ("arithmetic right shift")
7424. Shifting with negative number of bits is undefined. (Currently, the
743 parser will shift into the other direction. This behavior may change.)
7445. Shifting with number of bits exceeding the width of the type is undefined.
745 (Currently, 1 << 32 == 1. This behavior may change.)
746
747Logical operators (!, &&, ||):
7481. Convert first operand to bool. (true if non-zero, false otherwise)
7492. If short-circuited, return the result as type bool, value 1 or 0.
7503. Otherwise, convert second operand to bool, evaluate the result, and return
751 the result in the same fashion.
752
753Arithmetic comparison operators (< > <= >= == !=):
7541. Promote operands in the same way as binary arithmetic and bitwise operators.
755 (Integral promotion + Usual arithmetic conversions)
7562. Return type bool, value 0 or 1 the same way as logical operators.
757
758Ternary conditional operator (?:):
7591. Evaluate the conditional and evaluate the operands.
7602. Return type of expression is the type under usual arithmetic conversions on
761 the second and third operand. (No integral promotions necessary.)
762
763*/
764
Yifan Hong52165692016-08-12 18:06:40 -0700765} // namespace android
766