blob: a3d1a01c4764a5d1a2490403f8565321d7827911 [file] [log] [blame]
Will McVickerefd970d2019-09-25 15:28:30 -07001/*
2 * Copyright (C) 2019, 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
Will McVickerefd970d2019-09-25 15:28:30 -070017#include "aidl_language.h"
Steven Moreland4bcb05c2019-11-27 18:57:47 -080018#include "aidl_typenames.h"
Will McVickerefd970d2019-09-25 15:28:30 -070019#include "logging.h"
20
21#include <stdlib.h>
22#include <algorithm>
23#include <iostream>
Steven Moreland0521bf32020-09-09 22:44:07 +000024#include <limits>
Will McVickerefd970d2019-09-25 15:28:30 -070025#include <memory>
26
27#include <android-base/parsedouble.h>
28#include <android-base/parseint.h>
29#include <android-base/strings.h>
30
Will McVickerd7d18df2019-09-12 13:40:50 -070031using android::base::ConsumeSuffix;
Steven Morelandcef22662020-07-08 20:54:28 +000032using android::base::EndsWith;
Will McVickerefd970d2019-09-25 15:28:30 -070033using android::base::Join;
Steven Morelandcef22662020-07-08 20:54:28 +000034using android::base::StartsWith;
Will McVickerefd970d2019-09-25 15:28:30 -070035using std::string;
36using std::unique_ptr;
37using std::vector;
38
Steven Moreland0521bf32020-09-09 22:44:07 +000039template <typename T>
Devin Moorecff93692020-09-24 10:39:57 -070040constexpr int CLZ(T x) {
Devin Mooree2de9e42020-10-02 08:55:08 -070041 // __builtin_clz(0) is undefined
42 if (x == 0) return sizeof(T) * 8;
Devin Moorecff93692020-09-24 10:39:57 -070043 return (sizeof(T) == sizeof(uint64_t)) ? __builtin_clzl(x) : __builtin_clz(x);
44}
45
46template <typename T>
Steven Moreland0521bf32020-09-09 22:44:07 +000047class OverflowGuard {
48 public:
49 OverflowGuard(T value) : mValue(value) {}
50 bool Overflowed() const { return mOverflowed; }
51
52 T operator+() { return +mValue; }
53 T operator-() {
54 if (isMin()) {
55 mOverflowed = true;
56 return 0;
57 }
58 return -mValue;
59 }
60 T operator!() { return !mValue; }
61 T operator~() { return ~mValue; }
62
63 T operator+(T o) {
64 T out;
65 mOverflowed = __builtin_add_overflow(mValue, o, &out);
66 return out;
67 }
68 T operator-(T o) {
69 T out;
70 mOverflowed = __builtin_sub_overflow(mValue, o, &out);
71 return out;
72 }
73 T operator*(T o) {
74 T out;
75#ifdef _WIN32
76 // ___mulodi4 not on windows https://bugs.llvm.org/show_bug.cgi?id=46669
77 // we should still get an error here from ubsan, but the nice error
78 // is needed on linux for aidl_parser_fuzzer, where we are more
79 // concerned about overflows elsewhere in the compiler in addition to
80 // those in interfaces.
81 out = mValue * o;
82#else
83 mOverflowed = __builtin_mul_overflow(mValue, o, &out);
84#endif
85 return out;
86 }
87 T operator/(T o) {
88 if (o == 0 || (isMin() && o == -1)) {
89 mOverflowed = true;
90 return 0;
91 }
92 return mValue / o;
93 }
94 T operator%(T o) {
95 if (o == 0 || (isMin() && o == -1)) {
96 mOverflowed = true;
97 return 0;
98 }
99 return mValue % o;
100 }
101 T operator|(T o) { return mValue | o; }
102 T operator^(T o) { return mValue ^ o; }
103 T operator&(T o) { return mValue & o; }
104 T operator<(T o) { return mValue < o; }
105 T operator>(T o) { return mValue > o; }
106 T operator<=(T o) { return mValue <= o; }
107 T operator>=(T o) { return mValue >= o; }
108 T operator==(T o) { return mValue == o; }
109 T operator!=(T o) { return mValue != o; }
110 T operator>>(T o) {
Devin Moorea9e64de2020-09-29 11:29:42 -0700111 if (o < 0 || o >= static_cast<T>(sizeof(T) * 8) || mValue < 0) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000112 mOverflowed = true;
113 return 0;
114 }
115 return mValue >> o;
116 }
117 T operator<<(T o) {
Devin Mooree2de9e42020-10-02 08:55:08 -0700118 if (o < 0 || mValue < 0 || o > CLZ(mValue) || o >= static_cast<T>(sizeof(T) * 8)) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000119 mOverflowed = true;
120 return 0;
121 }
122 return mValue << o;
123 }
124 T operator||(T o) { return mValue || o; }
125 T operator&&(T o) { return mValue && o; }
126
127 private:
128 bool isMin() { return mValue == std::numeric_limits<T>::min(); }
129
130 T mValue;
131 bool mOverflowed = false;
132};
133
134template <typename T>
135bool processGuard(const OverflowGuard<T>& guard, const AidlConstantValue& context) {
136 if (guard.Overflowed()) {
137 AIDL_ERROR(context) << "Constant expression computation overflows.";
138 return false;
139 }
140 return true;
141}
142
143// TODO: factor out all these macros
Steven Moreland21780812020-09-11 01:29:45 +0000144#define SHOULD_NOT_REACH() AIDL_FATAL(AIDL_LOCATION_HERE) << "Should not reach."
Will McVickerd7d18df2019-09-12 13:40:50 -0700145#define OPEQ(__y__) (string(op_) == string(__y__))
Steven Moreland0521bf32020-09-09 22:44:07 +0000146#define COMPUTE_UNARY(T, __op__) \
147 if (op == string(#__op__)) { \
148 OverflowGuard<T> guard(val); \
149 *out = __op__ guard; \
150 return processGuard(guard, context); \
Steven Morelande1ff67e2020-07-16 23:22:36 +0000151 }
Steven Moreland0521bf32020-09-09 22:44:07 +0000152#define COMPUTE_BINARY(T, __op__) \
153 if (op == string(#__op__)) { \
154 OverflowGuard<T> guard(lval); \
155 *out = guard __op__ rval; \
156 return processGuard(guard, context); \
Steven Morelande1ff67e2020-07-16 23:22:36 +0000157 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700158#define OP_IS_BIN_ARITHMETIC (OPEQ("+") || OPEQ("-") || OPEQ("*") || OPEQ("/") || OPEQ("%"))
159#define OP_IS_BIN_BITFLIP (OPEQ("|") || OPEQ("^") || OPEQ("&"))
160#define OP_IS_BIN_COMP \
161 (OPEQ("<") || OPEQ(">") || OPEQ("<=") || OPEQ(">=") || OPEQ("==") || OPEQ("!="))
162#define OP_IS_BIN_SHIFT (OPEQ(">>") || OPEQ("<<"))
163#define OP_IS_BIN_LOGICAL (OPEQ("||") || OPEQ("&&"))
164
165// NOLINT to suppress missing parentheses warnings about __def__.
166#define SWITCH_KIND(__cond__, __action__, __def__) \
167 switch (__cond__) { \
168 case Type::BOOLEAN: \
169 __action__(bool); \
170 case Type::INT8: \
171 __action__(int8_t); \
172 case Type::INT32: \
173 __action__(int32_t); \
174 case Type::INT64: \
175 __action__(int64_t); \
176 default: \
177 __def__; /* NOLINT */ \
178 }
179
180template <class T>
Steven Morelande1ff67e2020-07-16 23:22:36 +0000181bool handleUnary(const AidlConstantValue& context, const string& op, T val, int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000182 COMPUTE_UNARY(T, +)
183 COMPUTE_UNARY(T, -)
184 COMPUTE_UNARY(T, !)
185 COMPUTE_UNARY(T, ~)
Steven Moreland720a3cc2020-07-16 23:44:59 +0000186 AIDL_FATAL(context) << "Could not handleUnary for " << op << " " << val;
187 return false;
188}
189template <>
190bool handleUnary<bool>(const AidlConstantValue& context, const string& op, bool val, int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000191 COMPUTE_UNARY(bool, +)
192 COMPUTE_UNARY(bool, -)
193 COMPUTE_UNARY(bool, !)
Yifan Hongf17e3a72020-02-20 17:34:58 -0800194
Steven Moreland720a3cc2020-07-16 23:44:59 +0000195 if (op == "~") {
196 AIDL_ERROR(context) << "Bitwise negation of a boolean expression is always true.";
197 return false;
198 }
Steven Morelande1ff67e2020-07-16 23:22:36 +0000199 AIDL_FATAL(context) << "Could not handleUnary for " << op << " " << val;
200 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700201}
202
203template <class T>
Steven Morelande1ff67e2020-07-16 23:22:36 +0000204bool handleBinaryCommon(const AidlConstantValue& context, T lval, const string& op, T rval,
205 int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000206 COMPUTE_BINARY(T, +)
207 COMPUTE_BINARY(T, -)
208 COMPUTE_BINARY(T, *)
209 COMPUTE_BINARY(T, /)
210 COMPUTE_BINARY(T, %)
211 COMPUTE_BINARY(T, |)
212 COMPUTE_BINARY(T, ^)
213 COMPUTE_BINARY(T, &)
Will McVickerd7d18df2019-09-12 13:40:50 -0700214 // comparison operators: return 0 or 1 by nature.
Steven Moreland0521bf32020-09-09 22:44:07 +0000215 COMPUTE_BINARY(T, ==)
216 COMPUTE_BINARY(T, !=)
217 COMPUTE_BINARY(T, <)
218 COMPUTE_BINARY(T, >)
219 COMPUTE_BINARY(T, <=)
220 COMPUTE_BINARY(T, >=)
Steven Morelande1ff67e2020-07-16 23:22:36 +0000221
222 AIDL_FATAL(context) << "Could not handleBinaryCommon for " << lval << " " << op << " " << rval;
223 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700224}
225
226template <class T>
Devin Moore04823022020-09-11 10:43:35 -0700227bool handleShift(const AidlConstantValue& context, T lval, const string& op, T rval, int64_t* out) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700228 // just cast rval to int64_t and it should fit.
Steven Moreland0521bf32020-09-09 22:44:07 +0000229 COMPUTE_BINARY(T, >>)
230 COMPUTE_BINARY(T, <<)
Steven Morelande1ff67e2020-07-16 23:22:36 +0000231
232 AIDL_FATAL(context) << "Could not handleShift for " << lval << " " << op << " " << rval;
233 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700234}
235
Steven Morelande1ff67e2020-07-16 23:22:36 +0000236bool handleLogical(const AidlConstantValue& context, bool lval, const string& op, bool rval,
237 int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000238 COMPUTE_BINARY(bool, ||);
239 COMPUTE_BINARY(bool, &&);
Steven Morelande1ff67e2020-07-16 23:22:36 +0000240
241 AIDL_FATAL(context) << "Could not handleLogical for " << lval << " " << op << " " << rval;
Will McVickerd7d18df2019-09-12 13:40:50 -0700242 return false;
243}
244
Will McVickerefd970d2019-09-25 15:28:30 -0700245static bool isValidLiteralChar(char c) {
246 return !(c <= 0x1f || // control characters are < 0x20
247 c >= 0x7f || // DEL is 0x7f
248 c == '\\'); // Disallow backslashes for future proofing.
249}
250
Will McVickerd7d18df2019-09-12 13:40:50 -0700251bool AidlUnaryConstExpression::IsCompatibleType(Type type, const string& op) {
252 // Verify the unary type here
253 switch (type) {
254 case Type::BOOLEAN: // fall-through
255 case Type::INT8: // fall-through
256 case Type::INT32: // fall-through
257 case Type::INT64:
258 return true;
259 case Type::FLOATING:
260 return (op == "+" || op == "-");
261 default:
262 return false;
263 }
264}
265
266bool AidlBinaryConstExpression::AreCompatibleTypes(Type t1, Type t2) {
267 switch (t1) {
268 case Type::STRING:
269 if (t2 == Type::STRING) {
270 return true;
271 }
272 break;
273 case Type::BOOLEAN: // fall-through
274 case Type::INT8: // fall-through
275 case Type::INT32: // fall-through
276 case Type::INT64:
277 switch (t2) {
278 case Type::BOOLEAN: // fall-through
279 case Type::INT8: // fall-through
280 case Type::INT32: // fall-through
281 case Type::INT64:
282 return true;
283 break;
284 default:
285 break;
286 }
287 break;
288 default:
289 break;
290 }
291
292 return false;
293}
294
295// Returns the promoted kind for both operands
296AidlConstantValue::Type AidlBinaryConstExpression::UsualArithmeticConversion(Type left,
297 Type right) {
298 // These are handled as special cases
Steven Moreland21780812020-09-11 01:29:45 +0000299 AIDL_FATAL_IF(left == Type::STRING || right == Type::STRING, AIDL_LOCATION_HERE);
300 AIDL_FATAL_IF(left == Type::FLOATING || right == Type::FLOATING, AIDL_LOCATION_HERE);
Will McVickerd7d18df2019-09-12 13:40:50 -0700301
302 // Kinds in concern: bool, (u)int[8|32|64]
303 if (left == right) return left; // easy case
304 if (left == Type::BOOLEAN) return right;
305 if (right == Type::BOOLEAN) return left;
306
307 return left < right ? right : left;
308}
309
310// Returns the promoted integral type where INT32 is the smallest type
311AidlConstantValue::Type AidlBinaryConstExpression::IntegralPromotion(Type in) {
312 return (Type::INT32 < in) ? in : Type::INT32;
313}
314
315template <typename T>
316T AidlConstantValue::cast() const {
Steven Moreland21780812020-09-11 01:29:45 +0000317 AIDL_FATAL_IF(!is_evaluated_, this);
Will McVickerd7d18df2019-09-12 13:40:50 -0700318
319#define CASE_CAST_T(__type__) return static_cast<T>(static_cast<__type__>(final_value_));
320
321 SWITCH_KIND(final_type_, CASE_CAST_T, SHOULD_NOT_REACH(); return 0;);
322}
323
Steven Moreland541788d2020-05-21 22:05:52 +0000324AidlConstantValue* AidlConstantValue::Default(const AidlTypeSpecifier& specifier) {
325 AidlLocation location = specifier.GetLocation();
326
327 // allocation of int[0] is a bit wasteful in Java
328 if (specifier.IsArray()) {
329 return nullptr;
330 }
331
332 const std::string name = specifier.GetName();
333 if (name == "boolean") {
334 return Boolean(location, false);
335 }
336 if (name == "byte" || name == "int" || name == "long") {
337 return Integral(location, "0");
338 }
339 if (name == "float") {
340 return Floating(location, "0.0f");
341 }
342 if (name == "double") {
343 return Floating(location, "0.0");
344 }
345 return nullptr;
346}
347
Will McVickerefd970d2019-09-25 15:28:30 -0700348AidlConstantValue* AidlConstantValue::Boolean(const AidlLocation& location, bool value) {
349 return new AidlConstantValue(location, Type::BOOLEAN, value ? "true" : "false");
350}
351
352AidlConstantValue* AidlConstantValue::Character(const AidlLocation& location, char value) {
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800353 const std::string explicit_value = string("'") + value + "'";
Will McVickerefd970d2019-09-25 15:28:30 -0700354 if (!isValidLiteralChar(value)) {
355 AIDL_ERROR(location) << "Invalid character literal " << value;
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800356 return new AidlConstantValue(location, Type::ERROR, explicit_value);
Will McVickerefd970d2019-09-25 15:28:30 -0700357 }
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800358 return new AidlConstantValue(location, Type::CHARACTER, explicit_value);
Will McVickerefd970d2019-09-25 15:28:30 -0700359}
360
361AidlConstantValue* AidlConstantValue::Floating(const AidlLocation& location,
362 const std::string& value) {
363 return new AidlConstantValue(location, Type::FLOATING, value);
364}
365
Will McVickerd7d18df2019-09-12 13:40:50 -0700366bool AidlConstantValue::IsHex(const string& value) {
Steven Morelandcef22662020-07-08 20:54:28 +0000367 return StartsWith(value, "0x") || StartsWith(value, "0X");
Will McVickerefd970d2019-09-25 15:28:30 -0700368}
369
Will McVickerd7d18df2019-09-12 13:40:50 -0700370bool AidlConstantValue::ParseIntegral(const string& value, int64_t* parsed_value,
371 Type* parsed_type) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700372 if (parsed_value == nullptr || parsed_type == nullptr) {
373 return false;
374 }
375
Steven Morelandcef22662020-07-08 20:54:28 +0000376 const bool isLong = EndsWith(value, 'l') || EndsWith(value, 'L');
377 const std::string value_substr = isLong ? value.substr(0, value.size() - 1) : value;
Will McVickerd7d18df2019-09-12 13:40:50 -0700378
Steven Morelandcef22662020-07-08 20:54:28 +0000379 if (IsHex(value)) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700380 // AIDL considers 'const int foo = 0xffffffff' as -1, but if we want to
381 // handle that when computing constant expressions, then we need to
382 // represent 0xffffffff as a uint32_t. However, AIDL only has signed types;
383 // so we parse as an unsigned int when possible and then cast to a signed
384 // int. One example of this is in ICameraService.aidl where a constant int
385 // is used for bit manipulations which ideally should be handled with an
386 // unsigned int.
Steven Morelandcef22662020-07-08 20:54:28 +0000387 //
388 // Note, for historical consistency, we need to consider small hex values
389 // as an integral type. Recognizing them as INT8 could break some files,
390 // even though it would simplify this code.
391 if (uint32_t rawValue32;
392 !isLong && android::base::ParseUint<uint32_t>(value_substr, &rawValue32)) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700393 *parsed_value = static_cast<int32_t>(rawValue32);
394 *parsed_type = Type::INT32;
Steven Morelandcef22662020-07-08 20:54:28 +0000395 } else if (uint64_t rawValue64; android::base::ParseUint<uint64_t>(value_substr, &rawValue64)) {
396 *parsed_value = static_cast<int64_t>(rawValue64);
Will McVickerd7d18df2019-09-12 13:40:50 -0700397 *parsed_type = Type::INT64;
Steven Morelandcef22662020-07-08 20:54:28 +0000398 } else {
399 *parsed_value = 0;
400 *parsed_type = Type::ERROR;
401 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700402 }
403 return true;
404 }
405
Steven Morelandcef22662020-07-08 20:54:28 +0000406 if (!android::base::ParseInt<int64_t>(value_substr, parsed_value)) {
407 *parsed_value = 0;
Will McVickerd7d18df2019-09-12 13:40:50 -0700408 *parsed_type = Type::ERROR;
409 return false;
410 }
411
Steven Morelandcef22662020-07-08 20:54:28 +0000412 if (isLong) {
413 *parsed_type = Type::INT64;
414 } else {
Will McVickerd7d18df2019-09-12 13:40:50 -0700415 // guess literal type.
416 if (*parsed_value <= INT8_MAX && *parsed_value >= INT8_MIN) {
417 *parsed_type = Type::INT8;
418 } else if (*parsed_value <= INT32_MAX && *parsed_value >= INT32_MIN) {
419 *parsed_type = Type::INT32;
420 } else {
421 *parsed_type = Type::INT64;
422 }
423 }
424 return true;
425}
426
427AidlConstantValue* AidlConstantValue::Integral(const AidlLocation& location, const string& value) {
Steven Moreland21780812020-09-11 01:29:45 +0000428 AIDL_FATAL_IF(value.empty(), location);
Will McVickerd7d18df2019-09-12 13:40:50 -0700429
430 Type parsed_type;
431 int64_t parsed_value = 0;
432 bool success = ParseIntegral(value, &parsed_value, &parsed_type);
433 if (!success) {
434 return nullptr;
435 }
436
437 return new AidlConstantValue(location, parsed_type, parsed_value, value);
Will McVickerefd970d2019-09-25 15:28:30 -0700438}
439
440AidlConstantValue* AidlConstantValue::Array(
Will McVickerd7d18df2019-09-12 13:40:50 -0700441 const AidlLocation& location, std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values) {
Steven Moreland21780812020-09-11 01:29:45 +0000442 AIDL_FATAL_IF(values == nullptr, location);
Will McVickerd7d18df2019-09-12 13:40:50 -0700443 return new AidlConstantValue(location, Type::ARRAY, std::move(values));
Will McVickerefd970d2019-09-25 15:28:30 -0700444}
445
Will McVickerd7d18df2019-09-12 13:40:50 -0700446AidlConstantValue* AidlConstantValue::String(const AidlLocation& location, const string& value) {
Will McVickerefd970d2019-09-25 15:28:30 -0700447 for (size_t i = 0; i < value.length(); ++i) {
448 if (!isValidLiteralChar(value[i])) {
449 AIDL_ERROR(location) << "Found invalid character at index " << i << " in string constant '"
450 << value << "'";
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800451 return new AidlConstantValue(location, Type::ERROR, value);
Will McVickerefd970d2019-09-25 15:28:30 -0700452 }
453 }
454
455 return new AidlConstantValue(location, Type::STRING, value);
456}
457
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700458AidlConstantValue* AidlConstantValue::ShallowIntegralCopy(const AidlConstantValue& other) {
Daniel Norman3cce7cd2020-02-07 13:25:12 -0800459 // TODO(b/141313220) Perform a full copy instead of parsing+unparsing
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700460 AidlTypeSpecifier type = AidlTypeSpecifier(AIDL_LOCATION_HERE, "long", false, nullptr, "");
Steven Moreland65606612019-11-10 21:21:25 -0800461 // TODO(b/142722772) CheckValid() should be called before ValueString()
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800462 if (!other.CheckValid() || !other.evaluate(type)) {
Steven Moreland59e53e42019-11-26 20:38:08 -0800463 AIDL_ERROR(other) << "Failed to parse expression as integer: " << other.value_;
464 return nullptr;
465 }
466 const std::string& value = other.ValueString(type, AidlConstantValueDecorator);
467 if (value.empty()) {
468 return nullptr; // error already logged
Daniel Normanb28684e2019-10-17 15:31:39 -0700469 }
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700470
Steven Moreland59e53e42019-11-26 20:38:08 -0800471 AidlConstantValue* result = Integral(AIDL_LOCATION_HERE, value);
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700472 if (result == nullptr) {
473 AIDL_FATAL(other) << "Unable to perform ShallowIntegralCopy.";
474 }
475 return result;
Daniel Normanb28684e2019-10-17 15:31:39 -0700476}
477
Will McVickerd7d18df2019-09-12 13:40:50 -0700478string AidlConstantValue::ValueString(const AidlTypeSpecifier& type,
479 const ConstantValueDecorator& decorator) const {
Will McVickerefd970d2019-09-25 15:28:30 -0700480 if (type.IsGeneric()) {
481 AIDL_ERROR(type) << "Generic type cannot be specified with a constant literal.";
482 return "";
483 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700484 if (!is_evaluated_) {
485 // TODO(b/142722772) CheckValid() should be called before ValueString()
486 bool success = CheckValid();
487 success &= evaluate(type);
488 if (!success) {
489 // the detailed error message shall be printed in evaluate
490 return "";
491 }
Will McVickerefd970d2019-09-25 15:28:30 -0700492 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700493 if (!is_valid_) {
494 AIDL_ERROR(this) << "Invalid constant value: " + value_;
495 return "";
496 }
497 const string& type_string = type.GetName();
498 int err = 0;
Will McVickerefd970d2019-09-25 15:28:30 -0700499
Will McVickerd7d18df2019-09-12 13:40:50 -0700500 switch (final_type_) {
501 case Type::CHARACTER:
502 if (type_string == "char") {
503 return decorator(type, final_string_value_);
504 }
505 err = -1;
506 break;
507 case Type::STRING:
508 if (type_string == "String") {
509 return decorator(type, final_string_value_);
510 }
511 err = -1;
512 break;
513 case Type::BOOLEAN: // fall-through
514 case Type::INT8: // fall-through
515 case Type::INT32: // fall-through
516 case Type::INT64:
517 if (type_string == "byte") {
518 if (final_value_ > INT8_MAX || final_value_ < INT8_MIN) {
519 err = -1;
520 break;
521 }
522 return decorator(type, std::to_string(static_cast<int8_t>(final_value_)));
523 } else if (type_string == "int") {
524 if (final_value_ > INT32_MAX || final_value_ < INT32_MIN) {
525 err = -1;
526 break;
527 }
528 return decorator(type, std::to_string(static_cast<int32_t>(final_value_)));
529 } else if (type_string == "long") {
530 return decorator(type, std::to_string(final_value_));
531 } else if (type_string == "boolean") {
532 return decorator(type, final_value_ ? "true" : "false");
533 }
534 err = -1;
535 break;
536 case Type::ARRAY: {
537 if (!type.IsArray()) {
538 err = -1;
539 break;
540 }
541 vector<string> value_strings;
542 value_strings.reserve(values_.size());
Will McVickerefd970d2019-09-25 15:28:30 -0700543 bool success = true;
Will McVickerd7d18df2019-09-12 13:40:50 -0700544
Will McVickerefd970d2019-09-25 15:28:30 -0700545 for (const auto& value : values_) {
546 const AidlTypeSpecifier& array_base = type.ArrayBase();
Will McVickerd7d18df2019-09-12 13:40:50 -0700547 const string value_string = value->ValueString(array_base, decorator);
548 if (value_string.empty()) {
549 success = false;
550 break;
551 }
552 value_strings.push_back(value_string);
Will McVickerefd970d2019-09-25 15:28:30 -0700553 }
554 if (!success) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700555 err = -1;
556 break;
Will McVickerefd970d2019-09-25 15:28:30 -0700557 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700558
559 return decorator(type, "{" + Join(value_strings, ", ") + "}");
Will McVickerefd970d2019-09-25 15:28:30 -0700560 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700561 case Type::FLOATING: {
562 std::string_view raw_view(value_.c_str());
563 bool is_float_literal = ConsumeSuffix(&raw_view, "f");
564 std::string stripped_value = std::string(raw_view);
Will McVickerefd970d2019-09-25 15:28:30 -0700565
566 if (type_string == "double") {
567 double parsed_value;
Will McVickerd7d18df2019-09-12 13:40:50 -0700568 if (!android::base::ParseDouble(stripped_value, &parsed_value)) {
569 AIDL_ERROR(this) << "Could not parse " << value_;
570 err = -1;
571 break;
572 }
Will McVickerefd970d2019-09-25 15:28:30 -0700573 return decorator(type, std::to_string(parsed_value));
574 }
575 if (is_float_literal && type_string == "float") {
576 float parsed_value;
Will McVickerd7d18df2019-09-12 13:40:50 -0700577 if (!android::base::ParseFloat(stripped_value, &parsed_value)) {
578 AIDL_ERROR(this) << "Could not parse " << value_;
579 err = -1;
580 break;
581 }
Will McVickerefd970d2019-09-25 15:28:30 -0700582 return decorator(type, std::to_string(parsed_value) + "f");
583 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700584 err = -1;
585 break;
Will McVickerefd970d2019-09-25 15:28:30 -0700586 }
Will McVickerefd970d2019-09-25 15:28:30 -0700587 default:
Will McVickerd7d18df2019-09-12 13:40:50 -0700588 err = -1;
589 break;
Will McVickerefd970d2019-09-25 15:28:30 -0700590 }
591
Steven Moreland21780812020-09-11 01:29:45 +0000592 AIDL_FATAL_IF(err == 0, this);
Will McVickerd7d18df2019-09-12 13:40:50 -0700593 AIDL_ERROR(this) << "Invalid type specifier for " << ToString(final_type_) << ": " << type_string;
Will McVickerefd970d2019-09-25 15:28:30 -0700594 return "";
Will McVickerd7d18df2019-09-12 13:40:50 -0700595}
596
597bool AidlConstantValue::CheckValid() const {
598 // Nothing needs to be checked here. The constant value will be validated in
599 // the constructor or in the evaluate() function.
600 if (is_evaluated_) return is_valid_;
601
602 switch (type_) {
603 case Type::BOOLEAN: // fall-through
604 case Type::INT8: // fall-through
605 case Type::INT32: // fall-through
606 case Type::INT64: // fall-through
607 case Type::ARRAY: // fall-through
608 case Type::CHARACTER: // fall-through
609 case Type::STRING: // fall-through
610 case Type::FLOATING: // fall-through
611 case Type::UNARY: // fall-through
612 case Type::BINARY:
613 is_valid_ = true;
614 break;
Steven Moreland4ff04aa2019-12-02 10:44:29 -0800615 case Type::ERROR:
616 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700617 default:
618 AIDL_FATAL(this) << "Unrecognized constant value type: " << ToString(type_);
619 return false;
620 }
621
622 return true;
623}
624
625bool AidlConstantValue::evaluate(const AidlTypeSpecifier& type) const {
626 if (is_evaluated_) {
627 return is_valid_;
628 }
629 int err = 0;
630 is_evaluated_ = true;
631
632 switch (type_) {
633 case Type::ARRAY: {
634 if (!type.IsArray()) {
635 AIDL_ERROR(this) << "Invalid constant array type: " << type.GetName();
636 err = -1;
637 break;
638 }
639 Type array_type = Type::ERROR;
640 bool success = true;
641 for (const auto& value : values_) {
642 success = value->CheckValid();
643 if (success) {
644 success = value->evaluate(type.ArrayBase());
645 if (!success) {
646 AIDL_ERROR(this) << "Invalid array element: " << value->value_;
647 break;
648 }
649 if (array_type == Type::ERROR) {
650 array_type = value->final_type_;
651 } else if (!AidlBinaryConstExpression::AreCompatibleTypes(array_type,
652 value->final_type_)) {
653 AIDL_ERROR(this) << "Incompatible array element type: " << ToString(value->final_type_)
654 << ". Expecting type compatible with " << ToString(array_type);
655 success = false;
656 break;
657 }
658 } else {
659 break;
660 }
661 }
662 if (!success) {
663 err = -1;
664 break;
665 }
666 final_type_ = type_;
667 break;
668 }
669 case Type::BOOLEAN:
670 if ((value_ != "true") && (value_ != "false")) {
671 AIDL_ERROR(this) << "Invalid constant boolean value: " << value_;
672 err = -1;
673 break;
674 }
675 final_value_ = (value_ == "true") ? 1 : 0;
676 final_type_ = type_;
677 break;
678 case Type::INT8: // fall-through
679 case Type::INT32: // fall-through
680 case Type::INT64:
681 // Parsing happens in the constructor
682 final_type_ = type_;
683 break;
684 case Type::CHARACTER: // fall-through
685 case Type::STRING:
686 final_string_value_ = value_;
687 final_type_ = type_;
688 break;
689 case Type::FLOATING:
690 // Just parse on the fly in ValueString
691 final_type_ = type_;
692 break;
693 default:
694 AIDL_FATAL(this) << "Unrecognized constant value type: " << ToString(type_);
695 err = -1;
696 }
697
698 return (err == 0) ? true : false;
Will McVickerefd970d2019-09-25 15:28:30 -0700699}
700
701string AidlConstantValue::ToString(Type type) {
702 switch (type) {
Will McVickerefd970d2019-09-25 15:28:30 -0700703 case Type::BOOLEAN:
704 return "a literal boolean";
Will McVickerd7d18df2019-09-12 13:40:50 -0700705 case Type::INT8:
706 return "an int8 literal";
707 case Type::INT32:
708 return "an int32 literal";
709 case Type::INT64:
710 return "an int64 literal";
Steven Morelanda923a722019-11-26 20:08:30 -0800711 case Type::ARRAY:
712 return "a literal array";
713 case Type::CHARACTER:
714 return "a literal char";
Will McVickerefd970d2019-09-25 15:28:30 -0700715 case Type::STRING:
716 return "a literal string";
Steven Morelanda923a722019-11-26 20:08:30 -0800717 case Type::FLOATING:
718 return "a literal float";
Will McVickerd7d18df2019-09-12 13:40:50 -0700719 case Type::UNARY:
720 return "a unary expression";
721 case Type::BINARY:
722 return "a binary expression";
Steven Morelanda923a722019-11-26 20:08:30 -0800723 case Type::ERROR:
Steven Moreland21780812020-09-11 01:29:45 +0000724 AIDL_FATAL(AIDL_LOCATION_HERE) << "aidl internal error: error type failed to halt program";
Steven Morelanda923a722019-11-26 20:08:30 -0800725 return "";
Will McVickerefd970d2019-09-25 15:28:30 -0700726 default:
Steven Moreland21780812020-09-11 01:29:45 +0000727 AIDL_FATAL(AIDL_LOCATION_HERE)
728 << "aidl internal error: unknown constant type: " << static_cast<int>(type);
Will McVickerefd970d2019-09-25 15:28:30 -0700729 return ""; // not reached
730 }
731}
732
Will McVickerd7d18df2019-09-12 13:40:50 -0700733bool AidlUnaryConstExpression::CheckValid() const {
734 if (is_evaluated_) return is_valid_;
Steven Moreland21780812020-09-11 01:29:45 +0000735 AIDL_FATAL_IF(unary_ == nullptr, this);
Will McVickerd7d18df2019-09-12 13:40:50 -0700736
737 is_valid_ = unary_->CheckValid();
738 if (!is_valid_) {
739 final_type_ = Type::ERROR;
740 return false;
741 }
742
Steven Moreland4bcb05c2019-11-27 18:57:47 -0800743 return AidlConstantValue::CheckValid();
Will McVickerd7d18df2019-09-12 13:40:50 -0700744}
745
746bool AidlUnaryConstExpression::evaluate(const AidlTypeSpecifier& type) const {
747 if (is_evaluated_) {
748 return is_valid_;
749 }
750 is_evaluated_ = true;
751
752 // Recursively evaluate the expression tree
753 if (!unary_->is_evaluated_) {
754 // TODO(b/142722772) CheckValid() should be called before ValueString()
755 bool success = CheckValid();
756 success &= unary_->evaluate(type);
757 if (!success) {
758 is_valid_ = false;
759 return false;
760 }
761 }
Devin Moorec233fb82020-04-07 11:13:44 -0700762 if (!IsCompatibleType(unary_->final_type_, op_)) {
763 AIDL_ERROR(unary_) << "'" << op_ << "'"
764 << " is not compatible with " << ToString(unary_->final_type_)
765 << ": " + value_;
766 is_valid_ = false;
767 return false;
768 }
769 if (!unary_->is_valid_) {
770 AIDL_ERROR(unary_) << "Invalid constant unary expression: " + value_;
Will McVickerd7d18df2019-09-12 13:40:50 -0700771 is_valid_ = false;
772 return false;
773 }
774 final_type_ = unary_->final_type_;
775
776 if (final_type_ == Type::FLOATING) {
777 // don't do anything here. ValueString() will handle everything.
778 is_valid_ = true;
779 return true;
780 }
781
Steven Morelande1ff67e2020-07-16 23:22:36 +0000782#define CASE_UNARY(__type__) \
783 return handleUnary(*this, op_, static_cast<__type__>(unary_->final_value_), &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700784
785 SWITCH_KIND(final_type_, CASE_UNARY, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
786 is_valid_ = false; return false;)
787}
788
Will McVickerd7d18df2019-09-12 13:40:50 -0700789bool AidlBinaryConstExpression::CheckValid() const {
790 bool success = false;
791 if (is_evaluated_) return is_valid_;
Steven Moreland21780812020-09-11 01:29:45 +0000792 AIDL_FATAL_IF(left_val_ == nullptr, this);
793 AIDL_FATAL_IF(right_val_ == nullptr, this);
Will McVickerd7d18df2019-09-12 13:40:50 -0700794
795 success = left_val_->CheckValid();
796 if (!success) {
797 final_type_ = Type::ERROR;
798 AIDL_ERROR(this) << "Invalid left operand in binary expression: " + value_;
799 }
800
801 success = right_val_->CheckValid();
802 if (!success) {
803 AIDL_ERROR(this) << "Invalid right operand in binary expression: " + value_;
804 final_type_ = Type::ERROR;
805 }
806
807 if (final_type_ == Type::ERROR) {
808 is_valid_ = false;
809 return false;
810 }
811
812 is_valid_ = true;
Steven Moreland4bcb05c2019-11-27 18:57:47 -0800813 return AidlConstantValue::CheckValid();
Will McVickerd7d18df2019-09-12 13:40:50 -0700814}
815
816bool AidlBinaryConstExpression::evaluate(const AidlTypeSpecifier& type) const {
817 if (is_evaluated_) {
818 return is_valid_;
819 }
820 is_evaluated_ = true;
Steven Moreland21780812020-09-11 01:29:45 +0000821 AIDL_FATAL_IF(left_val_ == nullptr, type);
822 AIDL_FATAL_IF(right_val_ == nullptr, type);
Will McVickerd7d18df2019-09-12 13:40:50 -0700823
824 // Recursively evaluate the binary expression tree
825 if (!left_val_->is_evaluated_ || !right_val_->is_evaluated_) {
826 // TODO(b/142722772) CheckValid() should be called before ValueString()
827 bool success = CheckValid();
828 success &= left_val_->evaluate(type);
829 success &= right_val_->evaluate(type);
830 if (!success) {
831 is_valid_ = false;
832 return false;
833 }
834 }
835 if (!left_val_->is_valid_ || !right_val_->is_valid_) {
836 is_valid_ = false;
837 return false;
838 }
839 is_valid_ = AreCompatibleTypes(left_val_->final_type_, right_val_->final_type_);
840 if (!is_valid_) {
Steven Moreland1f9f2212020-09-24 18:20:15 +0000841 AIDL_ERROR(this) << "Cannot perform operation '" << op_ << "' on "
842 << ToString(right_val_->GetType()) << " and " << ToString(left_val_->GetType())
843 << ".";
Will McVickerd7d18df2019-09-12 13:40:50 -0700844 return false;
845 }
846
847 bool isArithmeticOrBitflip = OP_IS_BIN_ARITHMETIC || OP_IS_BIN_BITFLIP;
848
849 // Handle String case first
850 if (left_val_->final_type_ == Type::STRING) {
Steven Moreland22e36112020-10-01 00:50:45 +0000851 AIDL_FATAL_IF(right_val_->final_type_ != Type::STRING, this);
Will McVickerd7d18df2019-09-12 13:40:50 -0700852 if (!OPEQ("+")) {
Steven Moreland22e36112020-10-01 00:50:45 +0000853 AIDL_ERROR(this) << "Only '+' is supported for strings, not '" << op_ << "'.";
Will McVickerd7d18df2019-09-12 13:40:50 -0700854 final_type_ = Type::ERROR;
855 is_valid_ = false;
856 return false;
857 }
858
859 // Remove trailing " from lhs
860 const string& lhs = left_val_->final_string_value_;
861 if (lhs.back() != '"') {
862 AIDL_ERROR(this) << "'" << lhs << "' is missing a trailing quote.";
863 final_type_ = Type::ERROR;
864 is_valid_ = false;
865 return false;
866 }
867 const string& rhs = right_val_->final_string_value_;
868 // Remove starting " from rhs
869 if (rhs.front() != '"') {
870 AIDL_ERROR(this) << "'" << rhs << "' is missing a leading quote.";
871 final_type_ = Type::ERROR;
872 is_valid_ = false;
873 return false;
874 }
875
876 final_string_value_ = string(lhs.begin(), lhs.end() - 1).append(rhs.begin() + 1, rhs.end());
877 final_type_ = Type::STRING;
878 return true;
879 }
880
Will McVickerd7d18df2019-09-12 13:40:50 -0700881 // CASE: + - * / % | ^ & < > <= >= == !=
882 if (isArithmeticOrBitflip || OP_IS_BIN_COMP) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700883 // promoted kind for both operands.
884 Type promoted = UsualArithmeticConversion(IntegralPromotion(left_val_->final_type_),
885 IntegralPromotion(right_val_->final_type_));
886 // result kind.
887 final_type_ = isArithmeticOrBitflip
888 ? promoted // arithmetic or bitflip operators generates promoted type
889 : Type::BOOLEAN; // comparison operators generates bool
890
Steven Morelande1ff67e2020-07-16 23:22:36 +0000891#define CASE_BINARY_COMMON(__type__) \
892 return handleBinaryCommon(*this, static_cast<__type__>(left_val_->final_value_), op_, \
893 static_cast<__type__>(right_val_->final_value_), &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700894
895 SWITCH_KIND(promoted, CASE_BINARY_COMMON, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
896 is_valid_ = false; return false;)
897 }
898
899 // CASE: << >>
900 string newOp = op_;
901 if (OP_IS_BIN_SHIFT) {
Devin Moore04823022020-09-11 10:43:35 -0700902 // promoted kind for both operands.
903 final_type_ = UsualArithmeticConversion(IntegralPromotion(left_val_->final_type_),
904 IntegralPromotion(right_val_->final_type_));
905 auto numBits = right_val_->final_value_;
Will McVickerd7d18df2019-09-12 13:40:50 -0700906 if (numBits < 0) {
Steven Moreland74d3f552020-02-04 15:57:50 -0800907 // shifting with negative number of bits is undefined in C. In AIDL it
Will McVickerd7d18df2019-09-12 13:40:50 -0700908 // is defined as shifting into the other direction.
909 newOp = OPEQ("<<") ? ">>" : "<<";
910 numBits = -numBits;
911 }
912
Devin Moore04823022020-09-11 10:43:35 -0700913#define CASE_SHIFT(__type__) \
914 return handleShift(*this, static_cast<__type__>(left_val_->final_value_), newOp, \
915 static_cast<__type__>(numBits), &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700916
917 SWITCH_KIND(final_type_, CASE_SHIFT, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
918 is_valid_ = false; return false;)
919 }
920
921 // CASE: && ||
922 if (OP_IS_BIN_LOGICAL) {
923 final_type_ = Type::BOOLEAN;
924 // easy; everything is bool.
Steven Morelande1ff67e2020-07-16 23:22:36 +0000925 return handleLogical(*this, left_val_->final_value_, op_, right_val_->final_value_,
926 &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700927 }
928
929 SHOULD_NOT_REACH();
930 is_valid_ = false;
931 return false;
932}
933
Will McVickerd7d18df2019-09-12 13:40:50 -0700934AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type parsed_type,
935 int64_t parsed_value, const string& checked_value)
936 : AidlNode(location),
937 type_(parsed_type),
938 value_(checked_value),
Will McVickerd7d18df2019-09-12 13:40:50 -0700939 final_type_(parsed_type),
940 final_value_(parsed_value) {
Steven Moreland21780812020-09-11 01:29:45 +0000941 AIDL_FATAL_IF(value_.empty() && type_ != Type::ERROR, location);
942 AIDL_FATAL_IF(type_ != Type::INT8 && type_ != Type::INT32 && type_ != Type::INT64, location);
Will McVickerd7d18df2019-09-12 13:40:50 -0700943}
Will McVickerefd970d2019-09-25 15:28:30 -0700944
945AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type type,
Will McVickerd7d18df2019-09-12 13:40:50 -0700946 const string& checked_value)
947 : AidlNode(location),
948 type_(type),
949 value_(checked_value),
Will McVickerd7d18df2019-09-12 13:40:50 -0700950 final_type_(type) {
Steven Moreland21780812020-09-11 01:29:45 +0000951 AIDL_FATAL_IF(value_.empty() && type_ != Type::ERROR, location);
Will McVickerd7d18df2019-09-12 13:40:50 -0700952 switch (type_) {
953 case Type::INT8:
954 case Type::INT32:
955 case Type::INT64:
956 case Type::ARRAY:
957 AIDL_FATAL(this) << "Invalid type: " << ToString(type_);
958 break;
959 default:
960 break;
961 }
962}
963
964AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type type,
965 std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values)
966 : AidlNode(location),
967 type_(type),
968 values_(std::move(*values)),
969 is_valid_(false),
970 is_evaluated_(false),
971 final_type_(type) {
Steven Moreland21780812020-09-11 01:29:45 +0000972 AIDL_FATAL_IF(type_ != Type::ARRAY, location);
Will McVickerd7d18df2019-09-12 13:40:50 -0700973}
974
975AidlUnaryConstExpression::AidlUnaryConstExpression(const AidlLocation& location, const string& op,
976 std::unique_ptr<AidlConstantValue> rval)
977 : AidlConstantValue(location, Type::UNARY, op + rval->value_),
978 unary_(std::move(rval)),
979 op_(op) {
980 final_type_ = Type::UNARY;
981}
982
983AidlBinaryConstExpression::AidlBinaryConstExpression(const AidlLocation& location,
984 std::unique_ptr<AidlConstantValue> lval,
985 const string& op,
986 std::unique_ptr<AidlConstantValue> rval)
987 : AidlConstantValue(location, Type::BINARY, lval->value_ + op + rval->value_),
988 left_val_(std::move(lval)),
989 right_val_(std::move(rval)),
990 op_(op) {
991 final_type_ = Type::BINARY;
Will McVickerefd970d2019-09-25 15:28:30 -0700992}