xaizek / zograscope (License: AGPLv3 only) (since 2018-12-07)
Mainly a syntax-aware diff that also provides a number of additional tools.
<root> / src / Highlighter.cpp (0d9990bc0929e4018561c27e6618016b7f61631f) (18KiB) (mode 100644) [raw]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
// Copyright (C) 2017 xaizek <xaizek@posteo.net>
//
// This file is part of zograscope.
//
// zograscope is free software: you can redistribute it and/or modify
// it under the terms of version 3 of the GNU Affero General Public License as
// published by the Free Software Foundation.
//
// zograscope is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with zograscope.  If not, see <http://www.gnu.org/licenses/>.

#include "Highlighter.hpp"

#include <algorithm>
#include <limits>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

#include <boost/range/adaptor/reversed.hpp>
#include <boost/utility/string_ref.hpp>
#include <boost/optional.hpp>
#include "dtl/dtl.hpp"

#include "utils/strings.hpp"
#include "ColorCane.hpp"
#include "Language.hpp"
#include "colors.hpp"
#include "tree.hpp"

static int leftShift(const Node *node);
static ColorGroup getHighlight(const Node &node, int moved, State state,
                               const Language &lang);
static bool isDiffable(const Node &node, State state, const Language &lang);
static std::vector<boost::string_ref> toWords(boost::string_ref s);
static std::vector<boost::string_ref> toChars(boost::string_ref s);

class Highlighter::ColorPicker
{
public:
    ColorPicker(const Language &lang);

public:
    void setEntry(const Node *node, bool moved, State state);

    void advancedLine();

    ColorGroup getHighlight() const;
    ColorGroup getFillHighlight() const;

private:
    const Language &lang;
    ColorGroup currHighlight = ColorGroup::None;
    ColorGroup prevHighlight = ColorGroup::None;
    const Node *currNode = nullptr;
    const Node *prevNode = nullptr;
    bool prevMoved = false;
    bool currMoved = false;
};

Highlighter::ColorPicker::ColorPicker(const Language &lang) : lang(lang) { }

void
Highlighter::ColorPicker::setEntry(const Node *node, bool moved, State state)
{
    prevNode = (currNode == node ? nullptr : currNode);
    currNode = node;

    prevMoved = currMoved;
    currMoved = moved;

    prevHighlight = currHighlight;
    currHighlight = ::getHighlight(*currNode, moved, state, lang);
}

void
Highlighter::ColorPicker::advancedLine()
{
    prevNode = nullptr;
}

ColorGroup
Highlighter::ColorPicker::getHighlight() const
{
    return currHighlight;
}

ColorGroup
Highlighter::ColorPicker::getFillHighlight() const
{
    if (prevNode == nullptr) {
        return ColorGroup::None;
    }

    // Updates are individual (one to one) and look better separated with
    // background.
    if (prevHighlight == currHighlight &&
        currNode->state != State::Updated) {
        return currHighlight;
    }

    if (prevNode->leaf && prevMoved && currMoved) {
        return prevHighlight;
    }

    return ColorGroup::None;
}

Highlighter::Highlighter(const Tree &tree, bool original)
    : Highlighter(*tree.getRoot(), *tree.getLanguage(), original, 1, 1)
{
}

Highlighter::Highlighter(const Node &root, const Language &lang, bool original,
                         int lineOffset)
    : Highlighter(root, lang, original, lineOffset, leftShift(&root))
{
}

// Computes how far to the right subtree defined by the `node` is shifted.  This
// is the same amount by which it can be shifted to the left to get rid of
// unnecessary indentation.
static int
leftShift(const Node *node)
{
    auto getCol = [](const Node *node) {
        if (node->spelling.find('\n') != std::string::npos) {
            // Multiline nodes occupy first column.
            return 1;
        }
        return node->col;
    };

    if (node->next != nullptr) {
        return leftShift(node->next);
    }

    if (node->children.empty() && node->leaf) {
        return getCol(node);
    }

    int shift = std::numeric_limits<int>::max();
    for (Node *child : node->children) {
        if (!child->leaf || child->next != nullptr) {
            shift = std::min(shift, leftShift(child));
        } else {
            shift = std::min(shift, getCol(child));
        }
    }
    return shift;
}

