error-reporter.c++ (2283B)
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors 2 // Licensed under the MIT License: 3 // 4 // Permission is hereby granted, free of charge, to any person obtaining a copy 5 // of this software and associated documentation files (the "Software"), to deal 6 // in the Software without restriction, including without limitation the rights 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 // copies of the Software, and to permit persons to whom the Software is 9 // furnished to do so, subject to the following conditions: 10 // 11 // The above copyright notice and this permission notice shall be included in 12 // all copies or substantial portions of the Software. 13 // 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 // THE SOFTWARE. 21 22 #include "error-reporter.h" 23 #include <kj/debug.h> 24 25 namespace capnp { 26 namespace compiler { 27 28 namespace { 29 30 template <typename T> 31 static size_t findLargestElementBefore(const kj::Vector<T>& vec, const T& key) { 32 KJ_REQUIRE(vec.size() > 0 && vec[0] <= key); 33 34 size_t lower = 0; 35 size_t upper = vec.size(); 36 37 while (upper - lower > 1) { 38 size_t mid = (lower + upper) / 2; 39 if (vec[mid] > key) { 40 upper = mid; 41 } else { 42 lower = mid; 43 } 44 } 45 46 return lower; 47 } 48 49 } // namespace 50 51 LineBreakTable::LineBreakTable(kj::ArrayPtr<const char> content) 52 : lineBreaks(content.size() / 40) { 53 lineBreaks.add(0); 54 for (const char* pos = content.begin(); pos < content.end(); ++pos) { 55 if (*pos == '\n') { 56 lineBreaks.add(pos + 1 - content.begin()); 57 } 58 } 59 } 60 61 GlobalErrorReporter::SourcePos LineBreakTable::toSourcePos(uint32_t byteOffset) const { 62 uint line = findLargestElementBefore(lineBreaks, byteOffset); 63 uint col = byteOffset - lineBreaks[line]; 64 return GlobalErrorReporter::SourcePos { byteOffset, line, col }; 65 } 66 67 } // namespace compiler 68 } // namespace capnp