1 /* 2 * Copyright (C) 2015, 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 17 #pragma once 18 19 #include <iostream> 20 #include <memory> 21 #include <string> 22 23 #include "location.h" 24 25 class AidlNode; 26 27 // Generic point for printing any error in the AIDL compiler. 28 class AidlErrorLog { 29 public: 30 enum Severity { NO_OP, WARNING, ERROR, FATAL }; 31 32 AidlErrorLog(Severity severity, const AidlLocation& location, const std::string& suffix = ""); 33 AidlErrorLog(Severity severity, const std::string& filename); 34 AidlErrorLog(Severity severity, const AidlNode& node); AidlErrorLog(Severity severity,const AidlNode * node)35 AidlErrorLog(Severity severity, const AidlNode* node) : AidlErrorLog(severity, *node) {} 36 37 template <typename T> AidlErrorLog(Severity severity,const std::unique_ptr<T> & node)38 AidlErrorLog(Severity severity, const std::unique_ptr<T>& node) : AidlErrorLog(severity, *node) {} 39 ~AidlErrorLog(); 40 41 // AidlErrorLog is a single use object. No need to copy 42 AidlErrorLog(const AidlErrorLog&) = delete; 43 AidlErrorLog& operator=(const AidlErrorLog&) = delete; 44 45 // btw, making it movable so that functions can return it. 46 AidlErrorLog(AidlErrorLog&&) = default; 47 AidlErrorLog& operator=(AidlErrorLog&&) = delete; 48 49 template <typename T> 50 AidlErrorLog& operator<<(T&& arg) { 51 if (severity_ != NO_OP) { 52 (*os_) << std::forward<T>(arg); 53 } 54 return *this; 55 } 56 clearError()57 static void clearError() { sHadError = false; } hadError()58 static bool hadError() { return sHadError; } 59 60 private: 61 std::ostream* os_; 62 Severity severity_; 63 const AidlLocation location_; 64 const std::string suffix_; 65 static bool sHadError; 66 }; 67 68 // A class used to make it obvious to clang that code is going to abort. This 69 // informs static analyses of the aborting behavior of `AIDL_FATAL`, and 70 // helps generate slightly faster/smaller code. 71 class AidlAbortOnDestruction { 72 public: ~AidlAbortOnDestruction()73 __attribute__((noreturn)) ~AidlAbortOnDestruction() { abort(); } 74 }; 75 76 #define AIDL_ERROR(CONTEXT) ::AidlErrorLog(AidlErrorLog::ERROR, (CONTEXT)) 77 #define AIDL_FATAL(CONTEXT) \ 78 (::AidlAbortOnDestruction(), ::AidlErrorLog(AidlErrorLog::FATAL, (CONTEXT))) 79 #define AIDL_FATAL_IF(CONDITION, CONTEXT) \ 80 if (CONDITION) AIDL_FATAL(CONTEXT) << "Bad internal state: " << #CONDITION << ": " 81