Highlighter::Highlighter(const Node &root, const Language &lang, bool original,
                         int lineOffset, int colOffset)
    : lang(lang), line(lineOffset), col(1), colOffset(colOffset),
      colorPicker(new ColorPicker(lang)), original(original), current(nullptr),
      printReferences(false), printBrackets(false), transparentDiffables(false)
{
    toProcess.push({ &root, root.moved, root.state, false, false });
}

Highlighter::~Highlighter() = default;

void
Highlighter::setPrintReferences(bool print)
{
    printReferences = print;
}

void
Highlighter::setPrintBrackets(bool print)
{
    printBrackets = print;
}

void
Highlighter::setTransparentDiffables(bool transparent)
{
    transparentDiffables = transparent;
}

ColorCane
Highlighter::print(int from, int n)
{
    colorCane = ColorCane();
    if (from < line) {
        n = std::max(0, n - (line - from));
    }

    skipUntil(from);
    print(n);
    return std::move(colorCane);
}

ColorCane
Highlighter::print()
{
    colorCane = ColorCane();
    print(std::numeric_limits<int>::max());
    return std::move(colorCane);
}

void
Highlighter::skipUntil(int targetLine)
{
    if (line >= targetLine) {
        return;
    }

    if (!lines.empty()) {
        for (std::size_t i = 1U; i < lines.size(); ++i) {
            if (++line == targetLine) {
                olines.erase(olines.begin(), olines.begin() + i);
                lines.erase(lines.begin(), lines.begin() + i);
                return;
            }
        }
        olines.clear();
        lines.clear();
    }

    while (!toProcess.empty()) {
        Entry entry = getEntry();
        const Node *const node = entry.node;
        if (!node->leaf) {
            advance(entry);
            continue;
        }

        colorPicker->setEntry(entry.node, entry.moved, entry.state);

        while (node->line > line) {
            if (++line == targetLine) {
                return;
            }
        }

        advance(entry);

        split(node->spelling, '\n', olines);

        for (std::size_t i = 1U; i < olines.size(); ++i) {
            if (++line == targetLine) {
                current = node;
                colorPicker->advancedLine();
                lines = getSpelling(entry).splitIntoLines();
                olines.erase(olines.begin(), olines.begin() + i);
                lines.erase(lines.begin(), lines.begin() + i);
                return;
            }
        }

        olines.clear();
        lines.clear();
    }
}

void
Highlighter::print(int n)
{
    col = colOffset;
    colorPicker->advancedLine();

    if (!lines.empty()) {
        printSpelling(n);
    }

    while (!toProcess.empty() && n != 0) {
        Entry entry = getEntry();
        const Node *const node = entry.node;
        if (!node->leaf) {
            advance(entry);
            continue;
        }

        colorPicker->setEntry(entry.node, entry.moved, entry.state);

        while (node->line > line) {
            ++line;
            colorPicker->advancedLine();
            if (--n == 0) {
                return;
            }
            colorCane.append('\n');
            col = colOffset;
        }

        if (node->col > col) {
            ColorGroup fillHi = colorPicker->getFillHighlight();
            colorCane.append(' ', node->col - col, fillHi);
            col = node->col;
        }

        advance(entry);

        lines = getSpelling(entry).splitIntoLines();
        split(node->spelling, '\n', olines);
        current = node;

        printSpelling(n);
    }
}

void
Highlighter::printSpelling(int &n)
{
    ColorGroup hi = colorPicker->getHighlight();

    auto printLine = [&](ColorCane &cc) {
        std::vector<ColorCane> ccs = std::move(cc).cutAfter(" \t");

        for (auto &piece : ccs[0]) {
            colorCane.append(piece.text, piece.node, piece.hi);
        }
        for (auto &piece : ccs[1]) {
            ColorGroup cg = (piece.hi == ColorGroup::None ? hi : piece.hi);
            colorCane.append(piece.text, piece.node, cg);
        }
    };

    printLine(lines.front());
    col += olines.front().size();

    for (std::size_t i = 1U; i < lines.size(); ++i) {
        ++line;
        colorPicker->advancedLine();
        if (--n == 0) {
            olines.erase(olines.begin(), olines.begin() + i);
            lines.erase(lines.begin(), lines.begin() + i);
            return;
        }

        colorCane.append('\n');
        printLine(lines[i]);
        col = 1 + olines[i].size();
    }

    olines.clear();
    lines.clear();
}

