blob: 8a2b8756e75faffb66bed3b8d3078e5c7536dba9 [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));
Timur Iskhakov7296af12017-08-09 21:52:48 +0000176 mTrivialDescription = true;
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
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700257 mExpr = std::string("(") + mOp + mUnary->description() + ")";
258 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
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700273 mExpr = std::string("(") + mLval->description() + " " + mOp + " " + mRval->description() + ")";
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
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700333 mExpr = std::string("(") + mCond->description() + "?" + mTrueVal->description() + ":" +
334 mFalseVal->description() + ")";
Yifan Hongf24fa852016-09-23 11:03:15 -0700335
Timur Iskhakov891a8662017-08-25 21:53:48 -0700336 // note: for ?:, unlike arithmetic ops, integral promotion is not processed.
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700337 mValueKind = usualArithmeticConversion(mTrueVal->mValueKind, mFalseVal->mValueKind);
Yifan Hong57886972016-08-17 10:42:15 -0700338
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700339#define CASE_TERNARY(__type__) \
340 mValue = mCond->mValue ? (static_cast<__type__>(mTrueVal->mValue)) \
341 : (static_cast<__type__>(mFalseVal->mValue)); \
Timur Iskhakov7296af12017-08-09 21:52:48 +0000342 return;
Yifan Hong57886972016-08-17 10:42:15 -0700343
Yifan Hongf24fa852016-09-23 11:03:15 -0700344 SWITCH_KIND(mValueKind, CASE_TERNARY, SHOULD_NOT_REACH(); return;)
Yifan Hong52165692016-08-12 18:06:40 -0700345}
346
Timur Iskhakov7296af12017-08-09 21:52:48 +0000347void ReferenceConstantExpression::evaluate() {
348 if (isEvaluated()) return;
Timur Iskhakov891a8662017-08-25 21:53:48 -0700349 CHECK(mReference->constExpr() != nullptr);
Timur Iskhakov7296af12017-08-09 21:52:48 +0000350
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700351 ConstantExpression* expr = mReference->constExpr();
Timur Iskhakov891a8662017-08-25 21:53:48 -0700352 CHECK(expr->isEvaluated());
Timur Iskhakov7296af12017-08-09 21:52:48 +0000353
354 mValueKind = expr->mValueKind;
355 mValue = expr->mValue;
356 mIsEvaluated = true;
Yifan Hong52165692016-08-12 18:06:40 -0700357}
Yifan Hong57886972016-08-17 10:42:15 -0700358
Timur Iskhakov7296af12017-08-09 21:52:48 +0000359std::unique_ptr<ConstantExpression> ConstantExpression::addOne(ScalarType::Kind baseKind) {
360 auto ret = std::make_unique<BinaryConstantExpression>(
361 this, "+", ConstantExpression::One(baseKind).release());
Timur Iskhakov7296af12017-08-09 21:52:48 +0000362 return ret;
Yifan Hongf24fa852016-09-23 11:03:15 -0700363}
364
Timur Iskhakov7296af12017-08-09 21:52:48 +0000365const std::string& ConstantExpression::description() const {
366 CHECK(isEvaluated());
Yifan Hongf24fa852016-09-23 11:03:15 -0700367 return mExpr;
Yifan Hong57886972016-08-17 10:42:15 -0700368}
369
Yifan Hong5706a432016-11-02 09:44:18 -0700370bool ConstantExpression::descriptionIsTrivial() const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000371 CHECK(isEvaluated());
Yifan Hong5706a432016-11-02 09:44:18 -0700372 return mTrivialDescription;
373}
374
Yifan Hongfc610cd2016-09-22 13:34:45 -0700375std::string ConstantExpression::value() const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000376 CHECK(isEvaluated());
Yifan Hongf24fa852016-09-23 11:03:15 -0700377 return rawValue(mValueKind);
378}
379
Yifan Hongc07b2022016-11-08 12:44:24 -0800380std::string ConstantExpression::value(ScalarType::Kind castKind) const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000381 CHECK(isEvaluated());
Yifan Hongc07b2022016-11-08 12:44:24 -0800382 return rawValue(castKind);
383}
384
Yifan Hongf24fa852016-09-23 11:03:15 -0700385std::string ConstantExpression::cppValue() const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000386 CHECK(isEvaluated());
Yifan Hongf24fa852016-09-23 11:03:15 -0700387 return cppValue(mValueKind);
Yifan Hong52165692016-08-12 18:06:40 -0700388}
389
Yifan Hongfc610cd2016-09-22 13:34:45 -0700390std::string ConstantExpression::cppValue(ScalarType::Kind castKind) const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000391 CHECK(isEvaluated());
Yifan Hongf24fa852016-09-23 11:03:15 -0700392 std::string literal(rawValue(castKind));
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700393 // this is a hack to translate
394 // enum x : int64_t { y = 1l << 63 };
395 // into
396 // enum class x : int64_t { y = (int64_t)-9223372036854775808ull };
397 // by adding the explicit cast.
398 // Because 9223372036854775808 is uint64_t, and
399 // -(uint64_t)9223372036854775808 == 9223372036854775808 could not
400 // be narrowed to int64_t.
401 if(castKind == SK(INT64) && (int64_t)mValue == INT64_MIN) {
George Burgess IV4157fa42018-02-17 21:56:56 -0800402 return "static_cast<" +
403 ScalarType(SK(INT64), nullptr /* parent */).getCppStackType() // "int64_t"
404 + ">(" + literal + "ull)";
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700405 }
Yifan Hong57886972016-08-17 10:42:15 -0700406
Yifan Hong2bd3c1f2016-09-22 13:20:05 -0700407 // add suffix if necessary.
408 if(castKind == SK(UINT32) || castKind == SK(UINT64)) literal += "u";
409 if(castKind == SK(UINT64) || castKind == SK(INT64)) literal += "ll";
Yifan Hongfc610cd2016-09-22 13:34:45 -0700410 return literal;
Yifan Hong57886972016-08-17 10:42:15 -0700411}
412
Yifan Hongf24fa852016-09-23 11:03:15 -0700413std::string ConstantExpression::javaValue() const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000414 CHECK(isEvaluated());
Yifan Hongf24fa852016-09-23 11:03:15 -0700415 return javaValue(mValueKind);
Yifan Hong19ca75a2016-08-31 10:20:03 -0700416}
417
Yifan Hongf24fa852016-09-23 11:03:15 -0700418std::string ConstantExpression::javaValue(ScalarType::Kind castKind) const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000419 CHECK(isEvaluated());
Yifan Hongf24fa852016-09-23 11:03:15 -0700420 switch(castKind) {
421 case SK(UINT64): return rawValue(SK(INT64)) + "L";
422 case SK(INT64): return rawValue(SK(INT64)) + "L";
423 case SK(UINT32): return rawValue(SK(INT32));
424 case SK(UINT16): return rawValue(SK(INT16));
425 case SK(UINT8) : return rawValue(SK(INT8));
426 case SK(BOOL) :
George Burgess IV4157fa42018-02-17 21:56:56 -0800427 return this->cast<bool>() ? "true" : "false";
Yifan Hongf24fa852016-09-23 11:03:15 -0700428 default: break;
429 }
430 return rawValue(castKind);
431}
432
433std::string ConstantExpression::rawValue(ScalarType::Kind castKind) const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000434 CHECK(isEvaluated());
Yifan Hong57886972016-08-17 10:42:15 -0700435
Yifan Hongfc610cd2016-09-22 13:34:45 -0700436#define CASE_STR(__type__) return std::to_string(this->cast<__type__>());
Yifan Hong57886972016-08-17 10:42:15 -0700437
Yifan Hongf24fa852016-09-23 11:03:15 -0700438 SWITCH_KIND(castKind, CASE_STR, SHOULD_NOT_REACH(); return 0; );
Yifan Hong57886972016-08-17 10:42:15 -0700439}
440
Yifan Hong19ca75a2016-08-31 10:20:03 -0700441template<typename T>
442T ConstantExpression::cast() const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000443 CHECK(isEvaluated());
Yifan Hong57886972016-08-17 10:42:15 -0700444
Yifan Hong19ca75a2016-08-31 10:20:03 -0700445#define CASE_CAST_T(__type__) return static_cast<T>(static_cast<__type__>(mValue));
Yifan Hong57886972016-08-17 10:42:15 -0700446
Yifan Hongf24fa852016-09-23 11:03:15 -0700447 SWITCH_KIND(mValueKind, CASE_CAST_T, SHOULD_NOT_REACH(); return 0; );
Yifan Hong57886972016-08-17 10:42:15 -0700448}
449
Yifan Honge77ca132016-09-27 10:49:05 -0700450size_t ConstantExpression::castSizeT() const {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000451 CHECK(isEvaluated());
Yifan Honge77ca132016-09-27 10:49:05 -0700452 return this->cast<size_t>();
453}
454
Timur Iskhakova6d33882017-09-01 13:02:09 -0700455bool ConstantExpression::isReferenceConstantExpression() const {
456 return false;
457}
458
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700459std::vector<ConstantExpression*> ConstantExpression::getConstantExpressions() {
460 const auto& constRet = static_cast<const ConstantExpression*>(this)->getConstantExpressions();
461 std::vector<ConstantExpression*> ret(constRet.size());
462 std::transform(constRet.begin(), constRet.end(), ret.begin(),
463 [](const auto* ce) { return const_cast<ConstantExpression*>(ce); });
464 return ret;
465}
466
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700467std::vector<Reference<LocalIdentifier>*> ConstantExpression::getReferences() {
468 const auto& constRet = static_cast<const ConstantExpression*>(this)->getReferences();
469 std::vector<Reference<LocalIdentifier>*> ret(constRet.size());
470 std::transform(constRet.begin(), constRet.end(), ret.begin(),
471 [](const auto* ce) { return const_cast<Reference<LocalIdentifier>*>(ce); });
472 return ret;
473}
474
475std::vector<const Reference<LocalIdentifier>*> ConstantExpression::getReferences() const {
476 return {};
477}
478
Timur Iskhakov891a8662017-08-25 21:53:48 -0700479status_t ConstantExpression::recursivePass(const std::function<status_t(ConstantExpression*)>& func,
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700480 std::unordered_set<const ConstantExpression*>* visited,
481 bool processBeforeDependencies) {
Timur Iskhakov35930c42017-08-28 18:49:54 -0700482 if (mIsPostParseCompleted) return OK;
483
Timur Iskhakov891a8662017-08-25 21:53:48 -0700484 if (visited->find(this) != visited->end()) return OK;
485 visited->insert(this);
486
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700487 if (processBeforeDependencies) {
488 status_t err = func(this);
489 if (err != OK) return err;
490 }
491
Timur Iskhakov891a8662017-08-25 21:53:48 -0700492 for (auto* nextCE : getConstantExpressions()) {
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700493 status_t err = nextCE->recursivePass(func, visited, processBeforeDependencies);
Timur Iskhakov891a8662017-08-25 21:53:48 -0700494 if (err != OK) return err;
495 }
496
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700497 for (auto* nextRef : getReferences()) {
498 auto* nextCE = nextRef->shallowGet()->constExpr();
499 CHECK(nextCE != nullptr) << "Local identifier is not a constant expression";
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700500 status_t err = nextCE->recursivePass(func, visited, processBeforeDependencies);
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700501 if (err != OK) return err;
502 }
503
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700504 if (!processBeforeDependencies) {
505 status_t err = func(this);
506 if (err != OK) return err;
507 }
Timur Iskhakov891a8662017-08-25 21:53:48 -0700508
509 return OK;
510}
511
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700512status_t ConstantExpression::recursivePass(
513 const std::function<status_t(const ConstantExpression*)>& func,
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700514 std::unordered_set<const ConstantExpression*>* visited, bool processBeforeDependencies) const {
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700515 if (mIsPostParseCompleted) return OK;
516
517 if (visited->find(this) != visited->end()) return OK;
518 visited->insert(this);
519
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700520 if (processBeforeDependencies) {
521 status_t err = func(this);
522 if (err != OK) return err;
523 }
524
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700525 for (const auto* nextCE : getConstantExpressions()) {
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700526 status_t err = nextCE->recursivePass(func, visited, processBeforeDependencies);
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700527 if (err != OK) return err;
528 }
529
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700530 for (const auto* nextRef : getReferences()) {
531 const auto* nextCE = nextRef->shallowGet()->constExpr();
532 CHECK(nextCE != nullptr) << "Local identifier is not a constant expression";
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700533 status_t err = nextCE->recursivePass(func, visited, processBeforeDependencies);
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700534 if (err != OK) return err;
535 }
536
Timur Iskhakov82c048e2017-09-09 01:20:53 -0700537 if (!processBeforeDependencies) {
538 status_t err = func(this);
539 if (err != OK) return err;
540 }
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700541
542 return OK;
543}
544
Timur Iskhakova6d33882017-09-01 13:02:09 -0700545ConstantExpression::CheckAcyclicStatus::CheckAcyclicStatus(
546 status_t status, const ConstantExpression* cycleEnd,
547 const ReferenceConstantExpression* lastReference)
548 : status(status), cycleEnd(cycleEnd), lastReference(lastReference) {
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700549 CHECK(cycleEnd == nullptr || status != OK);
Timur Iskhakova6d33882017-09-01 13:02:09 -0700550 CHECK((cycleEnd == nullptr) == (lastReference == nullptr));
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700551}
552
553ConstantExpression::CheckAcyclicStatus ConstantExpression::checkAcyclic(
554 std::unordered_set<const ConstantExpression*>* visited,
555 std::unordered_set<const ConstantExpression*>* stack) const {
556 if (stack->find(this) != stack->end()) {
Timur Iskhakova6d33882017-09-01 13:02:09 -0700557 CHECK(isReferenceConstantExpression())
558 << "Only reference constant expression could be the cycle end";
559
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700560 std::cerr << "ERROR: Cyclic declaration:\n";
Timur Iskhakova6d33882017-09-01 13:02:09 -0700561 return CheckAcyclicStatus(UNKNOWN_ERROR, this,
562 static_cast<const ReferenceConstantExpression*>(this));
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700563 }
564
565 if (visited->find(this) != visited->end()) return CheckAcyclicStatus(OK);
566 visited->insert(this);
567 stack->insert(this);
568
569 for (const auto* nextCE : getConstantExpressions()) {
570 auto err = nextCE->checkAcyclic(visited, stack);
571 if (err.status != OK) {
572 return err;
573 }
574 }
575
576 for (const auto* nextRef : getReferences()) {
577 const auto* nextCE = nextRef->shallowGet()->constExpr();
578 CHECK(nextCE != nullptr) << "Local identifier is not a constant expression";
579 auto err = nextCE->checkAcyclic(visited, stack);
580
581 if (err.status != OK) {
582 if (err.cycleEnd == nullptr) return err;
583
584 // Only ReferenceConstantExpression has references,
Timur Iskhakova6d33882017-09-01 13:02:09 -0700585 CHECK(isReferenceConstantExpression())
586 << "Only reference constant expression could have refereneces";
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700587
Timur Iskhakova6d33882017-09-01 13:02:09 -0700588 // mExpr is defined explicitly before evaluation
589 std::cerr << " '" << err.lastReference->mExpr << "' in '" << mExpr << "' at "
590 << nextRef->location() << "\n";
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700591
592 if (err.cycleEnd == this) {
593 return CheckAcyclicStatus(err.status);
594 }
Timur Iskhakova6d33882017-09-01 13:02:09 -0700595 return CheckAcyclicStatus(err.status, err.cycleEnd,
596 static_cast<const ReferenceConstantExpression*>(this));
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700597 }
598 }
599
600 CHECK(stack->find(this) != stack->end());
601 stack->erase(this);
602 return CheckAcyclicStatus(OK);
603}
604
Timur Iskhakov35930c42017-08-28 18:49:54 -0700605void ConstantExpression::setPostParseCompleted() {
606 CHECK(!mIsPostParseCompleted);
607 mIsPostParseCompleted = true;
608}
609
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700610std::vector<const ConstantExpression*> LiteralConstantExpression::getConstantExpressions() const {
Timur Iskhakov891a8662017-08-25 21:53:48 -0700611 return {};
612}
613
Timur Iskhakov7296af12017-08-09 21:52:48 +0000614UnaryConstantExpression::UnaryConstantExpression(const std::string& op, ConstantExpression* value)
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700615 : mUnary(value), mOp(op) {}
Timur Iskhakov7296af12017-08-09 21:52:48 +0000616
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700617std::vector<const ConstantExpression*> UnaryConstantExpression::getConstantExpressions() const {
Timur Iskhakov891a8662017-08-25 21:53:48 -0700618 return {mUnary};
619}
620
Timur Iskhakov7296af12017-08-09 21:52:48 +0000621BinaryConstantExpression::BinaryConstantExpression(ConstantExpression* lval, const std::string& op,
622 ConstantExpression* rval)
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700623 : mLval(lval), mRval(rval), mOp(op) {}
Timur Iskhakov7296af12017-08-09 21:52:48 +0000624
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700625std::vector<const ConstantExpression*> BinaryConstantExpression::getConstantExpressions() const {
Timur Iskhakov891a8662017-08-25 21:53:48 -0700626 return {mLval, mRval};
627}
628
Timur Iskhakov7296af12017-08-09 21:52:48 +0000629TernaryConstantExpression::TernaryConstantExpression(ConstantExpression* cond,
630 ConstantExpression* trueVal,
631 ConstantExpression* falseVal)
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700632 : mCond(cond), mTrueVal(trueVal), mFalseVal(falseVal) {}
Timur Iskhakov7296af12017-08-09 21:52:48 +0000633
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700634std::vector<const ConstantExpression*> TernaryConstantExpression::getConstantExpressions() const {
Timur Iskhakov891a8662017-08-25 21:53:48 -0700635 return {mCond, mTrueVal, mFalseVal};
636}
637
Timur Iskhakov7296af12017-08-09 21:52:48 +0000638ReferenceConstantExpression::ReferenceConstantExpression(const Reference<LocalIdentifier>& value,
639 const std::string& expr)
Timur Iskhakovd27580c2017-08-09 20:14:52 -0700640 : mReference(value) {
Timur Iskhakov7296af12017-08-09 21:52:48 +0000641 mExpr = expr;
Timur Iskhakov505e5612017-08-27 18:26:48 -0700642 mTrivialDescription = mExpr.empty();
Timur Iskhakov7296af12017-08-09 21:52:48 +0000643}
644
Timur Iskhakova6d33882017-09-01 13:02:09 -0700645bool ReferenceConstantExpression::isReferenceConstantExpression() const {
646 return true;
647}
648
Timur Iskhakovb58f4182017-08-29 15:19:24 -0700649std::vector<const ConstantExpression*> ReferenceConstantExpression::getConstantExpressions() const {
Timur Iskhakov77dd65c2017-08-31 22:46:56 -0700650 // Returns reference instead
651 return {};
652}
653
654std::vector<const Reference<LocalIdentifier>*> ReferenceConstantExpression::getReferences() const {
655 return {&mReference};
Timur Iskhakov891a8662017-08-25 21:53:48 -0700656}
657
Yifan Hong57886972016-08-17 10:42:15 -0700658/*
659
660Evaluating expressions in HIDL language
661
662The following rules are mostly like that in:
663http://en.cppreference.com/w/cpp/language/operator_arithmetic
664http://en.cppreference.com/w/cpp/language/operator_logical
665http://en.cppreference.com/w/cpp/language/operator_comparison
666http://en.cppreference.com/w/cpp/language/operator_other
667
668The type of literal is the first type which the value
669can fit from the list of types depending on the suffix and bases.
670
671suffix decimal bases hexadecimal bases
672no suffix int32_t int32_t
673 int64_t uint32_t
674 int64_t
675 uint64_t
676
677u/U uint32_t (same as left)
678 uint64_t
679
680l/L int64_t int64_t
681
682ul/UL/uL/Ul uint64_t uint64_t
683
684
685Note: There are no negative integer literals.
686 -1 is the unary minus applied to 1.
687
688Unary arithmetic and bitwise operators (~ + -):
689 don't change the type of the argument.
690 (so -1u = -(1u) has type uint32_t)
691
692Binary arithmetic and bitwise operators (except shifts) (+ - * / % & | ^):
6931. Integral promotion is first applied on both sides.
6942. If both operands have the same type, no promotion is necessary.
6953. Usual arithmetic conversions.
696
697Integral promotion: if an operand is of a type with less than 32 bits,
698(including bool), it is promoted to int32_t.
699
700Usual arithmetic conversions:
7011. If operands are both signed or both unsigned, lesser conversion rank is
702 converted to greater conversion rank.
7032. Otherwise, if unsigned's rank >= signed's rank, -> unsigned's type
7043. Otherwise, if signed's type can hold all values in unsigned's type,
705 -> signed's type
7064. Otherwise, both converted to the unsigned counterpart of the signed operand's
707 type.
708rank: bool < int8_t < int16_t < int32_t < int64_t
709
710
711Shift operators (<< >>):
7121. Integral promotion is applied on both sides.
7132. For unsigned a, a << b discards bits that shifts out.
714 For signed non-negative a, a << b is legal if no bits shifts out, otherwise error.
715 For signed negative a, a << b gives error.
7163. For unsigned and signed non-negative a, a >> b discards bits that shifts out.
717 For signed negative a, a >> b discards bits that shifts out, and the signed
718 bit gets extended. ("arithmetic right shift")
7194. Shifting with negative number of bits is undefined. (Currently, the
720 parser will shift into the other direction. This behavior may change.)
7215. Shifting with number of bits exceeding the width of the type is undefined.
722 (Currently, 1 << 32 == 1. This behavior may change.)
723
724Logical operators (!, &&, ||):
7251. Convert first operand to bool. (true if non-zero, false otherwise)
7262. If short-circuited, return the result as type bool, value 1 or 0.
7273. Otherwise, convert second operand to bool, evaluate the result, and return
728 the result in the same fashion.
729
730Arithmetic comparison operators (< > <= >= == !=):
7311. Promote operands in the same way as binary arithmetic and bitwise operators.
732 (Integral promotion + Usual arithmetic conversions)
7332. Return type bool, value 0 or 1 the same way as logical operators.
734
735Ternary conditional operator (?:):
7361. Evaluate the conditional and evaluate the operands.
7372. Return type of expression is the type under usual arithmetic conversions on
738 the second and third operand. (No integral promotions necessary.)
739
740*/
741
Yifan Hong52165692016-08-12 18:06:40 -0700742} // namespace android
743