1 // Copyright (c) 2015-2016 The Khronos Group Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef LIBSPIRV_DIAGNOSTIC_H_ 16 #define LIBSPIRV_DIAGNOSTIC_H_ 17 18 #include <sstream> 19 #include <string> 20 21 #include "spirv-tools/libspirv.hpp" 22 23 namespace libspirv { 24 25 // A DiagnosticStream remembers the current position of the input and an error 26 // code, and captures diagnostic messages via the left-shift operator. 27 // If the error code is not SPV_FAILED_MATCH, then captured messages are 28 // emitted during the destructor. 29 class DiagnosticStream { 30 public: DiagnosticStream(spv_position_t position,const spvtools::MessageConsumer & consumer,spv_result_t error)31 DiagnosticStream(spv_position_t position, 32 const spvtools::MessageConsumer& consumer, 33 spv_result_t error) 34 : position_(position), consumer_(consumer), error_(error) {} 35 DiagnosticStream(DiagnosticStream && other)36 DiagnosticStream(DiagnosticStream&& other) 37 : stream_(other.stream_.str()), 38 position_(other.position_), 39 consumer_(other.consumer_), 40 error_(other.error_) {} 41 42 ~DiagnosticStream(); 43 44 // Adds the given value to the diagnostic message to be written. 45 template <typename T> 46 DiagnosticStream& operator<<(const T& val) { 47 stream_ << val; 48 return *this; 49 } 50 51 // Conversion operator to spv_result, returning the error code. spv_result_t()52 operator spv_result_t() { return error_; } 53 54 private: 55 std::stringstream stream_; 56 spv_position_t position_; 57 const spvtools::MessageConsumer& consumer_; // Message consumer callback. 58 spv_result_t error_; 59 }; 60 61 // Changes the MessageConsumer in |context| to one that updates |diagnostic| 62 // with the last message received. 63 // 64 // This function expects that |diagnostic| is not nullptr and its content is a 65 // nullptr. 66 void UseDiagnosticAsMessageConsumer(spv_context context, 67 spv_diagnostic* diagnostic); 68 69 std::string spvResultToString(spv_result_t res); 70 71 } // namespace libspirv 72 73 #endif // LIBSPIRV_DIAGNOSTIC_H_ 74