Highlighter::Entry
Highlighter::getEntry()
{
    Entry entry = toProcess.top();
    const Node *node = entry.node;

    if (node->next != nullptr || node->leaf) {
        if (!entry.propagateState && node->state != State::Unchanged) {
            entry.propagateState = true;
            entry.state = node->state;
        }
        if (node->moved) {
            entry.propagateMoved = true;
            entry.moved = true;
        }
    }

    if (node->next != nullptr) {
        // Update entry and rerun the checks (state can be changed both on
        // switching to a different layer and directly after switching to it).
        entry.node = node->next;
        toProcess.top() = entry;
        return getEntry();
    }

    return entry;
}

void
Highlighter::advance(const Entry &entry)
{
    toProcess.pop();
    for (Node *child : boost::adaptors::reverse(entry.node->children)) {
        Entry childEntry = entry;
        childEntry.node = child;
        if (!childEntry.propagateState) {
            childEntry.state = child->state;
        }
        if (!childEntry.propagateMoved) {
            childEntry.moved = child->moved;
        }

        toProcess.push(childEntry);
    }
}

// Determines color group for the specified node considering overrides of its
// properties.
static ColorGroup
getHighlight(const Node &node, int moved, State state, const Language &lang)
{
    // Highlighting based on node state has higher priority.
    switch (state) {
        case State::Deleted:
            return ColorGroup::Deleted;
        case State::Inserted:
            return ColorGroup::Inserted;
        case State::Updated:
            // TODO: things that were updated and moved at the same time need a
            //       special color?
            //       Or update kinda implies move, since it's obvious that there
            //       was a match between nodes?
            if (!isDiffable(node, state, lang)) {
                return ColorGroup::Updated;
            }
            break;

        case State::Unchanged:
            if (moved) {
                return ColorGroup::Moved;
            }
            break;
    }

    // Highlighting based on node type follows.
    switch (node.type) {
        case Type::Specifiers: return ColorGroup::Specifiers;
        case Type::UserTypes:  return ColorGroup::UserTypes;
        case Type::Types:      return ColorGroup::Types;
        case Type::Directives: return ColorGroup::Directives;
        case Type::Comments:   return ColorGroup::Comments;
        case Type::Functions:  return ColorGroup::Functions;

        case Type::Jumps:
        case Type::Keywords:
            return ColorGroup::Keywords;
        case Type::LeftBrackets:
        case Type::RightBrackets:
            return ColorGroup::Brackets;
        case Type::Assignments:
        case Type::Operators:
        case Type::LogicalOperators:
        case Type::Comparisons:
            return ColorGroup::Operators;
        case Type::StrConstants:
        case Type::IntConstants:
        case Type::FPConstants:
        case Type::CharConstants:
            return ColorGroup::Constants;

        case Type::Identifiers:
        case Type::Other:
        case Type::Virtual:
        case Type::NonInterchangeable:
            break;
    }

    return ColorGroup::Other;
}

ColorCane
Highlighter::getSpelling(const Entry &entry)
{
    const Node &node = *entry.node;

    const bool diffable = isDiffable(node, entry.state, lang);
    if (!diffable && entry.state != State::Updated) {
        ColorCane cc;
        cc.append(node.spelling, &node);
        return cc;
    }

    ColorCane cc;
    if (diffable) {
        cc = diffSpelling(node, entry.moved);
    } else {
        cc.append(node.spelling, &node, ColorGroup::Updated);
    }

    int &id = updates[original ? &node : node.relative];
    id = updates.size();
    if (printReferences) {
        cc.append('{', ColorGroup::UpdatedSurroundings);
        cc.append(std::to_string(id), nullptr, ColorGroup::UpdatedSurroundings);
        cc.append('}', ColorGroup::UpdatedSurroundings);
    }

    return cc;
}

// Checks whether node spelling can be diffed.
static bool
isDiffable(const Node &node, State state, const Language &lang)
{
    return node.relative != nullptr
        && lang.isDiffable(&node)
        && state == State::Updated;
}

