| #include <algorithm> |
| 6 |
| 7 | SyntaxHighlighter::SyntaxHighlighter(const std::string &path) { |
| 8 | m_tree = std::make_shared<LanguageTree>(); |
| 9 | m_tree->load(path); |
| 10 | } |
| 11 |
| 12 | TokenList SyntaxHighlighter::tokenize(const std::string &text, |
| 13 | const std::string &language) const { |
| 14 | const Grammar *grammar = m_tree->find(language); |
| 15 | const Grammar *fixed = nullptr; |
| 16 |
| 17 | // "<host>-<language>", as "diff-cs": the embedded-language tokens of <host> |
| 18 | // hold code in <language>. Both may have dashes of their own, so every split |
| 19 | // is tried. When no <language> resolves, <host> still highlights, finding |
| 20 | // the language in the text if it can. |
| 21 | if (!grammar) { |
| 22 | const Grammar *host = nullptr; |
| 23 |
| 24 | for (size_t split = language.find('-'); split != std::string::npos; |
| 25 | split = language.find('-', split + 1)) { |
| 26 | const Grammar *prefix = m_tree->find(language.substr(0, split)); |
| 27 | if (!prefix) { |
| 28 | continue; |
| 29 | } |
| 30 |
| 31 | if (const Grammar *suffix = m_tree->find(language.substr(split + 1))) { |
| 32 | grammar = prefix; |
| 33 | fixed = suffix; |
| 34 | break; |
| 35 | } |
| 36 |
| 37 | if (!host) { |
| 38 | host = prefix; |
| 39 | } |
| 40 | } |
| 41 |
| 42 | if (!grammar) { |
| 43 | grammar = host; |
| 44 | } |
| 45 | } |
| 46 |
| 47 | if (!grammar) { |
| 48 | return TokenList(text); |
| 49 | } |
| 50 |
| 51 | // Code takes under 8 regex searches a byte in every language measured. A text |
| 52 | // that makes the rematching superlinear runs out instead, at the same point |
| 53 | // on every device, and keeps the tokens found until then. |
| 54 | constexpr size_t kSearchesPerByte = 64; |
| 55 | constexpr size_t kSearchesAtLeast = 1024; |
| 56 |
| 57 | const Grammar *named = nullptr; |
| 58 | State state; |
| 59 | state.searchesLeft = kSearchesPerByte * text.size() + kSearchesAtLeast; |
| 60 | TokenList tokenList = tokenize(state, text, grammar); |
| 61 | try { |
| 62 | highlightEmbedded(state, tokenList, 0, text, fixed, named); |
| 63 | } catch (...) { |
| 64 | } |
| 65 | return tokenList; |
| 66 | } |
| 67 |
| 68 | namespace { |
| 69 | constexpr std::string_view kEmbeddedLanguage = "embedded-language"; |
| 70 | constexpr std::string_view kEmbeddedLanguageName = "embedded-language-name"; |
| 71 |
| 72 | struct SliceCursor { |
| 73 | const TokenList *list; |
| 74 | TokenListPtr node; |
| 75 | size_t pos; |
| 76 | }; |
| 77 |
| 78 | // Appends to `out` the part of `tokens` between `from` and `to`, given in the |
| 79 | // text `tokens` was made from, as views of the same characters in `text`, |
| 80 | // where `from` sits at `offset`. A token crossing either end is cut there, so |
| 81 | // a multiline comment comes out once per line. |
| 82 | // |
| 83 | // The slices of one run are taken in order, so `cursors` keeps, for each |
| 84 | // depth, the node the last one stopped at: a slice costs the tokens it holds, |
| 85 | // not every token before it. |
| 86 | TokenListPtr appendSlice(TokenList &out, TokenListPtr tail, |
| 87 | const TokenList &tokens, size_t pos, size_t from, |
| 88 | size_t to, std::string_view text, size_t offset, |
| 89 | std::vector<SliceCursor> &cursors, size_t depth) { |
| 90 | if (cursors.size() == depth) { |
| 91 | cursors.push_back({nullptr, nullptr, 0}); |
| 92 | } |
| 93 |
| 94 | if (cursors[depth].list != &tokens) { |
| 95 | cursors[depth] = {&tokens, tokens.head->next, pos}; |
| 96 | } |
| 97 |
| 98 | TokenListPtr node = cursors[depth].node; |
| 99 | pos = cursors[depth].pos; |
| 100 |
| 101 | while (node != tokens.head && pos < to) { |
| 102 | const size_t length = node->length(); |
| 103 | const size_t start = std::max(pos, from); |
| 104 | const size_t end = std::min(pos + length, to); |
| 105 |
| 106 | if (start < end) { |
| 107 | if (node->isSyntax()) { |
| 108 | const auto &syntax = static_cast<const Syntax &>(*node); |
| 109 |
| 110 | TokenList children; |
| 111 | appendSlice(children, children.head, syntax.children(), pos, start, end, |
| 112 | text, offset + (start - from), cursors, depth + 1); |
| 113 |
| 114 | tail = out.addAfter(tail, syntax.type(), std::move(children), |
| 115 | syntax.alias(), end - start); |
| 116 | } else { |
| 117 | tail = out.addAfter(tail, text.substr(offset + (start - from), end - start)); |
| 118 | } |
| 119 | } |
| 120 |
| 121 | // It runs on into the next slice, which starts with it. |
| 122 | if (pos + length > to) { |
| 123 | break; |
| 124 | } |
| 125 |
| 126 | pos += length; |
| 127 | node = node->next; |
| 128 | } |
| 129 |
| 130 | cursors[depth].node = node; |
| 131 | cursors[depth].pos = pos; |
| 132 | return tail; |
| 133 | } |
| 134 | } // namespace |
| 135 |
| 136 | // `fixed` is the language the caller named, which wins over any the text |
| 137 | // names. Otherwise an embedded-language-name token, as a diff's file name, |
| 138 | // sets `named` for the parts after it, in whichever parent they are. |
| 139 | void SyntaxHighlighter::highlightEmbedded(State &state, TokenList &tokenList, |
| 140 | size_t pos, std::string_view text, |
| 141 | const Grammar *fixed, |
| 142 | const Grammar *&named) const { |
| 143 | std::string content; |
| 144 | std::vector<EmbeddedPart> parts; |
| 145 | const Grammar *language = nullptr; |
| 146 |
| 147 | // A run of embedded-language tokens under one parent, in one language, is |
| 148 | // one piece of code, so a comment or a string runs on from one to the next, |
| 149 | // as over a diff's context lines. |
| 150 | for (TokenListPtr node = tokenList.head->next; node != tokenList.head; |
| 151 | pos += node->length(), node = node->next) { |
| 152 | if (!node->isSyntax()) { |
| 153 | continue; |
| 154 | } |
| 155 |
| 156 | auto &syntax = static_cast<Syntax &>(*node); |
| 157 |
| 158 | if (syntax.type() == kEmbeddedLanguageName) { |
| 159 | if (!fixed) { |
| 160 | std::string name(text.substr(pos, syntax.length())); |
| 161 | for (char &c : name) { |
| 162 | if (c >= 'A' && c <= 'Z') { |
| 163 | c += 'a' - 'A'; |
| 164 | } |
| 165 | } |
| 166 |
| 167 | named = m_tree->find(name); |
| 168 | } |
| 169 |
| 170 | // One inside it names the language more closely, as a path's extension |
| 171 | // does. |
| 172 | highlightEmbedded(state, syntax.m_children, pos, text, fixed, named); |
| 173 | } else if (syntax.type() == kEmbeddedLanguage) { |
| 174 | const Grammar *grammar = fixed ? fixed : named; |
| 175 | if (grammar != language) { |
| 176 | highlightParts(state, parts, content, text, language); |
| 177 | language = grammar; |
| 178 | } |
| 179 |
| 180 | if (language) { |
| 181 | parts.push_back({node, pos, content.size()}); |
| 182 | content.append(text.substr(pos, syntax.length())); |
| 183 | } |
| 184 | } else { |
| 185 | highlightEmbedded(state, syntax.m_children, pos, text, fixed, named); |
| 186 | } |
| 187 | } |
| 188 |
| 189 | highlightParts(state, parts, content, text, language); |
| 190 | } |
| 191 |
| 192 | void SyntaxHighlighter::highlightParts(State &state, |
| 193 | std::vector<EmbeddedPart> &parts, |
| 194 | std::string &content, |
| 195 | std::string_view text, |
| 196 | const Grammar *language) const { |
| 197 | if (parts.empty()) { |
| 198 | return; |
| 199 | } |
| 200 |
| 201 | // Its views are into `content`, which is cleared below: the parts are |
| 202 | // rebuilt from it as views into `text`. |
| 203 | TokenList highlighted = tokenize(state, std::string_view(content), language); |
| 204 | std::vector<SliceCursor> cursors; |
| 205 |
| 206 | for (const auto &part : parts) { |
| 207 | auto &syntax = static_cast<Syntax &>(*part.node); |
| 208 |
| 209 | TokenList children; |
| 210 | appendSlice(children, children.head, highlighted, 0, part.start, |
| 211 | part.start + syntax.length(), text, part.offset, cursors, 0); |
| 212 |
| 213 | syntax.m_children.swap(children); |
| 214 | } |
| 215 |
| 216 | parts.clear(); |
| 217 | content.clear(); |
| 218 | } |
| 219 |
| 220 | std::map<std::string, std::string> SyntaxHighlighter::languages() const { |
| 221 | return m_tree->keys(); |
| 222 | } |
| 223 |
| 224 | std::string SyntaxHighlighter::languageName(const std::string &language) const { |
| 225 | return m_tree->languageName(language); |
| 226 | } |
| 227 |
| 228 | std::vector<LanguageGroup> SyntaxHighlighter::languageGroups() const { |
| 229 | std::vector<LanguageGroup> groups; |
| 230 | std::map<std::pair<size_t, std::string>, size_t> index; |
| 231 |
| 232 | // A name joins the group of the first one before it with the same grammar |
| 233 | // and the same display name, which is the language it is an alias of. |
| 234 | for (const auto &name : m_tree->order()) { |
| 235 | const auto &language = m_tree->language(name); |
| 236 | if (language.first.empty()) { |
| 237 | continue; |
| 238 | } |
| 239 |
| 240 | auto key = std::make_pair(language.second, language.first); |
| 241 | auto found = index.find(key); |
| 242 |
| 243 | if (found != index.end()) { |
| 244 | groups[found->second].aliases.push_back(name); |
| 245 | } else { |
| 246 | index.emplace(key, groups.size()); |
| 247 | groups.push_back(LanguageGroup{name, language.first, {}}); |
| 248 | } |
| 249 | } |
| 250 |
| 251 | return groups; |
| 252 | } |
| 253 |
| 254 | TokenList SyntaxHighlighter::tokenize(State &state, std::string_view text, |
| 255 | const Grammar *grammar) const { |
| 256 | // Grammars may include themselves through "inside" (for example |
| 257 | // brightscript directive-statement -> expression -> brightscript), |
| 258 | // which can recurse on the same text forever and overflow the stack. |
| 259 | constexpr auto kMaxDepth = 32; |
| 260 | if (state.depth >= kMaxDepth) { |
| 261 | return TokenList(text); |
| 262 | } |
| 263 | struct DepthGuard { |
| 264 | int &depth; |
| 265 | DepthGuard(int &depth) : depth(++depth) {} |
| 266 | ~DepthGuard() { --depth; } |
| 267 | } guard(state.depth); |
| 268 |
| 269 | const size_t searchesFrom = state.searchesFrom; |
| 270 | state.searchesFrom = state.searches.size(); |
| 271 |
| 272 | TokenList tokenList(text); |
| 273 | try { |
| 274 | matchGrammar(state, text, tokenList, grammar, tokenList.head, 0, nullptr); |
| 275 | } catch (...) { |
| 276 | } |
| 277 |
| 278 | state.searches.resize(state.searchesFrom); |
| 279 | state.searchesFrom = searchesFrom; |
| 280 |
| 281 | return tokenList; |
| 282 | } |
| 283 |
| 284 | // A search that gives up found nothing, so that one pattern goes without and the |
| 285 | // others still get their tokens. Giving up is the longest a search can take, so |
| 286 | // it happens only so many times before the tokenizing stops. |
| 287 | bool SyntaxHighlighter::search(State &state, const Pattern &pattern, size_t pos, |
| 288 | std::string_view text, size_t &start, |
| 289 | size_t &length, |
| 290 | size_t &lookbehindLength) const { |
| 291 | try { |
| 292 | return pattern.search(pos, text, start, length, lookbehindLength); |
| 293 | } catch (...) { |
| 294 | if (--state.searchesToGiveUp == 0) { |
| 295 | state.searchesLeft = 0; |
| 296 | } |
| 297 | return false; |
| 298 | } |
| 299 | } |
| 300 |
| 301 | std::string_view SyntaxHighlighter::matchGreedy(State &state, |
| 302 | const Pattern &pattern, |
| 303 | bool &success, size_t &pos, |
| 304 | std::string_view text) const { |
| 305 | const auto end = state.searches.end(); |
| 306 | auto search = std::find_if( |
| 307 | state.searches.begin() + state.searchesFrom, end, |
| 308 | [&](const GreedySearch &search) { return search.pattern == &pattern; }); |
| 309 |
| 310 | if (search == end || pos < search->from || |
| 311 | (search->found && pos > search->start)) { |
| 312 | if (search == end) { |
| 313 | search = state.searches.insert(end, GreedySearch{&pattern}); |
| 314 | } |
| 315 |
| 316 | --state.searchesLeft; |
| 317 | search->from = pos; |
| 318 | search->found = this->search(state, pattern, pos, text, search->start, |
| 319 | search->length, search->lookbehind); |
| 320 | } |
| 321 |
| 322 | success = search->found; |
| 323 | if (!success) { |
| 324 | return {}; |
| 325 | } |
| 326 |
| 327 | pos = search->start + search->lookbehind; |
| 328 | return text.substr(pos, search->length - search->lookbehind); |
| 329 | } |
| 330 |
| 331 | void SyntaxHighlighter::matchGrammar(State &state, std::string_view text, |
| 332 | TokenList &tokenList, |
| 333 | const Grammar *grammar, |
| 334 | TokenListPtr startNode, size_t startPos, |
| 335 | RematchOptions *rematch) const { |
| 336 | for (const auto &token : grammar->tokens) { |
| 337 | int x = 0; |
| 338 | for (auto j = token.cbegin(); j != token.cend(); ++j) { |
| 339 | if (rematch && rematch->j == x && rematch->token == token.name()) { |
| 340 | return; |
| 341 | } |
| 342 |
| 343 | const auto &pattern = *j->get(); |
| 344 | const auto &inside = pattern.inside(); |
| 345 | const bool greedy = pattern.greedy(); |
| 346 |
| 347 | size_t pos = startPos; |
| 348 |
| 349 | // iterate the token list and keep track of the current token/string |
| 350 | // position |
| 351 | for (TokenListPtr currentNode = startNode->next; |
| 352 | currentNode != tokenList.head; |
| 353 | pos += currentNode->length(), currentNode = currentNode->next) { |
| 354 | if (rematch && pos >= rematch->reach) { |
| 355 | break; |
| 356 | } |
| 357 |
| 358 | // Out of searches. It stops here, where no edit to the list is half |
| 359 | // done. |
| 360 | if (state.searchesLeft == 0) { |
| 361 | return; |
| 362 | } |
| 363 |
| 364 | if (tokenList.length > text.length()) { |
| 365 | // Something went terribly wrong, ABORT, ABORT! |
| 366 | return; |
| 367 | } |
| 368 |
| 369 | if (currentNode->isSyntax()) { |
| 370 | continue; |
| 371 | } |
| 372 |
| 373 | const auto ¤tText = dynamic_cast<Text &>(*currentNode); |
| 374 | std::string_view str = currentText.value(); |
| 375 |
| 376 | auto removeCount = 1; // this is the to parameter of removeBetween |
| 377 | std::string_view match; |
| 378 | bool matchSuccess = false; |
| 379 | size_t matchIndex = pos; |
| 380 |
| 381 | if (greedy) { |
| 382 | match = matchGreedy(state, pattern, matchSuccess, matchIndex, text); |
| 383 | if (!matchSuccess || matchIndex >= text.length()) { |
| 384 | break; |
| 385 | } |
| 386 |
| 387 | auto from = matchIndex; |
| 388 | auto to = matchIndex + match.length(); |
| 389 | auto p = pos; |
| 390 |
| 391 | // find the node that contains the match |
| 392 | p += currentNode->length(); |
| 393 | while (from >= p) { |
| 394 | currentNode = currentNode->next; |
| 395 | p += currentNode->length(); |
| 396 | } |
| 397 | // adjust pos (and p) |
| 398 | p -= currentNode->length(); |
| 399 | pos = p; |
| 400 |
| 401 | // the current node is a Token, then the match starts inside another |
| 402 | // Token, which is invalid |
| 403 | if (currentNode->isSyntax()) { |
| 404 | continue; |
| 405 | } |
| 406 |
| 407 | // find the last node which is affected by this match |
| 408 | for (TokenListPtr k = currentNode; |
| 409 | k != tokenList.head && (p < to || !k->isSyntax()); k = k->next) { |
| 410 | removeCount++; |
| 411 | p += k->length(); |
| 412 | } |
| 413 | removeCount--; |
| 414 |
| 415 | // replace with the new match |
| 416 | str = text.substr(pos, p - pos); |
| 417 | matchIndex -= pos; |
| 418 | } else { |
| 419 | --state.searchesLeft; |
| 420 | size_t start, length, lookbehindLength; |
| 421 | if (!search(state, pattern, 0, str, start, length, lookbehindLength)) { |
| 422 | continue; |
| 423 | } |
| 424 |
| 425 | // change the match to remove the text matched by the Prism lookbehind |
| 426 | // group |
| 427 | matchIndex = start + lookbehindLength; |
| 428 | match = str.substr(matchIndex, length - lookbehindLength); |
| 429 | } |
| 430 |
| 431 | auto from = matchIndex; |
| 432 | auto before = str.substr(0, from); |
| 433 | auto after = str.substr(from + match.length()); |
| 434 |
| 435 | auto reach = pos + str.length(); |
| 436 | if (rematch && reach > rematch->reach) { |
| 437 | rematch->reach = reach; |
| 438 | } |
| 439 |
| 440 | TokenListPtr removeFrom = currentNode->prev; |
| 441 |
| 442 | if (before.size()) { |
| 443 | removeFrom = tokenList.addAfter(removeFrom, before); |
| 444 | pos += before.length(); |
| 445 | } |
| 446 |
| 447 | tokenList.removeRange(removeFrom, removeCount); |
| 448 |
| 449 | TokenList tokenEntries = [&]() { |
| 450 | if (inside) { |
| 451 | return tokenize(state, match, inside); |
| 452 | } else { |
| 453 | return TokenList(match); |
| 454 | } |
| 455 | }(); |
| 456 |
| 457 | currentNode = tokenList.addAfter(removeFrom, token.name(), |
| 458 | std::move(tokenEntries), |
| 459 | pattern.alias(), match.size()); |
| 460 |
| 461 | if (after.size()) { |
| 462 | tokenList.addAfter(currentNode, after); |
| 463 | } |
| 464 |
| 465 | if (removeCount > 1) { |
| 466 | // at least one Token object was removed, so we have to do some |
| 467 | // rematching this can only happen if the current pattern is greedy |
| 468 | RematchOptions nestedRematch = { |
| 469 | .token = token.name(), .reach = reach, .j = x}; |
| 470 |
| 471 | matchGrammar(state, text, tokenList, grammar, currentNode->prev, pos, |
| 472 | &nestedRematch); |
| 473 |
| 474 | // the reach might have been extended because of the rematching |
| 475 | if (rematch && nestedRematch.reach > rematch->reach) { |
| 476 | rematch->reach = nestedRematch.reach; |
| 477 | } |
| 478 | } |
| 479 | } |
| 480 |
| 481 | ++x; |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 |