blob: bac8dac77243746eb5e108241f8b091fb7cda5ec [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) {
41 return (sizeof(T) == sizeof(uint64_t)) ? __builtin_clzl(x) : __builtin_clz(x);
42}
43
44template <typename T>
Steven Moreland0521bf32020-09-09 22:44:07 +000045class OverflowGuard {
46 public:
47 OverflowGuard(T value) : mValue(value) {}
48 bool Overflowed() const { return mOverflowed; }
49
50 T operator+() { return +mValue; }
51 T operator-() {
52 if (isMin()) {
53 mOverflowed = true;
54 return 0;
55 }
56 return -mValue;
57 }
58 T operator!() { return !mValue; }
59 T operator~() { return ~mValue; }
60
61 T operator+(T o) {
62 T out;
63 mOverflowed = __builtin_add_overflow(mValue, o, &out);
64 return out;
65 }
66 T operator-(T o) {
67 T out;
68 mOverflowed = __builtin_sub_overflow(mValue, o, &out);
69 return out;
70 }
71 T operator*(T o) {
72 T out;
73#ifdef _WIN32
74 // ___mulodi4 not on windows https://bugs.llvm.org/show_bug.cgi?id=46669
75 // we should still get an error here from ubsan, but the nice error
76 // is needed on linux for aidl_parser_fuzzer, where we are more
77 // concerned about overflows elsewhere in the compiler in addition to
78 // those in interfaces.
79 out = mValue * o;
80#else
81 mOverflowed = __builtin_mul_overflow(mValue, o, &out);
82#endif
83 return out;
84 }
85 T operator/(T o) {
86 if (o == 0 || (isMin() && o == -1)) {
87 mOverflowed = true;
88 return 0;
89 }
90 return mValue / o;
91 }
92 T operator%(T o) {
93 if (o == 0 || (isMin() && o == -1)) {
94 mOverflowed = true;
95 return 0;
96 }
97 return mValue % o;
98 }
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) { 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) {
Devin Moorea9e64de2020-09-29 11:29:42 -0700109 if (o < 0 || o >= static_cast<T>(sizeof(T) * 8) || mValue < 0) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000110 mOverflowed = true;
111 return 0;
112 }
113 return mValue >> o;
114 }
115 T operator<<(T o) {
Devin Moorecff93692020-09-24 10:39:57 -0700116 if (o < 0 || mValue < 0 || o > CLZ(mValue)) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000117 mOverflowed = true;
118 return 0;
119 }
120 return mValue << o;
121 }
122 T operator||(T o) { return mValue || o; }
123 T operator&&(T o) { return mValue && o; }
124
125 private:
126 bool isMin() { return mValue == std::numeric_limits<T>::min(); }
127
128 T mValue;
129 bool mOverflowed = false;
130};
131
132template <typename T>
133bool processGuard(const OverflowGuard<T>& guard, const AidlConstantValue& context) {
134 if (guard.Overflowed()) {
135 AIDL_ERROR(context) << "Constant expression computation overflows.";
136 return false;
137 }
138 return true;
139}
140
141// TODO: factor out all these macros
Steven Moreland21780812020-09-11 01:29:45 +0000142#define SHOULD_NOT_REACH() AIDL_FATAL(AIDL_LOCATION_HERE) << "Should not reach."
Will McVickerd7d18df2019-09-12 13:40:50 -0700143#define OPEQ(__y__) (string(op_) == string(__y__))
Steven Moreland0521bf32020-09-09 22:44:07 +0000144#define COMPUTE_UNARY(T, __op__) \
145 if (op == string(#__op__)) { \
146 OverflowGuard<T> guard(val); \
147 *out = __op__ guard; \
148 return processGuard(guard, context); \
Steven Morelande1ff67e2020-07-16 23:22:36 +0000149 }
Steven Moreland0521bf32020-09-09 22:44:07 +0000150#define COMPUTE_BINARY(T, __op__) \
151 if (op == string(#__op__)) { \
152 OverflowGuard<T> guard(lval); \
153 *out = guard __op__ rval; \
154 return processGuard(guard, context); \
Steven Morelande1ff67e2020-07-16 23:22:36 +0000155 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700156#define OP_IS_BIN_ARITHMETIC (OPEQ("+") || OPEQ("-") || OPEQ("*") || OPEQ("/") || OPEQ("%"))
157#define OP_IS_BIN_BITFLIP (OPEQ("|") || OPEQ("^") || OPEQ("&"))
158#define OP_IS_BIN_COMP \
159 (OPEQ("<") || OPEQ(">") || OPEQ("<=") || OPEQ(">=") || OPEQ("==") || OPEQ("!="))
160#define OP_IS_BIN_SHIFT (OPEQ(">>") || OPEQ("<<"))
161#define OP_IS_BIN_LOGICAL (OPEQ("||") || OPEQ("&&"))
162
163// NOLINT to suppress missing parentheses warnings about __def__.
164#define SWITCH_KIND(__cond__, __action__, __def__) \
165 switch (__cond__) { \
166 case Type::BOOLEAN: \
167 __action__(bool); \
168 case Type::INT8: \
169 __action__(int8_t); \
170 case Type::INT32: \
171 __action__(int32_t); \
172 case Type::INT64: \
173 __action__(int64_t); \
174 default: \
175 __def__; /* NOLINT */ \
176 }
177
178template <class T>
Steven Morelande1ff67e2020-07-16 23:22:36 +0000179bool handleUnary(const AidlConstantValue& context, const string& op, T val, int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000180 COMPUTE_UNARY(T, +)
181 COMPUTE_UNARY(T, -)
182 COMPUTE_UNARY(T, !)
183 COMPUTE_UNARY(T, ~)
Steven Moreland720a3cc2020-07-16 23:44:59 +0000184 AIDL_FATAL(context) << "Could not handleUnary for " << op << " " << val;
185 return false;
186}
187template <>
188bool handleUnary<bool>(const AidlConstantValue& context, const string& op, bool val, int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000189 COMPUTE_UNARY(bool, +)
190 COMPUTE_UNARY(bool, -)
191 COMPUTE_UNARY(bool, !)
Yifan Hongf17e3a72020-02-20 17:34:58 -0800192
Steven Moreland720a3cc2020-07-16 23:44:59 +0000193 if (op == "~") {
194 AIDL_ERROR(context) << "Bitwise negation of a boolean expression is always true.";
195 return false;
196 }
Steven Morelande1ff67e2020-07-16 23:22:36 +0000197 AIDL_FATAL(context) << "Could not handleUnary for " << op << " " << val;
198 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700199}
200
201template <class T>
Steven Morelande1ff67e2020-07-16 23:22:36 +0000202bool handleBinaryCommon(const AidlConstantValue& context, T lval, const string& op, T rval,
203 int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000204 COMPUTE_BINARY(T, +)
205 COMPUTE_BINARY(T, -)
206 COMPUTE_BINARY(T, *)
207 COMPUTE_BINARY(T, /)
208 COMPUTE_BINARY(T, %)
209 COMPUTE_BINARY(T, |)
210 COMPUTE_BINARY(T, ^)
211 COMPUTE_BINARY(T, &)
Will McVickerd7d18df2019-09-12 13:40:50 -0700212 // comparison operators: return 0 or 1 by nature.
Steven Moreland0521bf32020-09-09 22:44:07 +0000213 COMPUTE_BINARY(T, ==)
214 COMPUTE_BINARY(T, !=)
215 COMPUTE_BINARY(T, <)
216 COMPUTE_BINARY(T, >)
217 COMPUTE_BINARY(T, <=)
218 COMPUTE_BINARY(T, >=)
Steven Morelande1ff67e2020-07-16 23:22:36 +0000219
220 AIDL_FATAL(context) << "Could not handleBinaryCommon for " << lval << " " << op << " " << rval;
221 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700222}
223
224template <class T>
Devin Moore04823022020-09-11 10:43:35 -0700225bool handleShift(const AidlConstantValue& context, T lval, const string& op, T rval, int64_t* out) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700226 // just cast rval to int64_t and it should fit.
Steven Moreland0521bf32020-09-09 22:44:07 +0000227 COMPUTE_BINARY(T, >>)
228 COMPUTE_BINARY(T, <<)
Steven Morelande1ff67e2020-07-16 23:22:36 +0000229
230 AIDL_FATAL(context) << "Could not handleShift for " << lval << " " << op << " " << rval;
231 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700232}
233
Steven Morelande1ff67e2020-07-16 23:22:36 +0000234bool handleLogical(const AidlConstantValue& context, bool lval, const string& op, bool rval,
235 int64_t* out) {
Steven Moreland0521bf32020-09-09 22:44:07 +0000236 COMPUTE_BINARY(bool, ||);
237 COMPUTE_BINARY(bool, &&);
Steven Morelande1ff67e2020-07-16 23:22:36 +0000238
239 AIDL_FATAL(context) << "Could not handleLogical for " << lval << " " << op << " " << rval;
Will McVickerd7d18df2019-09-12 13:40:50 -0700240 return false;
241}
242
Will McVickerefd970d2019-09-25 15:28:30 -0700243static bool isValidLiteralChar(char c) {
244 return !(c <= 0x1f || // control characters are < 0x20
245 c >= 0x7f || // DEL is 0x7f
246 c == '\\'); // Disallow backslashes for future proofing.
247}
248
Will McVickerd7d18df2019-09-12 13:40:50 -0700249bool AidlUnaryConstExpression::IsCompatibleType(Type type, const string& op) {
250 // Verify the unary type here
251 switch (type) {
252 case Type::BOOLEAN: // fall-through
253 case Type::INT8: // fall-through
254 case Type::INT32: // fall-through
255 case Type::INT64:
256 return true;
257 case Type::FLOATING:
258 return (op == "+" || op == "-");
259 default:
260 return false;
261 }
262}
263
264bool AidlBinaryConstExpression::AreCompatibleTypes(Type t1, Type t2) {
265 switch (t1) {
266 case Type::STRING:
267 if (t2 == Type::STRING) {
268 return true;
269 }
270 break;
271 case Type::BOOLEAN: // fall-through
272 case Type::INT8: // fall-through
273 case Type::INT32: // fall-through
274 case Type::INT64:
275 switch (t2) {
276 case Type::BOOLEAN: // fall-through
277 case Type::INT8: // fall-through
278 case Type::INT32: // fall-through
279 case Type::INT64:
280 return true;
281 break;
282 default:
283 break;
284 }
285 break;
286 default:
287 break;
288 }
289
290 return false;
291}
292
293// Returns the promoted kind for both operands
294AidlConstantValue::Type AidlBinaryConstExpression::UsualArithmeticConversion(Type left,
295 Type right) {
296 // These are handled as special cases
Steven Moreland21780812020-09-11 01:29:45 +0000297 AIDL_FATAL_IF(left == Type::STRING || right == Type::STRING, AIDL_LOCATION_HERE);
298 AIDL_FATAL_IF(left == Type::FLOATING || right == Type::FLOATING, AIDL_LOCATION_HERE);
Will McVickerd7d18df2019-09-12 13:40:50 -0700299
300 // Kinds in concern: bool, (u)int[8|32|64]
301 if (left == right) return left; // easy case
302 if (left == Type::BOOLEAN) return right;
303 if (right == Type::BOOLEAN) return left;
304
305 return left < right ? right : left;
306}
307
308// Returns the promoted integral type where INT32 is the smallest type
309AidlConstantValue::Type AidlBinaryConstExpression::IntegralPromotion(Type in) {
310 return (Type::INT32 < in) ? in : Type::INT32;
311}
312
313template <typename T>
314T AidlConstantValue::cast() const {
Steven Moreland21780812020-09-11 01:29:45 +0000315 AIDL_FATAL_IF(!is_evaluated_, this);
Will McVickerd7d18df2019-09-12 13:40:50 -0700316
317#define CASE_CAST_T(__type__) return static_cast<T>(static_cast<__type__>(final_value_));
318
319 SWITCH_KIND(final_type_, CASE_CAST_T, SHOULD_NOT_REACH(); return 0;);
320}
321
Steven Moreland541788d2020-05-21 22:05:52 +0000322AidlConstantValue* AidlConstantValue::Default(const AidlTypeSpecifier& specifier) {
323 AidlLocation location = specifier.GetLocation();
324
325 // allocation of int[0] is a bit wasteful in Java
326 if (specifier.IsArray()) {
327 return nullptr;
328 }
329
330 const std::string name = specifier.GetName();
331 if (name == "boolean") {
332 return Boolean(location, false);
333 }
334 if (name == "byte" || name == "int" || name == "long") {
335 return Integral(location, "0");
336 }
337 if (name == "float") {
338 return Floating(location, "0.0f");
339 }
340 if (name == "double") {
341 return Floating(location, "0.0");
342 }
343 return nullptr;
344}
345
Will McVickerefd970d2019-09-25 15:28:30 -0700346AidlConstantValue* AidlConstantValue::Boolean(const AidlLocation& location, bool value) {
347 return new AidlConstantValue(location, Type::BOOLEAN, value ? "true" : "false");
348}
349
350AidlConstantValue* AidlConstantValue::Character(const AidlLocation& location, char value) {
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800351 const std::string explicit_value = string("'") + value + "'";
Will McVickerefd970d2019-09-25 15:28:30 -0700352 if (!isValidLiteralChar(value)) {
353 AIDL_ERROR(location) << "Invalid character literal " << value;
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800354 return new AidlConstantValue(location, Type::ERROR, explicit_value);
Will McVickerefd970d2019-09-25 15:28:30 -0700355 }
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800356 return new AidlConstantValue(location, Type::CHARACTER, explicit_value);
Will McVickerefd970d2019-09-25 15:28:30 -0700357}
358
359AidlConstantValue* AidlConstantValue::Floating(const AidlLocation& location,
360 const std::string& value) {
361 return new AidlConstantValue(location, Type::FLOATING, value);
362}
363
Will McVickerd7d18df2019-09-12 13:40:50 -0700364bool AidlConstantValue::IsHex(const string& value) {
Steven Morelandcef22662020-07-08 20:54:28 +0000365 return StartsWith(value, "0x") || StartsWith(value, "0X");
Will McVickerefd970d2019-09-25 15:28:30 -0700366}
367
Will McVickerd7d18df2019-09-12 13:40:50 -0700368bool AidlConstantValue::ParseIntegral(const string& value, int64_t* parsed_value,
369 Type* parsed_type) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700370 if (parsed_value == nullptr || parsed_type == nullptr) {
371 return false;
372 }
373
Steven Morelandcef22662020-07-08 20:54:28 +0000374 const bool isLong = EndsWith(value, 'l') || EndsWith(value, 'L');
375 const std::string value_substr = isLong ? value.substr(0, value.size() - 1) : value;
Will McVickerd7d18df2019-09-12 13:40:50 -0700376
Steven Morelandcef22662020-07-08 20:54:28 +0000377 if (IsHex(value)) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700378 // AIDL considers 'const int foo = 0xffffffff' as -1, but if we want to
379 // handle that when computing constant expressions, then we need to
380 // represent 0xffffffff as a uint32_t. However, AIDL only has signed types;
381 // so we parse as an unsigned int when possible and then cast to a signed
382 // int. One example of this is in ICameraService.aidl where a constant int
383 // is used for bit manipulations which ideally should be handled with an
384 // unsigned int.
Steven Morelandcef22662020-07-08 20:54:28 +0000385 //
386 // Note, for historical consistency, we need to consider small hex values
387 // as an integral type. Recognizing them as INT8 could break some files,
388 // even though it would simplify this code.
389 if (uint32_t rawValue32;
390 !isLong && android::base::ParseUint<uint32_t>(value_substr, &rawValue32)) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700391 *parsed_value = static_cast<int32_t>(rawValue32);
392 *parsed_type = Type::INT32;
Steven Morelandcef22662020-07-08 20:54:28 +0000393 } else if (uint64_t rawValue64; android::base::ParseUint<uint64_t>(value_substr, &rawValue64)) {
394 *parsed_value = static_cast<int64_t>(rawValue64);
Will McVickerd7d18df2019-09-12 13:40:50 -0700395 *parsed_type = Type::INT64;
Steven Morelandcef22662020-07-08 20:54:28 +0000396 } else {
397 *parsed_value = 0;
398 *parsed_type = Type::ERROR;
399 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700400 }
401 return true;
402 }
403
Steven Morelandcef22662020-07-08 20:54:28 +0000404 if (!android::base::ParseInt<int64_t>(value_substr, parsed_value)) {
405 *parsed_value = 0;
Will McVickerd7d18df2019-09-12 13:40:50 -0700406 *parsed_type = Type::ERROR;
407 return false;
408 }
409
Steven Morelandcef22662020-07-08 20:54:28 +0000410 if (isLong) {
411 *parsed_type = Type::INT64;
412 } else {
Will McVickerd7d18df2019-09-12 13:40:50 -0700413 // guess literal type.
414 if (*parsed_value <= INT8_MAX && *parsed_value >= INT8_MIN) {
415 *parsed_type = Type::INT8;
416 } else if (*parsed_value <= INT32_MAX && *parsed_value >= INT32_MIN) {
417 *parsed_type = Type::INT32;
418 } else {
419 *parsed_type = Type::INT64;
420 }
421 }
422 return true;
423}
424
425AidlConstantValue* AidlConstantValue::Integral(const AidlLocation& location, const string& value) {
Steven Moreland21780812020-09-11 01:29:45 +0000426 AIDL_FATAL_IF(value.empty(), location);
Will McVickerd7d18df2019-09-12 13:40:50 -0700427
428 Type parsed_type;
429 int64_t parsed_value = 0;
430 bool success = ParseIntegral(value, &parsed_value, &parsed_type);
431 if (!success) {
432 return nullptr;
433 }
434
435 return new AidlConstantValue(location, parsed_type, parsed_value, value);
Will McVickerefd970d2019-09-25 15:28:30 -0700436}
437
438AidlConstantValue* AidlConstantValue::Array(
Will McVickerd7d18df2019-09-12 13:40:50 -0700439 const AidlLocation& location, std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values) {
Steven Moreland21780812020-09-11 01:29:45 +0000440 AIDL_FATAL_IF(values == nullptr, location);
Will McVickerd7d18df2019-09-12 13:40:50 -0700441 return new AidlConstantValue(location, Type::ARRAY, std::move(values));
Will McVickerefd970d2019-09-25 15:28:30 -0700442}
443
Will McVickerd7d18df2019-09-12 13:40:50 -0700444AidlConstantValue* AidlConstantValue::String(const AidlLocation& location, const string& value) {
Will McVickerefd970d2019-09-25 15:28:30 -0700445 for (size_t i = 0; i < value.length(); ++i) {
446 if (!isValidLiteralChar(value[i])) {
447 AIDL_ERROR(location) << "Found invalid character at index " << i << " in string constant '"
448 << value << "'";
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800449 return new AidlConstantValue(location, Type::ERROR, value);
Will McVickerefd970d2019-09-25 15:28:30 -0700450 }
451 }
452
453 return new AidlConstantValue(location, Type::STRING, value);
454}
455
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700456AidlConstantValue* AidlConstantValue::ShallowIntegralCopy(const AidlConstantValue& other) {
Daniel Norman3cce7cd2020-02-07 13:25:12 -0800457 // TODO(b/141313220) Perform a full copy instead of parsing+unparsing
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700458 AidlTypeSpecifier type = AidlTypeSpecifier(AIDL_LOCATION_HERE, "long", false, nullptr, "");
Steven Moreland65606612019-11-10 21:21:25 -0800459 // TODO(b/142722772) CheckValid() should be called before ValueString()
Steven Morelandcdedd9b2019-12-02 10:54:47 -0800460 if (!other.CheckValid() || !other.evaluate(type)) {
Steven Moreland59e53e42019-11-26 20:38:08 -0800461 AIDL_ERROR(other) << "Failed to parse expression as integer: " << other.value_;
462 return nullptr;
463 }
464 const std::string& value = other.ValueString(type, AidlConstantValueDecorator);
465 if (value.empty()) {
466 return nullptr; // error already logged
Daniel Normanb28684e2019-10-17 15:31:39 -0700467 }
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700468
Steven Moreland59e53e42019-11-26 20:38:08 -0800469 AidlConstantValue* result = Integral(AIDL_LOCATION_HERE, value);
Daniel Normanf0ca44f2019-10-25 09:59:44 -0700470 if (result == nullptr) {
471 AIDL_FATAL(other) << "Unable to perform ShallowIntegralCopy.";
472 }
473 return result;
Daniel Normanb28684e2019-10-17 15:31:39 -0700474}
475
Will McVickerd7d18df2019-09-12 13:40:50 -0700476string AidlConstantValue::ValueString(const AidlTypeSpecifier& type,
477 const ConstantValueDecorator& decorator) const {
Will McVickerefd970d2019-09-25 15:28:30 -0700478 if (type.IsGeneric()) {
479 AIDL_ERROR(type) << "Generic type cannot be specified with a constant literal.";
480 return "";
481 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700482 if (!is_evaluated_) {
483 // TODO(b/142722772) CheckValid() should be called before ValueString()
484 bool success = CheckValid();
485 success &= evaluate(type);
486 if (!success) {
487 // the detailed error message shall be printed in evaluate
488 return "";
489 }
Will McVickerefd970d2019-09-25 15:28:30 -0700490 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700491 if (!is_valid_) {
492 AIDL_ERROR(this) << "Invalid constant value: " + value_;
493 return "";
494 }
495 const string& type_string = type.GetName();
496 int err = 0;
Will McVickerefd970d2019-09-25 15:28:30 -0700497
Will McVickerd7d18df2019-09-12 13:40:50 -0700498 switch (final_type_) {
499 case Type::CHARACTER:
500 if (type_string == "char") {
501 return decorator(type, final_string_value_);
502 }
503 err = -1;
504 break;
505 case Type::STRING:
506 if (type_string == "String") {
507 return decorator(type, final_string_value_);
508 }
509 err = -1;
510 break;
511 case Type::BOOLEAN: // fall-through
512 case Type::INT8: // fall-through
513 case Type::INT32: // fall-through
514 case Type::INT64:
515 if (type_string == "byte") {
516 if (final_value_ > INT8_MAX || final_value_ < INT8_MIN) {
517 err = -1;
518 break;
519 }
520 return decorator(type, std::to_string(static_cast<int8_t>(final_value_)));
521 } else if (type_string == "int") {
522 if (final_value_ > INT32_MAX || final_value_ < INT32_MIN) {
523 err = -1;
524 break;
525 }
526 return decorator(type, std::to_string(static_cast<int32_t>(final_value_)));
527 } else if (type_string == "long") {
528 return decorator(type, std::to_string(final_value_));
529 } else if (type_string == "boolean") {
530 return decorator(type, final_value_ ? "true" : "false");
531 }
532 err = -1;
533 break;
534 case Type::ARRAY: {
535 if (!type.IsArray()) {
536 err = -1;
537 break;
538 }
539 vector<string> value_strings;
540 value_strings.reserve(values_.size());
Will McVickerefd970d2019-09-25 15:28:30 -0700541 bool success = true;
Will McVickerd7d18df2019-09-12 13:40:50 -0700542
Will McVickerefd970d2019-09-25 15:28:30 -0700543 for (const auto& value : values_) {
544 const AidlTypeSpecifier& array_base = type.ArrayBase();
Will McVickerd7d18df2019-09-12 13:40:50 -0700545 const string value_string = value->ValueString(array_base, decorator);
546 if (value_string.empty()) {
547 success = false;
548 break;
549 }
550 value_strings.push_back(value_string);
Will McVickerefd970d2019-09-25 15:28:30 -0700551 }
552 if (!success) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700553 err = -1;
554 break;
Will McVickerefd970d2019-09-25 15:28:30 -0700555 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700556
557 return decorator(type, "{" + Join(value_strings, ", ") + "}");
Will McVickerefd970d2019-09-25 15:28:30 -0700558 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700559 case Type::FLOATING: {
560 std::string_view raw_view(value_.c_str());
561 bool is_float_literal = ConsumeSuffix(&raw_view, "f");
562 std::string stripped_value = std::string(raw_view);
Will McVickerefd970d2019-09-25 15:28:30 -0700563
564 if (type_string == "double") {
565 double parsed_value;
Will McVickerd7d18df2019-09-12 13:40:50 -0700566 if (!android::base::ParseDouble(stripped_value, &parsed_value)) {
567 AIDL_ERROR(this) << "Could not parse " << value_;
568 err = -1;
569 break;
570 }
Will McVickerefd970d2019-09-25 15:28:30 -0700571 return decorator(type, std::to_string(parsed_value));
572 }
573 if (is_float_literal && type_string == "float") {
574 float parsed_value;
Will McVickerd7d18df2019-09-12 13:40:50 -0700575 if (!android::base::ParseFloat(stripped_value, &parsed_value)) {
576 AIDL_ERROR(this) << "Could not parse " << value_;
577 err = -1;
578 break;
579 }
Will McVickerefd970d2019-09-25 15:28:30 -0700580 return decorator(type, std::to_string(parsed_value) + "f");
581 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700582 err = -1;
583 break;
Will McVickerefd970d2019-09-25 15:28:30 -0700584 }
Will McVickerefd970d2019-09-25 15:28:30 -0700585 default:
Will McVickerd7d18df2019-09-12 13:40:50 -0700586 err = -1;
587 break;
Will McVickerefd970d2019-09-25 15:28:30 -0700588 }
589
Steven Moreland21780812020-09-11 01:29:45 +0000590 AIDL_FATAL_IF(err == 0, this);
Will McVickerd7d18df2019-09-12 13:40:50 -0700591 AIDL_ERROR(this) << "Invalid type specifier for " << ToString(final_type_) << ": " << type_string;
Will McVickerefd970d2019-09-25 15:28:30 -0700592 return "";
Will McVickerd7d18df2019-09-12 13:40:50 -0700593}
594
595bool AidlConstantValue::CheckValid() const {
596 // Nothing needs to be checked here. The constant value will be validated in
597 // the constructor or in the evaluate() function.
598 if (is_evaluated_) return is_valid_;
599
600 switch (type_) {
601 case Type::BOOLEAN: // fall-through
602 case Type::INT8: // fall-through
603 case Type::INT32: // fall-through
604 case Type::INT64: // fall-through
605 case Type::ARRAY: // fall-through
606 case Type::CHARACTER: // fall-through
607 case Type::STRING: // fall-through
608 case Type::FLOATING: // fall-through
609 case Type::UNARY: // fall-through
610 case Type::BINARY:
611 is_valid_ = true;
612 break;
Steven Moreland4ff04aa2019-12-02 10:44:29 -0800613 case Type::ERROR:
614 return false;
Will McVickerd7d18df2019-09-12 13:40:50 -0700615 default:
616 AIDL_FATAL(this) << "Unrecognized constant value type: " << ToString(type_);
617 return false;
618 }
619
620 return true;
621}
622
623bool AidlConstantValue::evaluate(const AidlTypeSpecifier& type) const {
624 if (is_evaluated_) {
625 return is_valid_;
626 }
627 int err = 0;
628 is_evaluated_ = true;
629
630 switch (type_) {
631 case Type::ARRAY: {
632 if (!type.IsArray()) {
633 AIDL_ERROR(this) << "Invalid constant array type: " << type.GetName();
634 err = -1;
635 break;
636 }
637 Type array_type = Type::ERROR;
638 bool success = true;
639 for (const auto& value : values_) {
640 success = value->CheckValid();
641 if (success) {
642 success = value->evaluate(type.ArrayBase());
643 if (!success) {
644 AIDL_ERROR(this) << "Invalid array element: " << value->value_;
645 break;
646 }
647 if (array_type == Type::ERROR) {
648 array_type = value->final_type_;
649 } else if (!AidlBinaryConstExpression::AreCompatibleTypes(array_type,
650 value->final_type_)) {
651 AIDL_ERROR(this) << "Incompatible array element type: " << ToString(value->final_type_)
652 << ". Expecting type compatible with " << ToString(array_type);
653 success = false;
654 break;
655 }
656 } else {
657 break;
658 }
659 }
660 if (!success) {
661 err = -1;
662 break;
663 }
664 final_type_ = type_;
665 break;
666 }
667 case Type::BOOLEAN:
668 if ((value_ != "true") && (value_ != "false")) {
669 AIDL_ERROR(this) << "Invalid constant boolean value: " << value_;
670 err = -1;
671 break;
672 }
673 final_value_ = (value_ == "true") ? 1 : 0;
674 final_type_ = type_;
675 break;
676 case Type::INT8: // fall-through
677 case Type::INT32: // fall-through
678 case Type::INT64:
679 // Parsing happens in the constructor
680 final_type_ = type_;
681 break;
682 case Type::CHARACTER: // fall-through
683 case Type::STRING:
684 final_string_value_ = value_;
685 final_type_ = type_;
686 break;
687 case Type::FLOATING:
688 // Just parse on the fly in ValueString
689 final_type_ = type_;
690 break;
691 default:
692 AIDL_FATAL(this) << "Unrecognized constant value type: " << ToString(type_);
693 err = -1;
694 }
695
696 return (err == 0) ? true : false;
Will McVickerefd970d2019-09-25 15:28:30 -0700697}
698
699string AidlConstantValue::ToString(Type type) {
700 switch (type) {
Will McVickerefd970d2019-09-25 15:28:30 -0700701 case Type::BOOLEAN:
702 return "a literal boolean";
Will McVickerd7d18df2019-09-12 13:40:50 -0700703 case Type::INT8:
704 return "an int8 literal";
705 case Type::INT32:
706 return "an int32 literal";
707 case Type::INT64:
708 return "an int64 literal";
Steven Morelanda923a722019-11-26 20:08:30 -0800709 case Type::ARRAY:
710 return "a literal array";
711 case Type::CHARACTER:
712 return "a literal char";
Will McVickerefd970d2019-09-25 15:28:30 -0700713 case Type::STRING:
714 return "a literal string";
Steven Morelanda923a722019-11-26 20:08:30 -0800715 case Type::FLOATING:
716 return "a literal float";
Will McVickerd7d18df2019-09-12 13:40:50 -0700717 case Type::UNARY:
718 return "a unary expression";
719 case Type::BINARY:
720 return "a binary expression";
Steven Morelanda923a722019-11-26 20:08:30 -0800721 case Type::ERROR:
Steven Moreland21780812020-09-11 01:29:45 +0000722 AIDL_FATAL(AIDL_LOCATION_HERE) << "aidl internal error: error type failed to halt program";
Steven Morelanda923a722019-11-26 20:08:30 -0800723 return "";
Will McVickerefd970d2019-09-25 15:28:30 -0700724 default:
Steven Moreland21780812020-09-11 01:29:45 +0000725 AIDL_FATAL(AIDL_LOCATION_HERE)
726 << "aidl internal error: unknown constant type: " << static_cast<int>(type);
Will McVickerefd970d2019-09-25 15:28:30 -0700727 return ""; // not reached
728 }
729}
730
Will McVickerd7d18df2019-09-12 13:40:50 -0700731bool AidlUnaryConstExpression::CheckValid() const {
732 if (is_evaluated_) return is_valid_;
Steven Moreland21780812020-09-11 01:29:45 +0000733 AIDL_FATAL_IF(unary_ == nullptr, this);
Will McVickerd7d18df2019-09-12 13:40:50 -0700734
735 is_valid_ = unary_->CheckValid();
736 if (!is_valid_) {
737 final_type_ = Type::ERROR;
738 return false;
739 }
740
Steven Moreland4bcb05c2019-11-27 18:57:47 -0800741 return AidlConstantValue::CheckValid();
Will McVickerd7d18df2019-09-12 13:40:50 -0700742}
743
744bool AidlUnaryConstExpression::evaluate(const AidlTypeSpecifier& type) const {
745 if (is_evaluated_) {
746 return is_valid_;
747 }
748 is_evaluated_ = true;
749
750 // Recursively evaluate the expression tree
751 if (!unary_->is_evaluated_) {
752 // TODO(b/142722772) CheckValid() should be called before ValueString()
753 bool success = CheckValid();
754 success &= unary_->evaluate(type);
755 if (!success) {
756 is_valid_ = false;
757 return false;
758 }
759 }
Devin Moorec233fb82020-04-07 11:13:44 -0700760 if (!IsCompatibleType(unary_->final_type_, op_)) {
761 AIDL_ERROR(unary_) << "'" << op_ << "'"
762 << " is not compatible with " << ToString(unary_->final_type_)
763 << ": " + value_;
764 is_valid_ = false;
765 return false;
766 }
767 if (!unary_->is_valid_) {
768 AIDL_ERROR(unary_) << "Invalid constant unary expression: " + value_;
Will McVickerd7d18df2019-09-12 13:40:50 -0700769 is_valid_ = false;
770 return false;
771 }
772 final_type_ = unary_->final_type_;
773
774 if (final_type_ == Type::FLOATING) {
775 // don't do anything here. ValueString() will handle everything.
776 is_valid_ = true;
777 return true;
778 }
779
Steven Morelande1ff67e2020-07-16 23:22:36 +0000780#define CASE_UNARY(__type__) \
781 return handleUnary(*this, op_, static_cast<__type__>(unary_->final_value_), &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700782
783 SWITCH_KIND(final_type_, CASE_UNARY, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
784 is_valid_ = false; return false;)
785}
786
Will McVickerd7d18df2019-09-12 13:40:50 -0700787bool AidlBinaryConstExpression::CheckValid() const {
788 bool success = false;
789 if (is_evaluated_) return is_valid_;
Steven Moreland21780812020-09-11 01:29:45 +0000790 AIDL_FATAL_IF(left_val_ == nullptr, this);
791 AIDL_FATAL_IF(right_val_ == nullptr, this);
Will McVickerd7d18df2019-09-12 13:40:50 -0700792
793 success = left_val_->CheckValid();
794 if (!success) {
795 final_type_ = Type::ERROR;
796 AIDL_ERROR(this) << "Invalid left operand in binary expression: " + value_;
797 }
798
799 success = right_val_->CheckValid();
800 if (!success) {
801 AIDL_ERROR(this) << "Invalid right operand in binary expression: " + value_;
802 final_type_ = Type::ERROR;
803 }
804
805 if (final_type_ == Type::ERROR) {
806 is_valid_ = false;
807 return false;
808 }
809
810 is_valid_ = true;
Steven Moreland4bcb05c2019-11-27 18:57:47 -0800811 return AidlConstantValue::CheckValid();
Will McVickerd7d18df2019-09-12 13:40:50 -0700812}
813
814bool AidlBinaryConstExpression::evaluate(const AidlTypeSpecifier& type) const {
815 if (is_evaluated_) {
816 return is_valid_;
817 }
818 is_evaluated_ = true;
Steven Moreland21780812020-09-11 01:29:45 +0000819 AIDL_FATAL_IF(left_val_ == nullptr, type);
820 AIDL_FATAL_IF(right_val_ == nullptr, type);
Will McVickerd7d18df2019-09-12 13:40:50 -0700821
822 // Recursively evaluate the binary expression tree
823 if (!left_val_->is_evaluated_ || !right_val_->is_evaluated_) {
824 // TODO(b/142722772) CheckValid() should be called before ValueString()
825 bool success = CheckValid();
826 success &= left_val_->evaluate(type);
827 success &= right_val_->evaluate(type);
828 if (!success) {
829 is_valid_ = false;
830 return false;
831 }
832 }
833 if (!left_val_->is_valid_ || !right_val_->is_valid_) {
834 is_valid_ = false;
835 return false;
836 }
837 is_valid_ = AreCompatibleTypes(left_val_->final_type_, right_val_->final_type_);
838 if (!is_valid_) {
Steven Moreland1f9f2212020-09-24 18:20:15 +0000839 AIDL_ERROR(this) << "Cannot perform operation '" << op_ << "' on "
840 << ToString(right_val_->GetType()) << " and " << ToString(left_val_->GetType())
841 << ".";
Will McVickerd7d18df2019-09-12 13:40:50 -0700842 return false;
843 }
844
845 bool isArithmeticOrBitflip = OP_IS_BIN_ARITHMETIC || OP_IS_BIN_BITFLIP;
846
847 // Handle String case first
848 if (left_val_->final_type_ == Type::STRING) {
Steven Moreland22e36112020-10-01 00:50:45 +0000849 AIDL_FATAL_IF(right_val_->final_type_ != Type::STRING, this);
Will McVickerd7d18df2019-09-12 13:40:50 -0700850 if (!OPEQ("+")) {
Steven Moreland22e36112020-10-01 00:50:45 +0000851 AIDL_ERROR(this) << "Only '+' is supported for strings, not '" << op_ << "'.";
Will McVickerd7d18df2019-09-12 13:40:50 -0700852 final_type_ = Type::ERROR;
853 is_valid_ = false;
854 return false;
855 }
856
857 // Remove trailing " from lhs
858 const string& lhs = left_val_->final_string_value_;
859 if (lhs.back() != '"') {
860 AIDL_ERROR(this) << "'" << lhs << "' is missing a trailing quote.";
861 final_type_ = Type::ERROR;
862 is_valid_ = false;
863 return false;
864 }
865 const string& rhs = right_val_->final_string_value_;
866 // Remove starting " from rhs
867 if (rhs.front() != '"') {
868 AIDL_ERROR(this) << "'" << rhs << "' is missing a leading quote.";
869 final_type_ = Type::ERROR;
870 is_valid_ = false;
871 return false;
872 }
873
874 final_string_value_ = string(lhs.begin(), lhs.end() - 1).append(rhs.begin() + 1, rhs.end());
875 final_type_ = Type::STRING;
876 return true;
877 }
878
Will McVickerd7d18df2019-09-12 13:40:50 -0700879 // CASE: + - * / % | ^ & < > <= >= == !=
880 if (isArithmeticOrBitflip || OP_IS_BIN_COMP) {
Will McVickerd7d18df2019-09-12 13:40:50 -0700881 // promoted kind for both operands.
882 Type promoted = UsualArithmeticConversion(IntegralPromotion(left_val_->final_type_),
883 IntegralPromotion(right_val_->final_type_));
884 // result kind.
885 final_type_ = isArithmeticOrBitflip
886 ? promoted // arithmetic or bitflip operators generates promoted type
887 : Type::BOOLEAN; // comparison operators generates bool
888
Steven Morelande1ff67e2020-07-16 23:22:36 +0000889#define CASE_BINARY_COMMON(__type__) \
890 return handleBinaryCommon(*this, static_cast<__type__>(left_val_->final_value_), op_, \
891 static_cast<__type__>(right_val_->final_value_), &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700892
893 SWITCH_KIND(promoted, CASE_BINARY_COMMON, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
894 is_valid_ = false; return false;)
895 }
896
897 // CASE: << >>
898 string newOp = op_;
899 if (OP_IS_BIN_SHIFT) {
Devin Moore04823022020-09-11 10:43:35 -0700900 // promoted kind for both operands.
901 final_type_ = UsualArithmeticConversion(IntegralPromotion(left_val_->final_type_),
902 IntegralPromotion(right_val_->final_type_));
903 auto numBits = right_val_->final_value_;
Will McVickerd7d18df2019-09-12 13:40:50 -0700904 if (numBits < 0) {
Steven Moreland74d3f552020-02-04 15:57:50 -0800905 // shifting with negative number of bits is undefined in C. In AIDL it
Will McVickerd7d18df2019-09-12 13:40:50 -0700906 // is defined as shifting into the other direction.
907 newOp = OPEQ("<<") ? ">>" : "<<";
908 numBits = -numBits;
909 }
910
Devin Moore04823022020-09-11 10:43:35 -0700911#define CASE_SHIFT(__type__) \
912 return handleShift(*this, static_cast<__type__>(left_val_->final_value_), newOp, \
913 static_cast<__type__>(numBits), &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700914
915 SWITCH_KIND(final_type_, CASE_SHIFT, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
916 is_valid_ = false; return false;)
917 }
918
919 // CASE: && ||
920 if (OP_IS_BIN_LOGICAL) {
921 final_type_ = Type::BOOLEAN;
922 // easy; everything is bool.
Steven Morelande1ff67e2020-07-16 23:22:36 +0000923 return handleLogical(*this, left_val_->final_value_, op_, right_val_->final_value_,
924 &final_value_);
Will McVickerd7d18df2019-09-12 13:40:50 -0700925 }
926
927 SHOULD_NOT_REACH();
928 is_valid_ = false;
929 return false;
930}
931
Will McVickerd7d18df2019-09-12 13:40:50 -0700932AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type parsed_type,
933 int64_t parsed_value, const string& checked_value)
934 : AidlNode(location),
935 type_(parsed_type),
936 value_(checked_value),
Will McVickerd7d18df2019-09-12 13:40:50 -0700937 final_type_(parsed_type),
938 final_value_(parsed_value) {
Steven Moreland21780812020-09-11 01:29:45 +0000939 AIDL_FATAL_IF(value_.empty() && type_ != Type::ERROR, location);
940 AIDL_FATAL_IF(type_ != Type::INT8 && type_ != Type::INT32 && type_ != Type::INT64, location);
Will McVickerd7d18df2019-09-12 13:40:50 -0700941}
Will McVickerefd970d2019-09-25 15:28:30 -0700942
943AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type type,
Will McVickerd7d18df2019-09-12 13:40:50 -0700944 const string& checked_value)
945 : AidlNode(location),
946 type_(type),
947 value_(checked_value),
Will McVickerd7d18df2019-09-12 13:40:50 -0700948 final_type_(type) {
Steven Moreland21780812020-09-11 01:29:45 +0000949 AIDL_FATAL_IF(value_.empty() && type_ != Type::ERROR, location);
Will McVickerd7d18df2019-09-12 13:40:50 -0700950 switch (type_) {
951 case Type::INT8:
952 case Type::INT32:
953 case Type::INT64:
954 case Type::ARRAY:
955 AIDL_FATAL(this) << "Invalid type: " << ToString(type_);
956 break;
957 default:
958 break;
959 }
960}
961
962AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type type,
963 std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values)
964 : AidlNode(location),
965 type_(type),
966 values_(std::move(*values)),
967 is_valid_(false),
968 is_evaluated_(false),
969 final_type_(type) {
Steven Moreland21780812020-09-11 01:29:45 +0000970 AIDL_FATAL_IF(type_ != Type::ARRAY, location);
Will McVickerd7d18df2019-09-12 13:40:50 -0700971}
972
973AidlUnaryConstExpression::AidlUnaryConstExpression(const AidlLocation& location, const string& op,
974 std::unique_ptr<AidlConstantValue> rval)
975 : AidlConstantValue(location, Type::UNARY, op + rval->value_),
976 unary_(std::move(rval)),
977 op_(op) {
978 final_type_ = Type::UNARY;
979}
980
981AidlBinaryConstExpression::AidlBinaryConstExpression(const AidlLocation& location,
982 std::unique_ptr<AidlConstantValue> lval,
983 const string& op,
984 std::unique_ptr<AidlConstantValue> rval)
985 : AidlConstantValue(location, Type::BINARY, lval->value_ + op + rval->value_),
986 left_val_(std::move(lval)),
987 right_val_(std::move(rval)),
988 op_(op) {
989 final_type_ = Type::BINARY;
Will McVickerefd970d2019-09-25 15:28:30 -0700990}