ColorCane
Highlighter::diffSpelling(const Node &node, bool moved)
{
    // XXX: some kind of caching would be nice since we're doing the same thing
    //      for both original and updated nodes.

    boost::string_ref l = (original ? node.spelling : node.relative->spelling);
    boost::string_ref r = (original ? node.relative->spelling : node.spelling);

    std::vector<boost::string_ref> lWords = toWords(l);
    std::vector<boost::string_ref> rWords = toWords(r);

    const bool surround = node.type == Type::Functions
                       || node.type == Type::Identifiers
                       || node.type == Type::UserTypes;

    if (surround && lWords.size() == 1U && rWords.size() == 1U) {
        lWords = toChars(l);
        rWords = toChars(r);
    }

    auto cmp = [](const boost::string_ref &a, const boost::string_ref &b) {
        return (a == b);
    };

    dtl::Diff<boost::string_ref, std::vector<boost::string_ref>,
              decltype(cmp)> diff(lWords, rWords, cmp);
    diff.compose();

    ColorCane cc;

    float worstDistance = std::max(lWords.size(), rWords.size());
    float sim = 1.0f - diff.getEditDistance()/worstDistance;

    // If Levenshtein distance ends up being too big (similarity is too small),
    // drop comparison results and get back to just printing two nodes as
    // updated.
    if (sim < 0.2f) {
        cc.append(node.spelling, &node, ColorGroup::Updated);
        return cc;
    }

    if (surround && printBrackets) {
        cc.append('[', ColorGroup::UpdatedSurroundings);
    }

    const char *lastL = l.data(), *lastR = r.data();

    auto printLeft = [&](const dtl::elemInfo &info, ColorGroup hi,
                         ColorGroup def) {
        const boost::string_ref sr = lWords[info.beforeIdx - 1];
        cc.append(boost::string_ref(lastL, sr.data() - lastL), &node, def);
        cc.append(sr, &node, hi);
        lastL = sr.data() + sr.size();
    };
    auto printRight = [&](const dtl::elemInfo &info, ColorGroup hi,
                          ColorGroup def) {
        const boost::string_ref sr = rWords[info.afterIdx - 1];
        cc.append(boost::string_ref(lastR, sr.data() - lastR), &node, def);
        cc.append(sr, &node, hi);
        lastR = sr.data() + sr.size();
    };

    // Unchanged parts are highlighted using this color group.
    ColorGroup def = ColorGroup::None;
    if (!transparentDiffables && surround) {
        def = ColorGroup::PieceUpdated;
    } else if (moved) {
        def = ColorGroup::Moved;
    }

    for (const auto &x : diff.getSes().getSequence()) {
        switch (x.second.type) {
            case dtl::SES_DELETE:
                if (original) {
                    printLeft(x.second, ColorGroup::PieceDeleted, def);
                }
                break;
            case dtl::SES_ADD:
                if (!original) {
                    printRight(x.second, ColorGroup::PieceInserted, def);
                }
                break;
            case dtl::SES_COMMON:
                if (original) {
                    printLeft(x.second, def, def);
                } else {
                    printRight(x.second, def, def);
                }
                break;
        }
    }

    if (original) {
        cc.append(boost::string_ref(lastL, lastL - l.end()), &node, def);
    } else {
        cc.append(boost::string_ref(lastR, lastR - r.end()), &node, def);
    }
    if (surround && printBrackets) {
        cc.append(']', ColorGroup::UpdatedSurroundings);
    }

    return cc;
}

// Breaks a multi-word string into collection of words.
static std::vector<boost::string_ref>
toWords(boost::string_ref s)
{
    std::vector<boost::string_ref> words;

    enum State { Start, WhiteSpace, Word, Punctuation, End };

    auto classify = [](char c) {
        if (std::ispunct(c, std::locale())) return Punctuation;
        if (std::isspace(c, std::locale())) return WhiteSpace;
        return Word;
    };

    auto isNonWord = [](State state) {
        return (state == Punctuation || state == WhiteSpace);
    };

    auto hasInput = [](State state) {
        return (state != Start && state != End);
    };

    State currentState = Start;
    std::size_t wordStart = 0U;
    for (std::size_t i = 0U; i <= s.size(); ++i) {
        const State newState = (i == s.size() ? End : classify(s[i]));
        // Each punctuation or whitespace character is treated as a separate
        // "word".
        if (currentState != newState || isNonWord(currentState)) {
            if (hasInput(currentState)) {
                words.emplace_back(s.substr(wordStart, i - wordStart));
            }
            if (hasInput(newState)) {
                wordStart = i;
            }
        }
        currentState = newState;
    }

    return words;
}

// Turns string into a bunch of single character strings.
static std::vector<boost::string_ref>
toChars(boost::string_ref s)
{
    std::vector<boost::string_ref> chars;
    chars.reserve(s.size());

    for (std::size_t i = 0U; i < s.size(); ++i) {
        chars.emplace_back(s.substr(i, 1));
    }

    return chars;
}
Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/zograscope

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/zograscope

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master