1 /** 2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd. 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 16 #include "sourceLocation.h" 17 18 #include <lexer/token/letters.h> 19 20 #include <cstdint> 21 22 namespace panda::es2panda::lexer { 23 AddCol(size_t offset)24void OffsetEntry::AddCol(size_t offset) 25 { 26 size_t diff = offset - offset_; 27 offset_ = offset; 28 29 if (ranges.empty()) { 30 ranges.emplace_back(Range {diff}); 31 return; 32 } 33 34 auto &range = ranges.back(); 35 36 if (diff == range.byteSize) { 37 range.cnt++; 38 } else { 39 ranges.emplace_back(Range {diff}); 40 } 41 } 42 LineIndex(const util::StringView & source)43LineIndex::LineIndex(const util::StringView &source) noexcept 44 { 45 auto iter = util::StringView::Iterator(source); 46 entrys_.emplace_back(0); 47 48 while (true) { 49 switch (iter.Next()) { 50 case util::StringView::Iterator::INVALID_CP: { 51 return; 52 } 53 case LEX_CHAR_CR: { 54 if (iter.HasNext() && iter.Peek() == LEX_CHAR_LF) { 55 iter.Forward(1); 56 } 57 58 [[fallthrough]]; 59 } 60 case LEX_CHAR_LF: 61 case LEX_CHAR_PS: 62 case LEX_CHAR_LS: { 63 entrys_.emplace_back(iter.Index()); 64 break; 65 } 66 default: { 67 entrys_.back().AddCol(iter.Index()); 68 } 69 } 70 } 71 } 72 GetLocation(SourcePosition pos)73SourceLocation LineIndex::GetLocation(SourcePosition pos) noexcept 74 { 75 size_t line = pos.line; 76 77 size_t col = 0; 78 const auto &entry = entrys_[pos.line]; 79 size_t diff = pos.index - entry.lineStart; 80 81 for (const auto &range : entry.ranges) { 82 if (diff < (range.cnt * range.byteSize)) { 83 col += (diff / range.byteSize) ; 84 break; 85 } 86 87 diff -= range.cnt * range.byteSize; 88 col += range.cnt; 89 } 90 91 return SourceLocation(line + 1, col + 1); 92 } 93 94 } // namespace panda::es2panda::lexer 95