1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of Qt Creator.
7 **
8 ** Commercial License Usage
9 ** Licensees holding valid commercial Qt licenses may use this file in
10 ** accordance with the commercial license agreement provided with the
11 ** Software or, alternatively, in accordance with the terms contained in
12 ** a written agreement between you and The Qt Company. For licensing terms
13 ** and conditions see https://www.qt.io/terms-conditions. For further
14 ** information use the contact form at https://www.qt.io/contact-us.
15 **
16 ** GNU General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU
18 ** General Public License version 3 as published by the Free Software
19 ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
20 ** included in the packaging of this file. Please review the following
21 ** information to ensure the GNU General Public License requirements will
22 ** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23 **
24 ****************************************************************************/
25 
26 #include "semantichighlighter.h"
27 
28 #include <texteditor/fontsettings.h>
29 #include <texteditor/semantichighlighter.h>
30 #include <texteditor/syntaxhighlighter.h>
31 #include <texteditor/textdocument.h>
32 #include <texteditor/textdocumentlayout.h>
33 
34 #include <utils/algorithm.h>
35 #include <utils/qtcassert.h>
36 
37 #include <QLoggingCategory>
38 #include <QTextDocument>
39 
40 using namespace TextEditor;
41 
42 using SemanticHighlighter::incrementalApplyExtraAdditionalFormats;
43 using SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd;
44 
45 static Q_LOGGING_CATEGORY(log, "qtc.cpptools.semantichighlighter", QtWarningMsg)
46 
47 namespace CppTools {
48 
parenSource()49 static Utils::Id parenSource() { return "CppTools"; }
50 
51 static const QList<std::pair<HighlightingResult, QTextBlock>>
splitRawStringLiteral(const HighlightingResult & result,const QTextBlock & startBlock)52 splitRawStringLiteral(const HighlightingResult &result, const QTextBlock &startBlock)
53 {
54     if (result.textStyles.mainStyle != C_STRING)
55         return {{result, startBlock}};
56 
57     QTextCursor cursor(startBlock);
58     cursor.setPosition(cursor.position() + result.column - 1);
59     cursor.setPosition(cursor.position() + result.length, QTextCursor::KeepAnchor);
60     const QString theString = cursor.selectedText();
61 
62     // Find all the components of a raw string literal. If we don't succeed, then it's
63     // something else.
64     if (!theString.endsWith('"'))
65         return {{result, startBlock}};
66     int rOffset = -1;
67     if (theString.startsWith("R\"")) {
68         rOffset = 0;
69     } else if (theString.startsWith("LR\"")
70                || theString.startsWith("uR\"")
71                || theString.startsWith("UR\"")) {
72         rOffset = 1;
73     } else if (theString.startsWith("u8R\"")) {
74         rOffset = 2;
75     }
76     if (rOffset == -1)
77         return {{result, startBlock}};
78     const int delimiterOffset = rOffset + 2;
79     const int openParenOffset = theString.indexOf('(', delimiterOffset);
80     if (openParenOffset == -1)
81         return {{result, startBlock}};
82     const QStringView delimiter = theString.mid(delimiterOffset, openParenOffset - delimiterOffset);
83     const int endDelimiterOffset = theString.length() - 1 - delimiter.length();
84     if (theString.mid(endDelimiterOffset, delimiter.length()) != delimiter)
85         return {{result, startBlock}};
86     if (theString.at(endDelimiterOffset - 1) != ')')
87         return {{result, startBlock}};
88 
89     // Now split the result. For clarity, we display only the actual content as a string,
90     // and the rest (including the delimiter) as a keyword.
91     HighlightingResult prefix = result;
92     prefix.textStyles.mainStyle = C_KEYWORD;
93     prefix.textStyles.mixinStyles = {};
94     prefix.length = delimiterOffset + delimiter.length() + 1;
95     cursor.setPosition(startBlock.position() + result.column - 1 + prefix.length);
96     QTextBlock stringBlock = cursor.block();
97     HighlightingResult actualString = result;
98     actualString.line = stringBlock.blockNumber() + 1;
99     actualString.column = cursor.positionInBlock() + 1;
100     actualString.length = endDelimiterOffset - openParenOffset - 2;
101     cursor.setPosition(cursor.position() + actualString.length);
102     QTextBlock suffixBlock = cursor.block();
103     HighlightingResult suffix = result;
104     suffix.textStyles.mainStyle = C_KEYWORD;
105     suffix.textStyles.mixinStyles = {};
106     suffix.line = suffixBlock.blockNumber() + 1;
107     suffix.column = cursor.positionInBlock() + 1;
108     suffix.length = delimiter.length() + 2;
109     QTC_CHECK(prefix.length + actualString.length + suffix.length == result.length);
110 
111     return {{prefix, startBlock}, {actualString, stringBlock}, {suffix, suffixBlock}};
112 }
113 
SemanticHighlighter(TextDocument * baseTextDocument)114 SemanticHighlighter::SemanticHighlighter(TextDocument *baseTextDocument)
115     : QObject(baseTextDocument)
116     , m_baseTextDocument(baseTextDocument)
117 {
118     QTC_CHECK(m_baseTextDocument);
119     updateFormatMapFromFontSettings();
120 }
121 
~SemanticHighlighter()122 SemanticHighlighter::~SemanticHighlighter()
123 {
124     if (m_watcher) {
125         disconnectWatcher();
126         m_watcher->cancel();
127         m_watcher->waitForFinished();
128     }
129 }
130 
setHighlightingRunner(HighlightingRunner highlightingRunner)131 void SemanticHighlighter::setHighlightingRunner(HighlightingRunner highlightingRunner)
132 {
133     m_highlightingRunner = highlightingRunner;
134 }
135 
run()136 void SemanticHighlighter::run()
137 {
138     QTC_ASSERT(m_highlightingRunner, return);
139 
140     qCDebug(log) << "SemanticHighlighter: run()";
141 
142     if (m_watcher) {
143         disconnectWatcher();
144         m_watcher->cancel();
145     }
146     m_watcher.reset(new QFutureWatcher<HighlightingResult>);
147     connectWatcher();
148 
149     m_revision = documentRevision();
150     m_watcher->setFuture(m_highlightingRunner());
151 }
152 
getClearedParentheses(const QTextBlock & block)153 static Parentheses getClearedParentheses(const QTextBlock &block)
154 {
155     return Utils::filtered(TextDocumentLayout::parentheses(block), [](const Parenthesis &p) {
156         return p.source != parenSource();
157     });
158 }
159 
onHighlighterResultAvailable(int from,int to)160 void SemanticHighlighter::onHighlighterResultAvailable(int from, int to)
161 {
162     if (documentRevision() != m_revision)
163         return; // outdated
164     if (!m_watcher || m_watcher->isCanceled())
165         return; // aborted
166 
167     qCDebug(log) << "onHighlighterResultAvailable()" << from << to;
168 
169     SyntaxHighlighter *highlighter = m_baseTextDocument->syntaxHighlighter();
170     QTC_ASSERT(highlighter, return);
171     incrementalApplyExtraAdditionalFormats(highlighter, m_watcher->future(), from, to, m_formatMap,
172                                            &splitRawStringLiteral);
173 
174     // In addition to the paren matching that the syntactic highlighter does
175     // (parentheses, braces, brackets, comments), here we inject info from the code model
176     // for angle brackets in templates and the ternary operator.
177     QPair<QTextBlock, Parentheses> parentheses;
178     for (int i = from; i < to; ++i) {
179         const HighlightingResult &result = m_watcher->future().resultAt(i);
180         if (result.kind != AngleBracketOpen && result.kind != AngleBracketClose
181                 && result.kind != DoubleAngleBracketClose
182                 && result.kind != TernaryIf && result.kind != TernaryElse) {
183             const QTextBlock block =
184                     m_baseTextDocument->document()->findBlockByNumber(result.line - 1);
185             TextDocumentLayout::setParentheses(block, getClearedParentheses(block));
186             continue;
187         }
188         if (parentheses.first.isValid() && result.line - 1 > parentheses.first.blockNumber()) {
189             TextDocumentLayout::setParentheses(parentheses.first, parentheses.second);
190             parentheses = {};
191         }
192         if (!parentheses.first.isValid()) {
193             parentheses.first = m_baseTextDocument->document()->findBlockByNumber(result.line - 1);
194             parentheses.second = getClearedParentheses(parentheses.first);
195         }
196         Parenthesis paren;
197         if (result.kind == AngleBracketOpen) {
198             paren = {Parenthesis::Opened, '<', result.column - 1};
199         } else if (result.kind == AngleBracketClose) {
200             paren = {Parenthesis::Closed, '>', result.column - 1};
201         } else if (result.kind == DoubleAngleBracketClose) {
202             Parenthesis extraParen = {Parenthesis::Closed, '>', result.column - 1};
203             extraParen.source = parenSource();
204             parentheses.second.append(extraParen);
205             paren = {Parenthesis::Closed, '>', result.column};
206         } else if (result.kind == TernaryIf) {
207             paren = {Parenthesis::Opened, '?', result.column - 1};
208         } else if (result.kind == TernaryElse) {
209             paren = {Parenthesis::Closed, ':', result.column - 1};
210         }
211         QTC_ASSERT(paren.pos != -1, continue);
212         paren.source = parenSource();
213 
214         static const auto posCmp = [](const Parenthesis &p1, const Parenthesis &p2) {
215             return p1.pos < p2.pos;
216         };
217         const auto it = std::lower_bound(parentheses.second.begin(), parentheses.second.end(),
218                                          paren, posCmp);
219         parentheses.second.insert(it, paren);
220     }
221     if (parentheses.first.isValid())
222         TextDocumentLayout::setParentheses(parentheses.first, parentheses.second);
223 }
224 
onHighlighterFinished()225 void SemanticHighlighter::onHighlighterFinished()
226 {
227     QTC_ASSERT(m_watcher, return);
228     if (!m_watcher->isCanceled() && documentRevision() == m_revision) {
229         SyntaxHighlighter *highlighter = m_baseTextDocument->syntaxHighlighter();
230         if (QTC_GUARD(highlighter)) {
231             qCDebug(log) << "onHighlighterFinished() - clearing formats";
232             clearExtraAdditionalFormatsUntilEnd(highlighter, m_watcher->future());
233         }
234     }
235 
236     // Clear out previous "semantic parentheses".
237     QTextBlock firstResultBlock;
238     QTextBlock lastResultBlock;
239     if (m_watcher->future().resultCount() == 0) {
240         firstResultBlock = lastResultBlock = m_baseTextDocument->document()->lastBlock();
241     } else {
242         firstResultBlock = m_baseTextDocument->document()->findBlockByNumber(
243                     m_watcher->resultAt(0).line - 1);
244         lastResultBlock = m_baseTextDocument->document()->findBlockByNumber(
245                     m_watcher->future().resultAt(m_watcher->future().resultCount() - 1).line - 1);
246     }
247     for (QTextBlock currentBlock = m_baseTextDocument->document()->firstBlock();
248          currentBlock != firstResultBlock; currentBlock = currentBlock.next()) {
249         TextDocumentLayout::setParentheses(currentBlock, getClearedParentheses(currentBlock));
250     }
251     for (QTextBlock currentBlock = lastResultBlock.next(); currentBlock.isValid();
252          currentBlock = currentBlock.next()) {
253         TextDocumentLayout::setParentheses(currentBlock, getClearedParentheses(currentBlock));
254     }
255 
256     m_watcher.reset();
257 }
258 
connectWatcher()259 void SemanticHighlighter::connectWatcher()
260 {
261     using Watcher = QFutureWatcher<HighlightingResult>;
262     connect(m_watcher.data(), &Watcher::resultsReadyAt,
263             this, &SemanticHighlighter::onHighlighterResultAvailable);
264     connect(m_watcher.data(), &Watcher::finished,
265             this, &SemanticHighlighter::onHighlighterFinished);
266 }
267 
disconnectWatcher()268 void SemanticHighlighter::disconnectWatcher()
269 {
270     using Watcher = QFutureWatcher<HighlightingResult>;
271     disconnect(m_watcher.data(), &Watcher::resultsReadyAt,
272                this, &SemanticHighlighter::onHighlighterResultAvailable);
273     disconnect(m_watcher.data(), &Watcher::finished,
274                this, &SemanticHighlighter::onHighlighterFinished);
275 }
276 
documentRevision() const277 unsigned SemanticHighlighter::documentRevision() const
278 {
279     return m_baseTextDocument->document()->revision();
280 }
281 
updateFormatMapFromFontSettings()282 void SemanticHighlighter::updateFormatMapFromFontSettings()
283 {
284     QTC_ASSERT(m_baseTextDocument, return);
285 
286     const FontSettings &fs = m_baseTextDocument->fontSettings();
287 
288     m_formatMap[TypeUse] = fs.toTextCharFormat(C_TYPE);
289     m_formatMap[LocalUse] = fs.toTextCharFormat(C_LOCAL);
290     m_formatMap[FieldUse] = fs.toTextCharFormat(C_FIELD);
291     m_formatMap[EnumerationUse] = fs.toTextCharFormat(C_ENUMERATION);
292     m_formatMap[VirtualMethodUse] = fs.toTextCharFormat(C_VIRTUAL_METHOD);
293     m_formatMap[LabelUse] = fs.toTextCharFormat(C_LABEL);
294     m_formatMap[MacroUse] = fs.toTextCharFormat(C_PREPROCESSOR);
295     m_formatMap[FunctionUse] = fs.toTextCharFormat(C_FUNCTION);
296     m_formatMap[FunctionDeclarationUse] =
297             fs.toTextCharFormat(TextStyles::mixinStyle(C_FUNCTION, C_DECLARATION));
298     m_formatMap[VirtualFunctionDeclarationUse] =
299             fs.toTextCharFormat(TextStyles::mixinStyle(C_VIRTUAL_METHOD, C_DECLARATION));
300     m_formatMap[PseudoKeywordUse] = fs.toTextCharFormat(C_KEYWORD);
301     m_formatMap[StringUse] = fs.toTextCharFormat(C_STRING);
302 }
303 
304 } // namespace CppTools
305