diff --git a/src/autotests/commentparser.cpp b/src/autotests/commentparser.cpp index f58f839..e56610c 100644 --- a/src/autotests/commentparser.cpp +++ b/src/autotests/commentparser.cpp @@ -1,376 +1,376 @@ /** * Copyright (C) 2019 Michael Reeves * * This file is part of KDiff3. * * KDiff3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * KDiff3 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KDiff3. If not, see . */ #include #include "../CommentParser.h" class CommentParserTest : public QObject { Q_OBJECT private slots: void init() { DefaultCommentParser parser; //Sanity check defaults. QVERIFY(!parser.isPureComment()); QVERIFY(!parser.isEscaped()); QVERIFY(!parser.inString()); QVERIFY(!parser.inComment()); } void singleLineComment() { DefaultCommentParser test; test.processLine("//ddj ?*8"); QVERIFY(!test.inComment()); QVERIFY(test.isPureComment()); //ignore trailing+leading whitespace test = DefaultCommentParser(); test.processLine("\t \t // comment "); QVERIFY(!test.inComment()); QVERIFY(test.isPureComment()); test = DefaultCommentParser(); test.processLine("//comment with quotes embedded \"\""); QVERIFY(!test.inComment()); QVERIFY(test.isPureComment()); test = DefaultCommentParser(); test.processLine("anythis//endof line comment"); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test = DefaultCommentParser(); test.processLine("anythis//ignore embedded multiline sequence /*"); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); } void inComment() { DefaultCommentParser test; test.mCommentType = DefaultCommentParser::multiLine; QVERIFY(test.inComment()); test.mCommentType = DefaultCommentParser::singleLine; QVERIFY(test.inComment()); test.mCommentType = DefaultCommentParser::none; QVERIFY(!test.inComment()); } void multiLineComment() { DefaultCommentParser test; //mutiline syntax on one line test.processLine("/* kjd*/"); QVERIFY(test.isPureComment()); QVERIFY(!test.inComment()); //mid line comment start. test = DefaultCommentParser(); test.processLine("fskk /* kjd */"); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); //mid line comment start. multiple lines test = DefaultCommentParser(); test.processLine("fskk /* kjd "); QVERIFY(test.inComment()); QVERIFY(!test.isPureComment()); test.processLine(" comment line "); QVERIFY(test.inComment()); QVERIFY(test.isPureComment()); test.processLine(" comment */ not comment "); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); //mid line comment start. multiple lines test = DefaultCommentParser(); test.processLine("fskk /* kjd "); QVERIFY(test.inComment()); QVERIFY(!test.isPureComment()); test.processLine(" comment line "); QVERIFY(test.inComment()); QVERIFY(test.isPureComment()); test.processLine(" comment * line / "); QVERIFY(test.inComment()); QVERIFY(test.isPureComment()); //embedded single line character sequence should not end comment test.processLine(" comment line //"); QVERIFY(test.inComment()); QVERIFY(test.isPureComment()); test.processLine(" comment */"); QVERIFY(!test.inComment()); QVERIFY(test.isPureComment()); //Escape squeances not relavate to comments test = DefaultCommentParser(); test.processLine("/* comment \\*/"); QVERIFY(!test.inComment()); QVERIFY(test.isPureComment()); test = DefaultCommentParser(); test.processLine(" int i = 8 / 8 * 3;/* comment*/"); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); //invalid in C++ should not be flagged as pure comment test.processLine("/* comment */ */"); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); //leading whitespace test = DefaultCommentParser(); test.processLine("\t \t /* comment */"); QVERIFY(!test.inComment()); QVERIFY(test.isPureComment()); //trailing whitespace test = DefaultCommentParser(); test.processLine("\t \t /* comment */ "); QVERIFY(!test.inComment()); QVERIFY(test.isPureComment()); } void stringTest() { DefaultCommentParser test; test.processLine("\"quoted string // \""); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test = DefaultCommentParser(); test.processLine("\"quoted string /* \""); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test = DefaultCommentParser(); test.processLine("\"\""); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test = DefaultCommentParser(); test.processChar("\"", '"'); QVERIFY(!test.isEscaped()); QVERIFY(test.inString()); test.processChar("\"'", '\''); QVERIFY(test.inString()); test.processChar("\"'\"", '"'); QVERIFY(!test.inString()); //test only escape sequence we care about test = DefaultCommentParser(); test.processChar("\"", '"'); test.processChar("\"", '\\'); QVERIFY(test.isEscaped()); QVERIFY(test.inString()); test.processChar("\"\\\"", '"'); QVERIFY(!test.isEscaped()); QVERIFY(test.inString()); test.processChar("\"\\\"\"", '"'); QVERIFY(!test.isEscaped()); QVERIFY(!test.inString()); } void quotedCharacter() { DefaultCommentParser test; test.processLine("'\"'"); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test.processLine("'a'"); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test.processLine("'\\\''"); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test.processLine("'*'"); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test.processLine("'/'"); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); } void nonComment() { DefaultCommentParser test; test.processLine(" int i = 8 / 8 * 3;"); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test = DefaultCommentParser(); test.processLine(" "); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test = DefaultCommentParser(); test.processLine(""); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test = DefaultCommentParser(); test.processLine(" / "); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); test = DefaultCommentParser(); test.processLine(" * "); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); //invalid in C++ should not be flagged as non-comment test.processLine(" */"); QVERIFY(!test.inString()); QVERIFY(!test.inComment()); QVERIFY(!test.isPureComment()); } void removeComment() { DefaultCommentParser test; QString line=QLatin1String(" int i = 8 / 8 * 3;"), correct=QLatin1String(" int i = 8 / 8 * 3;"); test.processLine(line); test.removeComment(line); QVERIFY(line == correct); QVERIFY(line.length() == correct.length()); test = DefaultCommentParser(); correct = line = QLatin1String(" //int i = 8 / 8 * 3;"); test.processLine(line); test.removeComment(line); QVERIFY(line == correct); test = DefaultCommentParser(); correct = line = QLatin1String("// int i = 8 / 8 * 3;"); test.processLine(line); test.removeComment(line); QVERIFY(line == correct); QVERIFY(line.length() == correct.length()); test = DefaultCommentParser(); line = QLatin1String(" int i = 8 / 8 * 3;// comment"); correct = QLatin1String(" int i = 8 / 8 * 3; "); test.processLine(line); test.removeComment(line); QVERIFY(line == correct); QVERIFY(line.length() == correct.length()); test = DefaultCommentParser(); line = QLatin1String(" int i = 8 / 8 * 3;/* comment"); correct = QLatin1String(" int i = 8 / 8 * 3; "); test.processLine(line); test.removeComment(line); QVERIFY(line == correct); QVERIFY(line.length() == correct.length()); correct = line = QLatin1String(" int i = 8 / 8 * 3;/* mot a comment"); test.processLine(line); test.removeComment(line); QVERIFY(line == correct); QVERIFY(line.length() == correct.length()); //end comment mid-line line = QLatin1String("d */ why"); correct = QLatin1String(" why"); test.processLine(line); test.removeComment(line); QVERIFY(line == correct); QVERIFY(line.length() == correct.length()); test = DefaultCommentParser(); line = QLatin1String(" int i = 8 / 8 * 3;/* comment*/"); correct = QLatin1String(" int i = 8 / 8 * 3; "); test.processLine(line); test.removeComment(line); QVERIFY(line == correct); QVERIFY(line.length() == correct.length()); test = DefaultCommentParser(); correct = line = QLatin1String(" /*int i = 8 / 8 * 3;/* comment*/"); test.processLine(line); test.removeComment(line); QVERIFY(line == correct); QVERIFY(line.length() == correct.length()); - //line with multiple comments wierd but legal c/c++ + //line with multiple comments weird but legal c/c++ test = DefaultCommentParser(); line = QLatin1String(" int /*why?*/ i = 8 / 8 * 3;/* comment*/"); correct = QLatin1String(" int i = 8 / 8 * 3; "); test.processLine(line); test.removeComment(line); QVERIFY(line == correct); QVERIFY(line.length() == correct.length()); //invalid in C++ should not be flagged as non-comment test = DefaultCommentParser(); line = correct = " */"; test.processLine(" */"); QVERIFY(line == correct); QVERIFY(line.length() == correct.length()); } }; QTEST_MAIN(CommentParserTest); #include "commentparser.moc" diff --git a/src/diff.h b/src/diff.h index 27e32f2..604f9eb 100644 --- a/src/diff.h +++ b/src/diff.h @@ -1,501 +1,501 @@ /*************************************************************************** * Copyright (C) 2003-2007 by Joachim Eibl * * Copyright (C) 2018 Michael Reeves reeves.87@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef DIFF_H #define DIFF_H #include "common.h" #include "fileaccess.h" #include "LineRef.h" #include "SourceData.h" #include "Logging.h" #include #include class Options; //These enums must be sequential with no gaps to allow loop interiation of values enum e_SrcSelector { Min = -1, Invalid=-1, None=0, A = 1, B = 2, C = 3, Max=C }; enum e_MergeDetails { eDefault, eNoChange, eBChanged, eCChanged, eBCChanged, // conflict eBCChangedAndEqual, // possible conflict eBDeleted, eCDeleted, eBCDeleted, // possible conflict eBChanged_CDeleted, // conflict eCChanged_BDeleted, // conflict eBAdded, eCAdded, eBCAdded, // conflict eBCAddedAndEqual // possible conflict }; enum ChangeFlag{ NoChange = 0, AChanged = 0x1, BChanged = 0x2, Both = AChanged | BChanged }; Q_DECLARE_FLAGS(ChangeFlags, ChangeFlag); Q_DECLARE_OPERATORS_FOR_FLAGS(ChangeFlags); // Each range with matching elements is followed by a range with differences on either side. // Then again range of matching elements should follow. class Diff { private: qint32 nofEquals = 0; qint64 mDiff1 = 0; qint64 mDiff2 = 0; public: Diff(qint32 eq, const qint64 inDiff1, const qint64 inDiff2) { nofEquals = eq; mDiff1 = inDiff1; mDiff2 = inDiff2; } inline qint32 numberOfEquals() const { return nofEquals; }; inline qint64 diff1() const { return mDiff1; }; inline qint64 diff2() const { return mDiff2; }; inline void setNumberOfEquals(const qint32 inNumOfEquals) { nofEquals = inNumOfEquals; } inline void adjustNumberOfEquals(const qint64 delta) { nofEquals += delta; } inline void adjustDiff1(const qint64 delta) { mDiff1 += delta; } inline void adjustDiff2(const qint64 delta) { mDiff2 += delta; } }; typedef std::list DiffList; class LineData { private: QSharedPointer mBuffer; //QString pLine; QtNumberType mFirstNonWhiteChar = 0; qint64 mOffset = 0; QtNumberType mSize = 0; bool bContainsPureComment = false;//TODO: Move me public: explicit LineData() = default; // needed for Qt internal reasons should not be used. inline LineData(const QSharedPointer &buffer, const qint64 inOffset, QtNumberType inSize = 0, QtNumberType inFirstNonWhiteChar=0, bool inIsPureComment=false) { mBuffer = buffer; mOffset = inOffset; mSize = inSize; bContainsPureComment = inIsPureComment; mFirstNonWhiteChar = inFirstNonWhiteChar; } Q_REQUIRED_RESULT inline int size() const { return mSize; } Q_REQUIRED_RESULT inline qint32 getFirstNonWhiteChar() const { return mFirstNonWhiteChar; } /* QString::fromRawData allows us to create a light weight QString backed by the buffer memmory. */ Q_REQUIRED_RESULT inline const QString getLine() const { return QString::fromRawData(mBuffer->data() + mOffset, mSize); } Q_REQUIRED_RESULT inline const QSharedPointer& getBuffer() const { return mBuffer; } Q_REQUIRED_RESULT inline qint64 getOffset() const { return mOffset; } Q_REQUIRED_RESULT int width(int tabSize) const; // Calcs width considering tabs. //int occurrences; inline bool whiteLine() const { return mFirstNonWhiteChar == mSize - 1; } inline bool isPureComment() const { return bContainsPureComment; } inline void setPureComment(const bool bPureComment) { bContainsPureComment = bPureComment; } static bool equal(const LineData& l1, const LineData& l2, bool bStrict); }; class ManualDiffHelpList; // A list of corresponding ranges class Diff3LineList; class Diff3LineVector; class DiffBufferInfo { private: const QVector* mLineDataA; const QVector* mLineDataB; const QVector* mLineDataC; LineCount m_sizeA; LineCount m_sizeB; LineCount m_sizeC; const Diff3LineList* m_pDiff3LineList; const Diff3LineVector* m_pDiff3LineVector; public: void init(Diff3LineList* d3ll, const Diff3LineVector* d3lv, const QVector* pldA, LineCount sizeA, const QVector* pldB, LineCount sizeB, const QVector* pldC, LineCount sizeC); inline const QVector* getLineData(e_SrcSelector srcIndex) const { switch(srcIndex) { case A: return mLineDataA; case B: return mLineDataB; case C: return mLineDataC; default: return nullptr; } } }; class Diff3Line { private: friend class Diff3LineList; LineRef lineA; LineRef lineB; LineRef lineC; bool bAEqC = false; // These are true if equal or only white-space changes exist. bool bBEqC = false; bool bAEqB = false; public: bool bWhiteLineA = false; bool bWhiteLineB = false; bool bWhiteLineC = false; DiffList* pFineAB = nullptr; // These are NULL only if completely equal or if either source doesn't exist. DiffList* pFineBC = nullptr; DiffList* pFineCA = nullptr; int linesNeededForDisplay = 1; // Due to wordwrap int sumLinesNeededForDisplay = 0; // For fast conversion to m_diff3WrapLineVector DiffBufferInfo* m_pDiffBufferInfo = nullptr; // For convenience ~Diff3Line() { if(pFineAB != nullptr) delete pFineAB; if(pFineBC != nullptr) delete pFineBC; if(pFineCA != nullptr) delete pFineCA; pFineAB = nullptr; pFineBC = nullptr; pFineCA = nullptr; } LineRef getLineA() const { return lineA; } LineRef getLineB() const { return lineB; } LineRef getLineC() const { return lineC; } inline void setLineA(const LineRef& line) { lineA = line; } inline void setLineB(const LineRef& line) { lineB = line; } inline void setLineC(const LineRef& line) { lineC = line; } inline bool isEqualAB() const { return bAEqB; } inline bool isEqualAC() const { return bAEqC; } inline bool isEqualBC() const { return bBEqC; } bool operator==(const Diff3Line& d3l) const { return lineA == d3l.lineA && lineB == d3l.lineB && lineC == d3l.lineC && bAEqB == d3l.bAEqB && bAEqC == d3l.bAEqC && bBEqC == d3l.bBEqC; } const LineData* getLineData(e_SrcSelector src) const { Q_ASSERT(m_pDiffBufferInfo != nullptr); - //Use at here not [] to avoid using really wierd syntax + //Use at here not [] to avoid using really weird syntax if(src == A && lineA.isValid()) return &m_pDiffBufferInfo->getLineData(src)->at(lineA); if(src == B && lineB.isValid()) return &m_pDiffBufferInfo->getLineData(src)->at(lineB); if(src == C && lineC.isValid()) return &m_pDiffBufferInfo->getLineData(src)->at(lineC); return nullptr; } const QString getString(const e_SrcSelector src) const { const LineData* pld = getLineData(src); if(pld) return pld->getLine(); else return QString(); } LineRef getLineInFile(e_SrcSelector src) const { if(src == A) return lineA; if(src == B) return lineB; if(src == C) return lineC; return -1; } bool fineDiff(bool bTextsTotalEqual, const e_SrcSelector selector, const QVector* v1, const QVector* v2); void mergeOneLine(e_MergeDetails& mergeDetails, bool& bConflict, bool& bLineRemoved, e_SrcSelector& src, bool bTwoInputs) const; void getLineInfo(const e_SrcSelector winIdx, const bool isTriple, LineRef& lineIdx, DiffList*& pFineDiff1, DiffList*& pFineDiff2, // return values ChangeFlags& changed, ChangeFlags& changed2) const; private: void setFineDiff(const e_SrcSelector selector, DiffList* pDiffList) { Q_ASSERT(selector == A || selector == B || selector == C); if(selector == A) { if(pFineAB != nullptr) delete pFineAB; pFineAB = pDiffList; } else if(selector == B) { if(pFineBC != nullptr) delete pFineBC; pFineBC = pDiffList; } else if(selector == C) { if(pFineCA) delete pFineCA; pFineCA = pDiffList; } } }; class Diff3LineList : public std::list { public: bool fineDiff(const e_SrcSelector selector, const QVector* v1, const QVector* v2); void calcDiff3LineVector(Diff3LineVector& d3lv); void calcWhiteDiff3Lines(const QVector* pldA, const QVector* pldB, const QVector* pldC); void calcDiff3LineListUsingAB(const DiffList* pDiffListAB); void calcDiff3LineListUsingAC(const DiffList* pDiffListAC); void calcDiff3LineListUsingBC(const DiffList* pDiffListBC); void correctManualDiffAlignment(ManualDiffHelpList* pManualDiffHelpList); void calcDiff3LineListTrim(const QVector* pldA, const QVector* pldB, const QVector* pldC, ManualDiffHelpList* pManualDiffHelpList); LineCount recalcWordWrap(bool resetDisplayCount) { //Diff3LineList::iterator i; LineCount sumOfLines = 0; for(Diff3Line& d3l: *this) { //Diff3Line& d3l = *i; if(resetDisplayCount) d3l.linesNeededForDisplay = 1; d3l.sumLinesNeededForDisplay = sumOfLines; sumOfLines += d3l.linesNeededForDisplay; } return sumOfLines; } //TODO: Add safety guards to prevent list from getting too large. Same problem as with QLinkedList. int size() const { if(std::list::size() > (size_t)TYPE_MAX(int))//explicit cast to silence gcc { qCDebug(kdiffMain) << "Diff3Line: List too large. size=" << std::list::size(); Q_ASSERT(false); //Unsupported size return 0; } return (int)std::list::size(); } //safe for small files same limit as exited with QLinkedList. This should ultimatly be removed. void debugLineCheck(const LineCount size, const e_SrcSelector srcSelector) const; }; class Diff3LineVector : public QVector { }; class Diff3WrapLine { public: Diff3Line* pD3L; int diff3LineIndex; int wrapLineOffset; int wrapLineLength; }; typedef QVector Diff3WrapLineVector; class TotalDiffStatus { public: inline void reset() { bBinaryAEqC = false; bBinaryBEqC = false; bBinaryAEqB = false; bTextAEqC = false; bTextBEqC = false; bTextAEqB = false; nofUnsolvedConflicts = 0; nofSolvedConflicts = 0; nofWhitespaceConflicts = 0; } inline int getUnsolvedConflicts() const { return nofUnsolvedConflicts; } inline void setUnsolvedConflicts(const int unsolved) { nofUnsolvedConflicts = unsolved; } inline int getSolvedConflicts() const { return nofSolvedConflicts; } inline void setSolvedConflicts(const int solved) { nofSolvedConflicts = solved; } inline int getWhitespaceConflicts() const { return nofWhitespaceConflicts; } inline void setWhitespaceConflicts(const int wintespace) { nofWhitespaceConflicts = wintespace; } inline int getNonWhitespaceConflicts() { return getUnsolvedConflicts() + getSolvedConflicts() - getWhitespaceConflicts(); } bool isBinaryEqualAC() const { return bBinaryAEqC; } bool isBinaryEqualBC() const { return bBinaryBEqC; } bool isBinaryEqualAB() const { return bBinaryAEqB; } bool bBinaryAEqC = false; bool bBinaryBEqC = false; bool bBinaryAEqB = false; bool bTextAEqC = false; bool bTextBEqC = false; bool bTextAEqB = false; private: int nofUnsolvedConflicts = 0; int nofSolvedConflicts = 0; int nofWhitespaceConflicts = 0; }; // Three corresponding ranges. (Minimum size of a valid range is one line.) class ManualDiffHelpEntry { private: LineRef lineA1; LineRef lineA2; LineRef lineB1; LineRef lineB2; LineRef lineC1; LineRef lineC2; public: LineRef& firstLine(e_SrcSelector winIdx) { return winIdx == A ? lineA1 : (winIdx == B ? lineB1 : lineC1); } LineRef& lastLine(e_SrcSelector winIdx) { return winIdx == A ? lineA2 : (winIdx == B ? lineB2 : lineC2); } bool isLineInRange(LineRef line, e_SrcSelector winIdx) { return line.isValid() && line >= firstLine(winIdx) && line <= lastLine(winIdx); } bool operator==(const ManualDiffHelpEntry& r) const { return lineA1 == r.lineA1 && lineB1 == r.lineB1 && lineC1 == r.lineC1 && lineA2 == r.lineA2 && lineB2 == r.lineB2 && lineC2 == r.lineC2; } int calcManualDiffFirstDiff3LineIdx(const Diff3LineVector& d3lv); void getRangeForUI(const e_SrcSelector winIdx, LineRef *rangeLine1, LineRef *rangeLine2) const { if(winIdx == A) { *rangeLine1 = lineA1; *rangeLine2 = lineA2; } if(winIdx == B) { *rangeLine1 = lineB1; *rangeLine2 = lineB2; } if(winIdx == C) { *rangeLine1 = lineC1; *rangeLine2 = lineC2; } } inline int getLine1(const e_SrcSelector winIdx) const { return winIdx == A ? lineA1 : winIdx == B ? lineB1 : lineC1;} inline int getLine2(const e_SrcSelector winIdx) const { return winIdx == A ? lineA2 : winIdx == B ? lineB2 : lineC2;} bool isValidMove(int line1, int line2, e_SrcSelector winIdx1, e_SrcSelector winIdx2) const; }; // A list of corresponding ranges class ManualDiffHelpList: public std::list { public: bool isValidMove(int line1, int line2, e_SrcSelector winIdx1, e_SrcSelector winIdx2) const; void insertEntry(e_SrcSelector winIdx, LineRef firstLine, LineRef lastLine); bool runDiff(const QVector* p1, LineRef size1, const QVector* p2, LineRef size2, DiffList& diffList, e_SrcSelector winIdx1, e_SrcSelector winIdx2, const QSharedPointer &pOptions); }; void calcDiff(const QString &line1, const QString &line2, DiffList& diffList, int match, int maxSearchRange); bool fineDiff( Diff3LineList& diff3LineList, int selector, const QVector* v1, const QVector* v2); inline bool isWhite(QChar c) { return c == ' ' || c == '\t' || c == '\r'; } /** Returns the number of equivalent spaces at position outPos. */ inline int tabber(int outPos, int tabSize) { return tabSize - (outPos % tabSize); } /** Returns a line number where the linerange [line, line+nofLines] can be displayed best. If it fits into the currently visible range then the returned value is the current firstLine. */ int getBestFirstLine(int line, int nofLines, int firstLine, int visibleLines); extern bool g_bIgnoreWhiteSpace; extern bool g_bIgnoreTrivialMatches; extern bool g_bAutoSolve; enum e_CoordType { eFileCoords, eD3LLineCoords, eWrapCoords }; QString calcHistorySortKey(const QString& keyOrder, QRegExp& matchedRegExpr, const QStringList& parenthesesGroupList); bool findParenthesesGroups(const QString& s, QStringList& sl); #endif diff --git a/src/gnudiff_io.cpp b/src/gnudiff_io.cpp index 8c1947a..f19e3ad 100644 --- a/src/gnudiff_io.cpp +++ b/src/gnudiff_io.cpp @@ -1,545 +1,545 @@ /* File I/O for GNU DIFF. Modified for KDiff3 by Joachim Eibl 2003, 2004, 2005. The original file was part of GNU DIFF. Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1998, 2001, 2002 Free Software Foundation, Inc. GNU DIFF is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU DIFF 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "gnudiff_diff.h" #include #include /* Rotate an unsigned value to the left. */ #define ROL(v, n) ((v) << (n) | (v) >> (sizeof(v) * CHAR_BIT - (n))) /* Given a hash value and a new character, return a new hash value. */ #define HASH(h, c) ((c) + ROL(h, 7)) /* The type of a hash value. */ typedef size_t hash_value; static_assert(std::is_unsigned::value, "hash_value must be signed."); /* Lines are put into equivalence classes of lines that match in lines_differ. Each equivalence class is represented by one of these structures, but only while the classes are being computed. Afterward, each class is represented by a number. */ struct equivclass { GNULineRef next; /* Next item in this bucket. */ hash_value hash; /* Hash of lines in this class. */ const QChar *line; /* A line that fits this class. */ size_t length; /* That line's length, not counting its newline. */ }; /* Hash-table: array of buckets, each being a chain of equivalence classes. buckets[-1] is reserved for incomplete lines. */ static GNULineRef *buckets; /* Number of buckets in the hash table array, not counting buckets[-1]. */ static size_t nbuckets; /* Array in which the equivalence classes are allocated. The bucket-chains go through the elements in this array. The number of an equivalence class is its index in this array. */ static equivclass *equivs; /* Index of first free element in the array `equivs'. */ static GNULineRef equivs_index; /* Number of elements allocated in the array `equivs'. */ static GNULineRef equivs_alloc; /* Check for binary files and compare them for exact identity. */ /* Return 1 if BUF contains a non text character. SIZE is the number of characters in BUF. */ #define binary_file_p(buf, size) (memchr(buf, 0, size) != 0) /* Compare two lines (typically one from each input file) according to the command line options. For efficiency, this is invoked only when the lines do not match exactly but an option like -i might cause us to ignore the difference. Return nonzero if the lines differ. */ bool GnuDiff::lines_differ(const QChar *s1, size_t len1, const QChar *s2, size_t len2) { const QChar *t1 = s1; const QChar *t2 = s2; const QChar *s1end = s1 + len1; const QChar *s2end = s2 + len2; for(;; ++t1, ++t2) { /* Test for exact char equality first, since it's a common case. */ if(t1 != s1end && t2 != s2end && *t1 == *t2) continue; else { while(t1 != s1end && ((bIgnoreWhiteSpace && isWhite(*t1)) || (bIgnoreNumbers && (t1->isDigit() || *t1 == '-' || *t1 == '.')))) { ++t1; } while(t2 != s2end && ((bIgnoreWhiteSpace && isWhite(*t2)) || (bIgnoreNumbers && (t2->isDigit() || *t2 == '-' || *t2 == '.')))) { ++t2; } if(t1 != s1end && t2 != s2end) { if(ignore_case) { /* Lowercase comparison. */ if(t1->toLower() == t2->toLower()) continue; } else if(*t1 == *t2) continue; else return true; } else if(t1 == s1end && t2 == s2end) return false; else return true; } } return false; } /* Split the file into lines, simultaneously computing the equivalence class for each line. */ void GnuDiff::find_and_hash_each_line(file_data *current) { hash_value h; const QChar *p = current->prefix_end; QChar c; GNULineRef i, *bucket; size_t length; /* Cache often-used quantities in local variables to help the compiler. */ const QChar **linbuf = current->linbuf; GNULineRef alloc_lines = current->alloc_lines; GNULineRef line = 0; GNULineRef linbuf_base = current->linbuf_base; GNULineRef *cureqs = (GNULineRef *)xmalloc(alloc_lines * sizeof(*cureqs)); equivclass *eqs = equivs; GNULineRef eqs_index = equivs_index; GNULineRef eqs_alloc = equivs_alloc; const QChar *suffix_begin = current->suffix_begin; const QChar *bufend = current->buffer + current->buffered; bool diff_length_compare_anyway = ignore_white_space != IGNORE_NO_WHITE_SPACE || bIgnoreNumbers; bool same_length_diff_contents_compare_anyway = diff_length_compare_anyway | ignore_case; while(p < suffix_begin) { const QChar *ip = p; h = 0; /* Hash this line until we find a newline or bufend is reached. */ if(ignore_case) switch(ignore_white_space) { case IGNORE_ALL_SPACE: while(p < bufend && !Utils::isEndOfLine(c = *p)) { if(!(isWhite(c) || (bIgnoreNumbers && (c.isDigit() || c == '-' || c == '.')))) h = HASH(h, c.toLower().unicode()); ++p; } break; default: while(p < bufend && !Utils::isEndOfLine(c = *p)) { h = HASH(h, c.toLower().unicode()); ++p; } break; } else switch(ignore_white_space) { case IGNORE_ALL_SPACE: while(p < bufend && !Utils::isEndOfLine(c = *p)) { if(!(isWhite(c) || (bIgnoreNumbers && (c.isDigit() || c == '-' || c == '.')))) h = HASH(h, c.unicode()); ++p; } break; default: while(p < bufend && !Utils::isEndOfLine(c = *p)) { h = HASH(h, c.unicode()); ++p; } break; } bucket = &buckets[h % nbuckets]; length = p - ip; ++p; for(i = *bucket;; i = eqs[i].next) if(!i) { /* Create a new equivalence class in this bucket. */ i = eqs_index++; if(i == eqs_alloc) { if((GNULineRef)(GNULINEREF_MAX / (2 * sizeof(*eqs))) <= eqs_alloc) xalloc_die(); eqs_alloc *= 2; eqs = (equivclass *)xrealloc(eqs, eqs_alloc * sizeof(*eqs)); } eqs[i].next = *bucket; eqs[i].hash = h; eqs[i].line = ip; eqs[i].length = length; *bucket = i; break; } else if(eqs[i].hash == h) { const QChar *eqline = eqs[i].line; /* Reuse existing class if lines_differ reports the lines equal. */ if(eqs[i].length == length) { /* Reuse existing equivalence class if the lines are identical. This detects the common case of exact identity faster than lines_differ would. */ if(memcmp(eqline, ip, length * sizeof(QChar)) == 0) break; if(!same_length_diff_contents_compare_anyway) continue; } else if(!diff_length_compare_anyway) continue; if(!lines_differ(eqline, eqs[i].length, ip, length)) break; } /* Maybe increase the size of the line table. */ if(line == alloc_lines) { /* Double (alloc_lines - linbuf_base) by adding to alloc_lines. */ if((GNULineRef)(GNULINEREF_MAX / 3) <= alloc_lines || (GNULineRef)(GNULINEREF_MAX / sizeof(*cureqs)) <= 2 * alloc_lines - linbuf_base || (GNULineRef)(GNULINEREF_MAX / sizeof(ptrdiff_t)) <= alloc_lines - linbuf_base) xalloc_die(); alloc_lines = 2 * alloc_lines - linbuf_base; cureqs = (GNULineRef *)xrealloc(cureqs, alloc_lines * sizeof(*cureqs)); linbuf += linbuf_base; linbuf = (const QChar **)xrealloc(linbuf, (alloc_lines - linbuf_base) * sizeof(ptrdiff_t)); linbuf -= linbuf_base; } linbuf[line] = ip; cureqs[line] = i; ++line; } current->buffered_lines = line; for(i = 0;; ++i) { /* Record the line start for lines in the suffix that we care about. Record one more line start than lines, so that we can compute the length of any buffered line. */ if(line == alloc_lines) { /* Double (alloc_lines - linbuf_base) by adding to alloc_lines. */ if((GNULineRef)(GNULINEREF_MAX / 3) <= alloc_lines || (GNULineRef)(GNULINEREF_MAX / sizeof(*cureqs)) <= 2 * alloc_lines - linbuf_base || (GNULineRef)(GNULINEREF_MAX / sizeof(ptrdiff_t)) <= alloc_lines - linbuf_base) xalloc_die(); alloc_lines = 2 * alloc_lines - linbuf_base; linbuf += linbuf_base; linbuf = (const QChar **)xrealloc(linbuf, (alloc_lines - linbuf_base) * sizeof(ptrdiff_t)); linbuf -= linbuf_base; } linbuf[line] = p; if(p >= bufend) break; if(context <= i && no_diff_means_no_output) break; line++; while(p < bufend && !Utils::isEndOfLine(*p++)) continue; } /* Done with cache in local variables. */ current->linbuf = linbuf; current->valid_lines = line; current->alloc_lines = alloc_lines; current->equivs = cureqs; equivs = eqs; equivs_alloc = eqs_alloc; equivs_index = eqs_index; } /* We have found N lines in a buffer of size S; guess the proportionate number of lines that will be found in a buffer of size T. However, do not guess a number of lines so large that the resulting line table might cause overflow in size calculations. */ GNULineRef GnuDiff::guess_lines(GNULineRef n, size_t s, size_t t) { size_t guessed_bytes_per_line = n < 10 ? 32 : s / (n - 1); size_t guessed_lines = std::max((size_t)1, t / guessed_bytes_per_line); return (GNULineRef)std::min((GNULineRef)guessed_lines, (GNULineRef)(GNULINEREF_MAX / (2 * sizeof(ptrdiff_t) + 1) - 5)) + 5; } /* Given a vector of two file_data objects, find the identical prefixes and suffixes of each object. */ void GnuDiff::find_identical_ends(file_data filevec[]) { /* Find identical prefix. */ const QChar *p0, *p1, *buffer0, *buffer1; p0 = buffer0 = filevec[0].buffer; p1 = buffer1 = filevec[1].buffer; size_t n0, n1; n0 = filevec[0].buffered; n1 = filevec[1].buffered; const QChar *const pEnd0 = p0 + n0; const QChar *const pEnd1 = p1 + n1; if(p0 == p1) /* The buffers are the same; sentinels won't work. */ p0 = p1 += n1; else { /* Loop until first mismatch, or end. */ while(p0 != pEnd0 && p1 != pEnd1 && *p0 == *p1) { p0++; p1++; } } /* Now P0 and P1 point at the first nonmatching characters. */ /* Skip back to last line-beginning in the prefix. */ while(p0 != buffer0 && !Utils::isEndOfLine(p0[-1])) p0--, p1--; /* Record the prefix. */ filevec[0].prefix_end = p0; filevec[1].prefix_end = p1; /* Find identical suffix. */ /* P0 and P1 point beyond the last chars not yet compared. */ p0 = buffer0 + n0; p1 = buffer1 + n1; const QChar *end0, *beg0; end0 = p0; /* Addr of last char in file 0. */ /* Get value of P0 at which we should stop scanning backward: this is when either P0 or P1 points just past the last char of the identical prefix. */ beg0 = filevec[0].prefix_end + (n0 < n1 ? 0 : n0 - n1); /* Scan back until chars don't match or we reach that point. */ for(; p0 != beg0; p0--, p1--) { if(*p0 != *p1) { /* Point at the first char of the matching suffix. */ beg0 = p0; break; } } // Go to the next line (skip last line with a difference) if(p0 != end0) { if(*p0 != *p1) ++p0; while(p0 < pEnd0 && !Utils::isEndOfLine(*p0++)) continue; } p1 += p0 - beg0; /* Record the suffix. */ filevec[0].suffix_begin = p0; filevec[1].suffix_begin = p1; /* Calculate number of lines of prefix to save. prefix_count == 0 means save the whole prefix; we need this for options like -D that output the whole file, or for enormous contexts (to avoid worrying about arithmetic overflow). We also need it for options like -F that output some preceding line; at least we will need to find the last few lines, but since we don't know how many, it's easiest to find them all. Otherwise, prefix_count != 0. Save just prefix_count lines at start of the line buffer; they'll be moved to the proper location later. Handle 1 more line than the context says (because we count 1 too many), rounded up to the next power of 2 to speed index computation. */ const QChar **linbuf0, **linbuf1; GNULineRef alloc_lines0, alloc_lines1; GNULineRef buffered_prefix, prefix_count, prefix_mask; GNULineRef middle_guess, suffix_guess; if(no_diff_means_no_output && context < (GNULineRef)(GNULINEREF_MAX / 4) && context < (GNULineRef)(n0)) { middle_guess = guess_lines(0, 0, p0 - filevec[0].prefix_end); suffix_guess = guess_lines(0, 0, buffer0 + n0 - p0); for(prefix_count = 1; prefix_count <= context; prefix_count *= 2) continue; alloc_lines0 = (prefix_count + middle_guess + std::min(context, suffix_guess)); } else { prefix_count = 0; alloc_lines0 = guess_lines(0, 0, n0); } prefix_mask = prefix_count - 1; GNULineRef lines = 0; linbuf0 = (const QChar **)xmalloc(alloc_lines0 * sizeof(ptrdiff_t)); p0 = buffer0; /* If the prefix is needed, find the prefix lines. */ if(!(no_diff_means_no_output && filevec[0].prefix_end == p0 && filevec[1].prefix_end == p1)) { end0 = filevec[0].prefix_end; while(p0 != end0) { GNULineRef l = lines++ & prefix_mask; if(l == alloc_lines0) { if((GNULineRef)(GNULINEREF_MAX / (2 * sizeof(ptrdiff_t))) <= alloc_lines0) xalloc_die(); alloc_lines0 *= 2; linbuf0 = (const QChar **)xrealloc(linbuf0, alloc_lines0 * sizeof(ptrdiff_t)); } linbuf0[l] = p0; while(p0 < pEnd0 && !Utils::isEndOfLine(*p0++)) continue; } } buffered_prefix = prefix_count && context < lines ? context : lines; /* Allocate line buffer 1. */ middle_guess = guess_lines(lines, p0 - buffer0, p1 - filevec[1].prefix_end); suffix_guess = guess_lines(lines, p0 - buffer0, buffer1 + n1 - p1); alloc_lines1 = buffered_prefix + middle_guess + std::min(context, suffix_guess); if(alloc_lines1 < buffered_prefix || (GNULineRef)(GNULINEREF_MAX / sizeof(ptrdiff_t)) <= alloc_lines1) xalloc_die(); linbuf1 = (const QChar **)xmalloc(alloc_lines1 * sizeof(ptrdiff_t)); GNULineRef i; if(buffered_prefix != lines) { /* Rotate prefix lines to proper location. */ for(i = 0; i < buffered_prefix; ++i) linbuf1[i] = linbuf0[(lines - context + i) & prefix_mask]; for(i = 0; i < buffered_prefix; ++i) linbuf0[i] = linbuf1[i]; } /* Initialize line buffer 1 from line buffer 0. */ for(i = 0; i < buffered_prefix; ++i) linbuf1[i] = linbuf0[i] - buffer0 + buffer1; /* Record the line buffer, adjusted so that linbuf[0] points at the first differing line. */ filevec[0].linbuf = linbuf0 + buffered_prefix; filevec[1].linbuf = linbuf1 + buffered_prefix; filevec[0].linbuf_base = filevec[1].linbuf_base = -buffered_prefix; filevec[0].alloc_lines = alloc_lines0 - buffered_prefix; filevec[1].alloc_lines = alloc_lines1 - buffered_prefix; filevec[0].prefix_lines = filevec[1].prefix_lines = lines; } /* If 1 < k, then (2**k - prime_offset[k]) is the largest prime less than 2**k. This table is derived from Chris K. Caldwell's list - . */ + . */ static unsigned char const prime_offset[] = { 0, 0, 1, 1, 3, 1, 3, 1, 5, 3, 3, 9, 3, 1, 3, 19, 15, 1, 5, 1, 3, 9, 3, 15, 3, 39, 5, 39, 57, 3, 35, 1, 5, 9, 41, 31, 5, 25, 45, 7, 87, 21, 11, 57, 17, 55, 21, 115, 59, 81, 27, 129, 47, 111, 33, 55, 5, 13, 27, 55, 93, 1, 57, 25}; /* Verify that this host's size_t is not too wide for the above table. */ static_assert(sizeof(size_t) * CHAR_BIT <= sizeof prime_offset, "Not enough primes in table"); /* Given a vector of two file_data objects, read the file associated with each one, and build the table of equivalence classes. Return nonzero if either file appears to be a binary file. If PRETEND_BINARY is nonzero, pretend they are binary regardless. */ bool GnuDiff::read_files(file_data filevec[], bool /*pretend_binary*/) { GNULineRef i; find_identical_ends(filevec); equivs_alloc = filevec[0].alloc_lines + filevec[1].alloc_lines + 1; if((GNULineRef)(GNULINEREF_MAX / sizeof(*equivs)) <= equivs_alloc) xalloc_die(); equivs = (equivclass *)xmalloc(equivs_alloc * sizeof(*equivs)); /* Equivalence class 0 is permanently safe for lines that were not hashed. Real equivalence classes start at 1. */ equivs_index = 1; /* Allocate (one plus) a prime number of hash buckets. Use a prime number between 1/3 and 2/3 of the value of equiv_allocs, approximately. */ for(i = 9; ((GNULineRef)1 << i) < equivs_alloc / 3; ++i) continue; nbuckets = ((GNULineRef)1 << i) - prime_offset[i]; if(GNULINEREF_MAX / sizeof(*buckets) <= nbuckets) xalloc_die(); buckets = (GNULineRef *)zalloc((nbuckets + 1) * sizeof(*buckets)); buckets++; for(i = 0; i < 2; ++i) find_and_hash_each_line(&filevec[i]); filevec[0].equiv_max = filevec[1].equiv_max = equivs_index; free(equivs); free(buckets - 1); return false; }