blob: 5c7cb3aeec0354f226b0079d3b90579f2b30fc92 [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>
40class OverflowGuard {
41 public:
42 OverflowGuard(T value) : mValue(value) {}
43 bool Overflowed() const { return mOverflowed; }
44
45 T operator+() { return +mValue; }
46 T operator-() {
47 if (isMin()) {
48 mOverflowed = true;
49 return 0;
50 }
51 return -mValue;
52 }
53 T operator!() { return !mValue; }
54 T operator~() { return ~mValue; }
55
56 T operator+(T o) {
57 T out;
58 mOverflowed = __builtin_add_overflow(mValue, o, &out);
59 return out;
60 }
61 T operator-(T o) {
62 T out;
63 mOverflowed = __builtin_sub_overflow(mValue, o, &out);
64 return out;
65 }
66 T operator*(T o) {
67 T out;
68#ifdef _WIN32
69 // ___mulodi4 not on windows https://bugs.llvm.org/show_bug.cgi?id=46669
70 // we should still get an error here from ubsan, but the nice error
71 // is needed on linux for aidl_parser_fuzzer, where we are more
72 // concerned about overflows elsewhere in the compiler in addition to
73 // those in interfaces.
74 out = mValue * o;
75#else
76 mOverflowed = __builtin_mul_overflow(mValue, o, &out);
77#endif
78 return out;
79 }
80 T operator/(T o) {
81 if (o == 0 || (isMin() && o == -1)) {
82 mOverflowed = true;
83 return 0;
84 }
85 return mValue / o;
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) { return mValue | o; }
95 T operator^(T o) { return mValue ^ o; }
96 T operator&(T o) { return mValue & o; }
97 T operator<(T o) { return mValue < o; }
98 T operator>(T o) { return mValue > o; }
99 T operator<=(T o) { return mValue <= o; }
100 T operator>=(T o) { return mValue >= o; }
101 T operator==(T o) { return mValue == o; }
102 T operator!=(T o) { return mValue != o; }
103 T operator>>(T o) {
104 if (o < 0) {
105 mOverflowed = true;
106 return 0;
107 }
108 return mValue >> o;
109 }
110 T operator<<(T o) {
111 if (o < 0 || o > static_cast<T>(sizeof(T) * 8)) {
112 mOverflowed = true;
113 return 0;
114 }
115 return mValue << o;
116 }
117 T operator||(T o) { return mValue || o; }
118 T operator&&(T o) { return mValue && o; }
119
120 private:
121 bool isMin() { return mValue == std::numeric_limits<T>::min(); }
122
123 T mValue;
124 bool mOverflowed = false;
125};
126
127template <typename T>
128bool processGuard(const OverflowGuard<T>& guard, const AidlConstantValue& context) {
129 if (guard.Overflowed()) {
130 AIDL_ERROR(context) << "Constant expression computation overflows.";
131 return false;
132 }
133 return true;
134}
135
136// TODO: factor out all these macros
Will McVickerd7d18df2019-09-12 13:40:50 -0700137#define SHOULD_NOT_REACH() CHECK(false) << LOG(FATAL) << ": should not reach here: "
138#define OPEQ(__y__) (string(op_) == string(__y__))
Steven Moreland0521bf32020-09-09 22:44:07 +0000139#define COMPUTE_UNARY(T, __op__) \
140 if (op == string(#__op__)) { \
141 OverflowGuard<T> guard(val); \
142 *out = __op__ guard; \
143 return processGuard(guard, context); \
Steven Morelande1ff67e2020-07-16 23:22:36 +0000144 }
Steven Moreland0521bf32020-09-09 22:44:07 +0000145#define COMPUTE_BINARY(T, __op__) \
146 if (op == string(#__op__)) { \
147 OverflowGuard<T> guard(lval); \
148 *out = guard __op__ rval; \
149 return processGuard(guard, context); \
Steven Morelande1ff67e2020-07-16 23:22:36 +0000150 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700151#define OP_IS_BIN_ARITHMETIC (OPEQ("+") || OPEQ("-") || OPEQ("*") || OPEQ("/") || OPEQ("%"))
152#define OP_IS_BIN_BITFLIP (OPEQ("|") || OPEQ("^") || OPEQ("&"))
153#define OP_IS_BIN_COMP \
154 (OPEQ("<") || OPEQ(">") || OPEQ("<=") || OPEQ(">=") || OPEQ("==") || OPEQ("!="))
155#define OP_IS_BIN_SHIFT (OPEQ(">>") || OPEQ("<<"))
156#define OP_IS_BIN_LOGICAL (OPEQ("||") || OPEQ("&&"))
157
158// NOLINT to suppress missing parentheses warnings about __def__.
159#define SWITCH_KIND(__cond__, __action__, __def__) \
160 switch (__cond__) { \
161 case Type::BOOLEAN: \
162 __action__(bool); \
163 case Type::INT8: \
164 __action__(int8_t); \
165 case Type::INT32: \
166 __action__(int32_t); \
167 case Type::INT64: \
168 __action__(int64_t); \
169 default: \
170 __def__; /* NOLINT */ \
171 }
172
173template <class T>
Steven Morelande1ff67e2020-07-16 23:22:36 +0000174bool handleUnary(const AidlConstantValue& context, const string& op, T val, int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000175 COMPUTE_UNARY(T, +)
176 COMPUTE_UNARY(T, -)
177 COMPUTE_UNARY(T, !)
178 COMPUTE_UNARY(T, ~)
Steven Moreland720a3cc2020-07-16 23:44:59 +0000179 AIDL_FATAL(context) << "Could not handleUnary for " << op << " " << val;
180 return false;
181}
182template <>
183bool handleUnary<bool>(const AidlConstantValue& context, const string& op, bool val, int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000184 COMPUTE_UNARY(bool, +)
185 COMPUTE_UNARY(bool, -)
186 COMPUTE_UNARY(bool, !)
Yifan Hongf17e3a72020-02-20 17:34:58 -0800187
Steven Moreland720a3cc2020-07-16 23:44:59 +0000188 if (op == "~") {
189 AIDL_ERROR(context) << "Bitwise negation of a boolean expression is always true.";
190 return false;
191 }
Steven Morelande1ff67e2020-07-16 23:22:36 +0000192 AIDL_FATAL(context) << "Could not handleUnary for " << op << " " << val;
193 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700194}
195
196template <class T>
Steven Morelande1ff67e2020-07-16 23:22:36 +0000197bool handleBinaryCommon(const AidlConstantValue& context, T lval, const string& op, T rval,
198 int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000199 COMPUTE_BINARY(T, +)
200 COMPUTE_BINARY(T, -)
201 COMPUTE_BINARY(T, *)
202 COMPUTE_BINARY(T, /)
203 COMPUTE_BINARY(T, %)
204 COMPUTE_BINARY(T, |)
205 COMPUTE_BINARY(T, ^)
206 COMPUTE_BINARY(T, &)
Will McVickerd7d18df2019-09-12 13:40:50 -0700207 // comparison operators: return 0 or 1 by nature.
Steven Moreland0521bf32020-09-09 22:44:07 +0000208 COMPUTE_BINARY(T, ==)
209 COMPUTE_BINARY(T, !=)
210 COMPUTE_BINARY(T, <)
211 COMPUTE_BINARY(T, >)
212 COMPUTE_BINARY(T, <=)
213 COMPUTE_BINARY(T, >=)
Steven Morelande1ff67e2020-07-16 23:22:36 +0000214
215 AIDL_FATAL(context) << "Could not handleBinaryCommon for " << lval << " " << op << " " << rval;
216 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700217}
218
219template <class T>
Steven Morelande1ff67e2020-07-16 23:22:36 +0000220bool handleShift(const AidlConstantValue& context, T lval, const string& op, int64_t rval,
221 int64_t* out) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700222 // just cast rval to int64_t and it should fit.
Steven Moreland0521bf32020-09-09 22:44:07 +0000223 COMPUTE_BINARY(T, >>)
224 COMPUTE_BINARY(T, <<)
Steven Morelande1ff67e2020-07-16 23:22:36 +0000225
226 AIDL_FATAL(context) << "Could not handleShift for " << lval << " " << op << " " << rval;
227 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700228}
229
Steven Morelande1ff67e2020-07-16 23:22:36 +0000230bool handleLogical(const AidlConstantValue& context, bool lval, const string& op, bool rval,
231 int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000232 COMPUTE_BINARY(bool, ||);
233 COMPUTE_BINARY(bool, &&);
Steven Morelande1ff67e2020-07-16 23:22:36 +0000234
235 AIDL_FATAL(context) << "Could not handleLogical for " << lval << " " << op << " " << rval;
Will McVickerd7d18df2019-09-12 13:40:50 -0700236 return false;
237}
238
Will McVickerefd970d2019-09-25 15:28:30 -0700239static bool isValidLiteralChar(char c) {
240 return !(c <= 0x1f || // control characters are < 0x20
241 c >= 0x7f || // DEL is 0x7f
242 c == '\\'); // Disallow backslashes for future proofing.
243}
244
Will McVickerd7d18df2019-09-12 13:40:50 -0700245bool AidlUnaryConstExpression::IsCompatibleType(Type type, const string& op) {
246 // Verify the unary type here
247 switch (type) {
248 case Type::BOOLEAN: // fall-through
249 case Type::INT8: // fall-through
250 case Type::INT32: // fall-through
251 case Type::INT64:
252 return true;
253 case Type::FLOATING:
254 return (op == "+" || op == "-");
255 default:
256 return false;
257 }
258}
259
260bool AidlBinaryConstExpression::AreCompatibleTypes(Type t1, Type t2) {
261 switch (t1) {
262 case Type::STRING:
263 if (t2 == Type::STRING) {
264 return true;
265 }
266 break;
267 case Type::BOOLEAN: // fall-through
268 case Type::INT8: // fall-through
269 case Type::INT32: // fall-through
270 case Type::INT64:
271 switch (t2) {
272 case Type::BOOLEAN: // fall-through
273 case Type::INT8: // fall-through
274 case Type::INT32: // fall-through
275 case Type::INT64:
276 return true;
277 break;
278 default:
279 break;
280 }
281 break;
282 default:
283 break;
284 }
285
286 return false;
287}
288
289// Returns the promoted kind for both operands
290AidlConstantValue::Type AidlBinaryConstExpression::UsualArithmeticConversion(Type left,
291 Type right) {
292 // These are handled as special cases
293 CHECK(left != Type::STRING && right != Type::STRING);
294 CHECK(left != Type::FLOATING && right != Type::FLOATING);
295
296 // Kinds in concern: bool, (u)int[8|32|64]
297 if (left == right) return left; // easy case
298 if (left == Type::BOOLEAN) return right;
299 if (right == Type::BOOLEAN) return left;
300
301 return left < right ? right : left;
302}
303
304// Returns the promoted integral type where INT32 is the smallest type
305AidlConstantValue::Type AidlBinaryConstExpression::IntegralPromotion(Type in) {
306 return (Type::INT32 < in) ? in : Type::INT32;
307}
308
309template <typename T>
310T AidlConstantValue::cast() const {
311 CHECK(is_evaluated_ == true);
312
313#define CASE_CAST_T(__type__) return static_cast<T>(static_cast<__type__>(final_value_));
314
315 SWITCH_KIND(final_type_, CASE_CAST_T, SHOULD_NOT_REACH(); return 0;);
316}
317
Steven Moreland541788d2020-05-21 22:05:52 +0000318AidlConstantValue* AidlConstantValue::Default(const AidlTypeSpecifier& specifier) {
319 AidlLocation location = specifier.GetLocation();
320
321 // allocation of int[0] is a bit wasteful in Java
322 if (specifier.IsArray()) {
323 return nullptr;
324 }
325
326 const std::string name = specifier.GetName();
327 if (name == "boolean") {
328 return Boolean(location, false);
329 }
330 if (name == "byte" || name == "int" || name == "long") {
331 return Integral(location, "0");
332 }
333 if (name == "float") {
334 return Floating(location, "0.0f");
335 }
336 if (name == "double") {
337 return Floating(location, "0.0");
338 }
339 return nullptr;
340}
341
Will McVickerefd970d2019-09-25 15:28:30 -0700342AidlConstantValue* AidlConstantValue::Boolean(const AidlLocation& location, bool value) {
343 return new AidlConstantValue(location, Type::BOOLEAN, value ? "true" : "false");
344}
345
346AidlConstantValue* AidlConstantValue::Character(const AidlLocation& location, char value) {
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800347 const std::string explicit_value = string("'") + value + "'";
Will McVickerefd970d2019-09-25 15:28:30 -0700348 if (!isValidLiteralChar(value)) {
349 AIDL_ERROR(location) << "Invalid character literal " << value;
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800350 return new AidlConstantValue(location, Type::ERROR, explicit_value);
Will McVickerefd970d2019-09-25 15:28:30 -0700351 }
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800352 return new AidlConstantValue(location, Type::CHARACTER, explicit_value);
Will McVickerefd970d2019-09-25 15:28:30 -0700353}
354
355AidlConstantValue* AidlConstantValue::Floating(const AidlLocation& location,
356 const std::string& value) {
357 return new AidlConstantValue(location, Type::FLOATING, value);
358}
359
Will McVickerd7d18df2019-09-12 13:40:50 -0700360bool AidlConstantValue::IsHex(const string& value) {
Steven Morelandcef22662020-07-08 20:54:28 +0000361 return StartsWith(value, "0x") || StartsWith(value, "0X");
Will McVickerefd970d2019-09-25 15:28:30 -0700362}
363
Will McVickerd7d18df2019-09-12 13:40:50 -0700364bool AidlConstantValue::ParseIntegral(const string& value, int64_t* parsed_value,
365 Type* parsed_type) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700366 if (parsed_value == nullptr || parsed_type == nullptr) {
367 return false;
368 }
369
Steven Morelandcef22662020-07-08 20:54:28 +0000370 const bool isLong = EndsWith(value, 'l') || EndsWith(value, 'L');
371 const std::string value_substr = isLong ? value.substr(0, value.size() - 1) : value;
Will McVickerd7d18df2019-09-12 13:40:50 -0700372
Steven Morelandcef22662020-07-08 20:54:28 +0000373 if (IsHex(value)) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700374 // AIDL considers 'const int foo = 0xffffffff' as -1, but if we want to
375 // handle that when computing constant expressions, then we need to
376 // represent 0xffffffff as a uint32_t. However, AIDL only has signed types;
377 // so we parse as an unsigned int when possible and then cast to a signed
378 // int. One example of this is in ICameraService.aidl where a constant int
379 // is used for bit manipulations which ideally should be handled with an
380 // unsigned int.
Steven Morelandcef22662020-07-08 20:54:28 +0000381 //
382 // Note, for historical consistency, we need to consider small hex values
383 // as an integral type. Recognizing them as INT8 could break some files,
384 // even though it would simplify this code.
385 if (uint32_t rawValue32;
386 !isLong && android::base::ParseUint<uint32_t>(value_substr, &rawValue32)) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700387 *parsed_value = static_cast<int32_t>(rawValue32);
388 *parsed_type = Type::INT32;
Steven Morelandcef22662020-07-08 20:54:28 +0000389 } else if (uint64_t rawValue64; android::base::ParseUint<uint64_t>(value_substr, &rawValue64)) {
390 *parsed_value = static_cast<int64_t>(rawValue64);
Will McVickerd7d18df2019-09-12 13:40:50 -0700391 *parsed_type = Type::INT64;
Steven Morelandcef22662020-07-08 20:54:28 +0000392 } else {
393 *parsed_value = 0;
394 *parsed_type = Type::ERROR;
395 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700396 }
397 return true;
398 }
399
Steven Morelandcef22662020-07-08 20:54:28 +0000400 if (!android::base::ParseInt<int64_t>(value_substr, parsed_value)) {
401 *parsed_value = 0;
Will McVickerd7d18df2019-09-12 13:40:50 -0700402 *parsed_type = Type::ERROR;
403 return false;
404 }
405
Steven Morelandcef22662020-07-08 20:54:28 +0000406 if (isLong) {
407 *parsed_type = Type::INT64;
408 } else {
Will McVickerd7d18df2019-09-12 13:40:50 -0700409 // guess literal type.
410 if (*parsed_value <= INT8_MAX && *parsed_value >= INT8_MIN) {
411 *parsed_type = Type::INT8;
412 } else if (*parsed_value <= INT32_MAX && *parsed_value >= INT32_MIN) {
413 *parsed_type = Type::INT32;
414 } else {
415 *parsed_type = Type::INT64;
416 }
417 }
418 return true;
419}
420
421AidlConstantValue* AidlConstantValue::Integral(const AidlLocation& location, const string& value) {
422 CHECK(!value.empty());
423
424 Type parsed_type;
425 int64_t parsed_value = 0;
426 bool success = ParseIntegral(value, &parsed_value, &parsed_type);
427 if (!success) {
428 return nullptr;
429 }
430
431 return new AidlConstantValue(location, parsed_type, parsed_value, value);
Will McVickerefd970d2019-09-25 15:28:30 -0700432}
433
434AidlConstantValue* AidlConstantValue::Array(
Will McVickerd7d18df2019-09-12 13:40:50 -0700435 const AidlLocation& location, std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values) {
Steven Moreland541788d2020-05-21 22:05:52 +0000436 CHECK(values != nullptr) << location;
Will McVickerd7d18df2019-09-12 13:40:50 -0700437 return new AidlConstantValue(location, Type::ARRAY, std::move(values));
Will McVickerefd970d2019-09-25 15:28:30 -0700438}
439
Will McVickerd7d18df2019-09-12 13:40:50 -0700440AidlConstantValue* AidlConstantValue::String(const AidlLocation& location, const string& value) {
Will McVickerefd970d2019-09-25 15:28:30 -0700441 for (size_t i = 0; i < value.length(); ++i) {
442 if (!isValidLiteralChar(value[i])) {
443 AIDL_ERROR(location) << "Found invalid character at index " << i << " in string constant '"
444 << value << "'";
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800445 return new AidlConstantValue(location, Type::ERROR, value);
Will McVickerefd970d2019-09-25 15:28:30 -0700446 }
447 }
448
449 return new AidlConstantValue(location, Type::STRING, value);
450}
451
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700452AidlConstantValue* AidlConstantValue::ShallowIntegralCopy(const AidlConstantValue& other) {
Daniel Norman3cce7cd2020-02-07 13:25:12 -0800453 // TODO(b/141313220) Perform a full copy instead of parsing+unparsing
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700454 AidlTypeSpecifier type = AidlTypeSpecifier(AIDL_LOCATION_HERE, "long", false, nullptr, "");
Steven Moreland65606612019-11-10 21:21:25 -0800455 // TODO(b/142722772) CheckValid() should be called before ValueString()
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800456 if (!other.CheckValid() || !other.evaluate(type)) {
Steven Moreland59e53e42019-11-26 20:38:08 -0800457 AIDL_ERROR(other) << "Failed to parse expression as integer: " << other.value_;
458 return nullptr;
459 }
460 const std::string& value = other.ValueString(type, AidlConstantValueDecorator);
461 if (value.empty()) {
462 return nullptr; // error already logged
Daniel Normanb28684e2019-10-17 15:31:39 -0700463 }
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700464
Steven Moreland59e53e42019-11-26 20:38:08 -0800465 AidlConstantValue* result = Integral(AIDL_LOCATION_HERE, value);
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700466 if (result == nullptr) {
467 AIDL_FATAL(other) << "Unable to perform ShallowIntegralCopy.";
468 }
469 return result;
Daniel Normanb28684e2019-10-17 15:31:39 -0700470}
471
Will McVickerd7d18df2019-09-12 13:40:50 -0700472string AidlConstantValue::ValueString(const AidlTypeSpecifier& type,
473 const ConstantValueDecorator& decorator) const {
Will McVickerefd970d2019-09-25 15:28:30 -0700474 if (type.IsGeneric()) {
475 AIDL_ERROR(type) << "Generic type cannot be specified with a constant literal.";
476 return "";
477 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700478 if (!is_evaluated_) {
479 // TODO(b/142722772) CheckValid() should be called before ValueString()
480 bool success = CheckValid();
481 success &= evaluate(type);
482 if (!success) {
483 // the detailed error message shall be printed in evaluate
484 return "";
485 }
Will McVickerefd970d2019-09-25 15:28:30 -0700486 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700487 if (!is_valid_) {
488 AIDL_ERROR(this) << "Invalid constant value: " + value_;
489 return "";
490 }
491 const string& type_string = type.GetName();
492 int err = 0;
Will McVickerefd970d2019-09-25 15:28:30 -0700493
Will McVickerd7d18df2019-09-12 13:40:50 -0700494 switch (final_type_) {
495 case Type::CHARACTER:
496 if (type_string == "char") {
497 return decorator(type, final_string_value_);
498 }
499 err = -1;
500 break;
501 case Type::STRING:
502 if (type_string == "String") {
503 return decorator(type, final_string_value_);
504 }
505 err = -1;
506 break;
507 case Type::BOOLEAN: // fall-through
508 case Type::INT8: // fall-through
509 case Type::INT32: // fall-through
510 case Type::INT64:
511 if (type_string == "byte") {
512 if (final_value_ > INT8_MAX || final_value_ < INT8_MIN) {
513 err = -1;
514 break;
515 }
516 return decorator(type, std::to_string(static_cast<int8_t>(final_value_)));
517 } else if (type_string == "int") {
518 if (final_value_ > INT32_MAX || final_value_ < INT32_MIN) {
519 err = -1;
520 break;
521 }
522 return decorator(type, std::to_string(static_cast<int32_t>(final_value_)));
523 } else if (type_string == "long") {
524 return decorator(type, std::to_string(final_value_));
525 } else if (type_string == "boolean") {
526 return decorator(type, final_value_ ? "true" : "false");
527 }
528 err = -1;
529 break;
530 case Type::ARRAY: {
531 if (!type.IsArray()) {
532 err = -1;
533 break;
534 }
535 vector<string> value_strings;
536 value_strings.reserve(values_.size());
Will McVickerefd970d2019-09-25 15:28:30 -0700537 bool success = true;
Will McVickerd7d18df2019-09-12 13:40:50 -0700538
Will McVickerefd970d2019-09-25 15:28:30 -0700539 for (const auto& value : values_) {
540 const AidlTypeSpecifier& array_base = type.ArrayBase();
Will McVickerd7d18df2019-09-12 13:40:50 -0700541 const string value_string = value->ValueString(array_base, decorator);
542 if (value_string.empty()) {
543 success = false;
544 break;
545 }
546 value_strings.push_back(value_string);
Will McVickerefd970d2019-09-25 15:28:30 -0700547 }
548 if (!success) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700549 err = -1;
550 break;
Will McVickerefd970d2019-09-25 15:28:30 -0700551 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700552
553 return decorator(type, "{" + Join(value_strings, ", ") + "}");
Will McVickerefd970d2019-09-25 15:28:30 -0700554 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700555 case Type::FLOATING: {
556 std::string_view raw_view(value_.c_str());
557 bool is_float_literal = ConsumeSuffix(&raw_view, "f");
558 std::string stripped_value = std::string(raw_view);
Will McVickerefd970d2019-09-25 15:28:30 -0700559
560 if (type_string == "double") {
561 double parsed_value;
Will McVickerd7d18df2019-09-12 13:40:50 -0700562 if (!android::base::ParseDouble(stripped_value, &parsed_value)) {
563 AIDL_ERROR(this) << "Could not parse " << value_;
564 err = -1;
565 break;
566 }
Will McVickerefd970d2019-09-25 15:28:30 -0700567 return decorator(type, std::to_string(parsed_value));
568 }
569 if (is_float_literal && type_string == "float") {
570 float parsed_value;
Will McVickerd7d18df2019-09-12 13:40:50 -0700571 if (!android::base::ParseFloat(stripped_value, &parsed_value)) {
572 AIDL_ERROR(this) << "Could not parse " << value_;
573 err = -1;
574 break;
575 }
Will McVickerefd970d2019-09-25 15:28:30 -0700576 return decorator(type, std::to_string(parsed_value) + "f");
577 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700578 err = -1;
579 break;
Will McVickerefd970d2019-09-25 15:28:30 -0700580 }
Will McVickerefd970d2019-09-25 15:28:30 -0700581 default:
Will McVickerd7d18df2019-09-12 13:40:50 -0700582 err = -1;
583 break;
Will McVickerefd970d2019-09-25 15:28:30 -0700584 }
585
Will McVickerd7d18df2019-09-12 13:40:50 -0700586 CHECK(err != 0);
587 AIDL_ERROR(this) << "Invalid type specifier for " << ToString(final_type_) << ": " << type_string;
Will McVickerefd970d2019-09-25 15:28:30 -0700588 return "";
Will McVickerd7d18df2019-09-12 13:40:50 -0700589}
590
591bool AidlConstantValue::CheckValid() const {
592 // Nothing needs to be checked here. The constant value will be validated in
593 // the constructor or in the evaluate() function.
594 if (is_evaluated_) return is_valid_;
595
596 switch (type_) {
597 case Type::BOOLEAN: // fall-through
598 case Type::INT8: // fall-through
599 case Type::INT32: // fall-through
600 case Type::INT64: // fall-through
601 case Type::ARRAY: // fall-through
602 case Type::CHARACTER: // fall-through
603 case Type::STRING: // fall-through
604 case Type::FLOATING: // fall-through
605 case Type::UNARY: // fall-through
606 case Type::BINARY:
607 is_valid_ = true;
608 break;
Steven Moreland4ff04aa2019-12-02 10:44:29 -0800609 case Type::ERROR:
610 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700611 default:
612 AIDL_FATAL(this) << "Unrecognized constant value type: " << ToString(type_);
613 return false;
614 }
615
616 return true;
617}
618
619bool AidlConstantValue::evaluate(const AidlTypeSpecifier& type) const {
620 if (is_evaluated_) {
621 return is_valid_;
622 }
623 int err = 0;
624 is_evaluated_ = true;
625
626 switch (type_) {
627 case Type::ARRAY: {
628 if (!type.IsArray()) {
629 AIDL_ERROR(this) << "Invalid constant array type: " << type.GetName();
630 err = -1;
631 break;
632 }
633 Type array_type = Type::ERROR;
634 bool success = true;
635 for (const auto& value : values_) {
636 success = value->CheckValid();
637 if (success) {
638 success = value->evaluate(type.ArrayBase());
639 if (!success) {
640 AIDL_ERROR(this) << "Invalid array element: " << value->value_;
641 break;
642 }
643 if (array_type == Type::ERROR) {
644 array_type = value->final_type_;
645 } else if (!AidlBinaryConstExpression::AreCompatibleTypes(array_type,
646 value->final_type_)) {
647 AIDL_ERROR(this) << "Incompatible array element type: " << ToString(value->final_type_)
648 << ". Expecting type compatible with " << ToString(array_type);
649 success = false;
650 break;
651 }
652 } else {
653 break;
654 }
655 }
656 if (!success) {
657 err = -1;
658 break;
659 }
660 final_type_ = type_;
661 break;
662 }
663 case Type::BOOLEAN:
664 if ((value_ != "true") && (value_ != "false")) {
665 AIDL_ERROR(this) << "Invalid constant boolean value: " << value_;
666 err = -1;
667 break;
668 }
669 final_value_ = (value_ == "true") ? 1 : 0;
670 final_type_ = type_;
671 break;
672 case Type::INT8: // fall-through
673 case Type::INT32: // fall-through
674 case Type::INT64:
675 // Parsing happens in the constructor
676 final_type_ = type_;
677 break;
678 case Type::CHARACTER: // fall-through
679 case Type::STRING:
680 final_string_value_ = value_;
681 final_type_ = type_;
682 break;
683 case Type::FLOATING:
684 // Just parse on the fly in ValueString
685 final_type_ = type_;
686 break;
687 default:
688 AIDL_FATAL(this) << "Unrecognized constant value type: " << ToString(type_);
689 err = -1;
690 }
691
692 return (err == 0) ? true : false;
Will McVickerefd970d2019-09-25 15:28:30 -0700693}
694
695string AidlConstantValue::ToString(Type type) {
696 switch (type) {
Will McVickerefd970d2019-09-25 15:28:30 -0700697 case Type::BOOLEAN:
698 return "a literal boolean";
Will McVickerd7d18df2019-09-12 13:40:50 -0700699 case Type::INT8:
700 return "an int8 literal";
701 case Type::INT32:
702 return "an int32 literal";
703 case Type::INT64:
704 return "an int64 literal";
Steven Morelanda923a722019-11-26 20:08:30 -0800705 case Type::ARRAY:
706 return "a literal array";
707 case Type::CHARACTER:
708 return "a literal char";
Will McVickerefd970d2019-09-25 15:28:30 -0700709 case Type::STRING:
710 return "a literal string";
Steven Morelanda923a722019-11-26 20:08:30 -0800711 case Type::FLOATING:
712 return "a literal float";
Will McVickerd7d18df2019-09-12 13:40:50 -0700713 case Type::UNARY:
714 return "a unary expression";
715 case Type::BINARY:
716 return "a binary expression";
Steven Morelanda923a722019-11-26 20:08:30 -0800717 case Type::ERROR:
718 LOG(FATAL) << "aidl internal error: error type failed to halt program";
719 return "";
Will McVickerefd970d2019-09-25 15:28:30 -0700720 default:
721 LOG(FATAL) << "aidl internal error: unknown constant type: " << static_cast<int>(type);
722 return ""; // not reached
723 }
724}
725
Will McVickerd7d18df2019-09-12 13:40:50 -0700726bool AidlUnaryConstExpression::CheckValid() const {
727 if (is_evaluated_) return is_valid_;
728 CHECK(unary_ != nullptr);
729
730 is_valid_ = unary_->CheckValid();
731 if (!is_valid_) {
732 final_type_ = Type::ERROR;
733 return false;
734 }
735
Steven Moreland4bcb05c2019-11-27 18:57:47 -0800736 return AidlConstantValue::CheckValid();
Will McVickerd7d18df2019-09-12 13:40:50 -0700737}
738
739bool AidlUnaryConstExpression::evaluate(const AidlTypeSpecifier& type) const {
740 if (is_evaluated_) {
741 return is_valid_;
742 }
743 is_evaluated_ = true;
744
745 // Recursively evaluate the expression tree
746 if (!unary_->is_evaluated_) {
747 // TODO(b/142722772) CheckValid() should be called before ValueString()
748 bool success = CheckValid();
749 success &= unary_->evaluate(type);
750 if (!success) {
751 is_valid_ = false;
752 return false;
753 }
754 }
Devin Moorec233fb82020-04-07 11:13:44 -0700755 if (!IsCompatibleType(unary_->final_type_, op_)) {
756 AIDL_ERROR(unary_) << "'" << op_ << "'"
757 << " is not compatible with " << ToString(unary_->final_type_)
758 << ": " + value_;
759 is_valid_ = false;
760 return false;
761 }
762 if (!unary_->is_valid_) {
763 AIDL_ERROR(unary_) << "Invalid constant unary expression: " + value_;
Will McVickerd7d18df2019-09-12 13:40:50 -0700764 is_valid_ = false;
765 return false;
766 }
767 final_type_ = unary_->final_type_;
768
769 if (final_type_ == Type::FLOATING) {
770 // don't do anything here. ValueString() will handle everything.
771 is_valid_ = true;
772 return true;
773 }
774
Steven Morelande1ff67e2020-07-16 23:22:36 +0000775#define CASE_UNARY(__type__) \
776 return handleUnary(*this, op_, static_cast<__type__>(unary_->final_value_), &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700777
778 SWITCH_KIND(final_type_, CASE_UNARY, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
779 is_valid_ = false; return false;)
780}
781
Will McVickerd7d18df2019-09-12 13:40:50 -0700782bool AidlBinaryConstExpression::CheckValid() const {
783 bool success = false;
784 if (is_evaluated_) return is_valid_;
785 CHECK(left_val_ != nullptr);
786 CHECK(right_val_ != nullptr);
787
788 success = left_val_->CheckValid();
789 if (!success) {
790 final_type_ = Type::ERROR;
791 AIDL_ERROR(this) << "Invalid left operand in binary expression: " + value_;
792 }
793
794 success = right_val_->CheckValid();
795 if (!success) {
796 AIDL_ERROR(this) << "Invalid right operand in binary expression: " + value_;
797 final_type_ = Type::ERROR;
798 }
799
800 if (final_type_ == Type::ERROR) {
801 is_valid_ = false;
802 return false;
803 }
804
805 is_valid_ = true;
Steven Moreland4bcb05c2019-11-27 18:57:47 -0800806 return AidlConstantValue::CheckValid();
Will McVickerd7d18df2019-09-12 13:40:50 -0700807}
808
809bool AidlBinaryConstExpression::evaluate(const AidlTypeSpecifier& type) const {
810 if (is_evaluated_) {
811 return is_valid_;
812 }
813 is_evaluated_ = true;
814 CHECK(left_val_ != nullptr);
815 CHECK(right_val_ != nullptr);
816
817 // Recursively evaluate the binary expression tree
818 if (!left_val_->is_evaluated_ || !right_val_->is_evaluated_) {
819 // TODO(b/142722772) CheckValid() should be called before ValueString()
820 bool success = CheckValid();
821 success &= left_val_->evaluate(type);
822 success &= right_val_->evaluate(type);
823 if (!success) {
824 is_valid_ = false;
825 return false;
826 }
827 }
828 if (!left_val_->is_valid_ || !right_val_->is_valid_) {
829 is_valid_ = false;
830 return false;
831 }
832 is_valid_ = AreCompatibleTypes(left_val_->final_type_, right_val_->final_type_);
833 if (!is_valid_) {
834 return false;
835 }
836
837 bool isArithmeticOrBitflip = OP_IS_BIN_ARITHMETIC || OP_IS_BIN_BITFLIP;
838
839 // Handle String case first
840 if (left_val_->final_type_ == Type::STRING) {
841 if (!OPEQ("+")) {
842 // invalid operation on strings
843 final_type_ = Type::ERROR;
844 is_valid_ = false;
845 return false;
846 }
847
848 // Remove trailing " from lhs
849 const string& lhs = left_val_->final_string_value_;
850 if (lhs.back() != '"') {
851 AIDL_ERROR(this) << "'" << lhs << "' is missing a trailing quote.";
852 final_type_ = Type::ERROR;
853 is_valid_ = false;
854 return false;
855 }
856 const string& rhs = right_val_->final_string_value_;
857 // Remove starting " from rhs
858 if (rhs.front() != '"') {
859 AIDL_ERROR(this) << "'" << rhs << "' is missing a leading quote.";
860 final_type_ = Type::ERROR;
861 is_valid_ = false;
862 return false;
863 }
864
865 final_string_value_ = string(lhs.begin(), lhs.end() - 1).append(rhs.begin() + 1, rhs.end());
866 final_type_ = Type::STRING;
867 return true;
868 }
869
Will McVickerd7d18df2019-09-12 13:40:50 -0700870 // CASE: + - * / % | ^ & < > <= >= == !=
871 if (isArithmeticOrBitflip || OP_IS_BIN_COMP) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700872 // promoted kind for both operands.
873 Type promoted = UsualArithmeticConversion(IntegralPromotion(left_val_->final_type_),
874 IntegralPromotion(right_val_->final_type_));
875 // result kind.
876 final_type_ = isArithmeticOrBitflip
877 ? promoted // arithmetic or bitflip operators generates promoted type
878 : Type::BOOLEAN; // comparison operators generates bool
879
Steven Morelande1ff67e2020-07-16 23:22:36 +0000880#define CASE_BINARY_COMMON(__type__) \
881 return handleBinaryCommon(*this, static_cast<__type__>(left_val_->final_value_), op_, \
882 static_cast<__type__>(right_val_->final_value_), &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700883
884 SWITCH_KIND(promoted, CASE_BINARY_COMMON, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
885 is_valid_ = false; return false;)
886 }
887
888 // CASE: << >>
889 string newOp = op_;
890 if (OP_IS_BIN_SHIFT) {
891 final_type_ = IntegralPromotion(left_val_->final_type_);
892 // instead of promoting rval, simply casting it to int64 should also be good.
893 int64_t numBits = right_val_->cast<int64_t>();
894 if (numBits < 0) {
Steven Moreland74d3f552020-02-04 15:57:50 -0800895 // shifting with negative number of bits is undefined in C. In AIDL it
Will McVickerd7d18df2019-09-12 13:40:50 -0700896 // is defined as shifting into the other direction.
897 newOp = OPEQ("<<") ? ">>" : "<<";
898 numBits = -numBits;
899 }
900
Steven Morelande1ff67e2020-07-16 23:22:36 +0000901#define CASE_SHIFT(__type__) \
902 return handleShift(*this, static_cast<__type__>(left_val_->final_value_), newOp, numBits, \
903 &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700904
905 SWITCH_KIND(final_type_, CASE_SHIFT, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
906 is_valid_ = false; return false;)
907 }
908
909 // CASE: && ||
910 if (OP_IS_BIN_LOGICAL) {
911 final_type_ = Type::BOOLEAN;
912 // easy; everything is bool.
Steven Morelande1ff67e2020-07-16 23:22:36 +0000913 return handleLogical(*this, left_val_->final_value_, op_, right_val_->final_value_,
914 &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700915 }
916
917 SHOULD_NOT_REACH();
918 is_valid_ = false;
919 return false;
920}
921
Will McVickerd7d18df2019-09-12 13:40:50 -0700922AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type parsed_type,
923 int64_t parsed_value, const string& checked_value)
924 : AidlNode(location),
925 type_(parsed_type),
926 value_(checked_value),
Will McVickerd7d18df2019-09-12 13:40:50 -0700927 final_type_(parsed_type),
928 final_value_(parsed_value) {
Steven Moreland541788d2020-05-21 22:05:52 +0000929 CHECK(!value_.empty() || type_ == Type::ERROR) << location;
930 CHECK(type_ == Type::INT8 || type_ == Type::INT32 || type_ == Type::INT64) << location;
Will McVickerd7d18df2019-09-12 13:40:50 -0700931}
Will McVickerefd970d2019-09-25 15:28:30 -0700932
933AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type type,
Will McVickerd7d18df2019-09-12 13:40:50 -0700934 const string& checked_value)
935 : AidlNode(location),
936 type_(type),
937 value_(checked_value),
Will McVickerd7d18df2019-09-12 13:40:50 -0700938 final_type_(type) {
Steven Moreland541788d2020-05-21 22:05:52 +0000939 CHECK(!value_.empty() || type_ == Type::ERROR) << location;
Will McVickerd7d18df2019-09-12 13:40:50 -0700940 switch (type_) {
941 case Type::INT8:
942 case Type::INT32:
943 case Type::INT64:
944 case Type::ARRAY:
945 AIDL_FATAL(this) << "Invalid type: " << ToString(type_);
946 break;
947 default:
948 break;
949 }
950}
951
952AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type type,
953 std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values)
954 : AidlNode(location),
955 type_(type),
956 values_(std::move(*values)),
957 is_valid_(false),
958 is_evaluated_(false),
959 final_type_(type) {
960 CHECK(type_ == Type::ARRAY);
961}
962
963AidlUnaryConstExpression::AidlUnaryConstExpression(const AidlLocation& location, const string& op,
964 std::unique_ptr<AidlConstantValue> rval)
965 : AidlConstantValue(location, Type::UNARY, op + rval->value_),
966 unary_(std::move(rval)),
967 op_(op) {
968 final_type_ = Type::UNARY;
969}
970
971AidlBinaryConstExpression::AidlBinaryConstExpression(const AidlLocation& location,
972 std::unique_ptr<AidlConstantValue> lval,
973 const string& op,
974 std::unique_ptr<AidlConstantValue> rval)
975 : AidlConstantValue(location, Type::BINARY, lval->value_ + op + rval->value_),
976 left_val_(std::move(lval)),
977 right_val_(std::move(rval)),
978 op_(op) {
979 final_type_ = Type::BINARY;
Will McVickerefd970d2019-09-25 15:28:30 -0700980}