Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmllscompletion.cpp
Go to the documentation of this file.
1// Copyright (C) 2024 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6
7#include <QtCore/qdiriterator.h>
8#include <QtCore/qfile.h>
9
11
12Q_LOGGING_CATEGORY(QQmlLSCompletionLog, "qt.languageserver.completions")
13
14using namespace QLspSpecification;
15using namespace QQmlJS::Dom;
16using namespace Qt::StringLiterals;
17
18/*!
19\class QQmlLSCompletion
20\internal
21\brief QQmlLSCompletion provides completions for all kinds of QML and JS constructs.
22
23Use the \l{completions} method to obtain completions at a certain DomItem.
24
25All the other methods in this class are helper methods: some compute completions for specific QML
26and JS constructs and some are shared between multiple QML or JS constructs to avoid code
27duplication. Most of the helper methods add their completion items via a BackInsertIterator.
28
29Some helper methods are called "suggest*" and will try to suggest code that does not exist yet. For
30example, any JS statement can be expected inside a Blockstatement so suggestJSStatementCompletion()
31is used to suggest JS statements inside of BlockStatements. Another example might be
32suggestReachableTypes() that will suggest Types for type annotations, attached types or Qml Object
33hierarchies, or suggestCaseAndDefaultStatementCompletion() that will only suggest "case" and
34"default" clauses for switch statements.
35
36Some helper methods are called "inside*" and will try to suggest code inside an existing structure.
37For example, insideForStatementCompletion() will try to suggest completion for the different code
38pieces initializer, condition, increment and statement that exist inside of:
39\badcode
40for(initializer; condition; increment)
41 statement
42\endcode
43*/
44
45CompletionItem QQmlLSCompletion::makeSnippet(QUtf8StringView qualifier, QUtf8StringView label,
46 QUtf8StringView insertText)
47{
48 CompletionItem res;
49 if (!qualifier.isEmpty()) {
50 res.label = qualifier.data();
51 res.label += '.';
52 }
53 res.label += label.data();
54 res.insertTextFormat = InsertTextFormat::Snippet;
55 if (!qualifier.isEmpty()) {
56 res.insertText = qualifier.data();
57 *res.insertText += '.';
58 *res.insertText += insertText.data();
59 } else {
60 res.insertText = insertText.data();
61 }
62 res.kind = CompletionItemKind::Snippet;
63 res.insertTextMode = InsertTextMode::AdjustIndentation;
64 return res;
65}
66
67CompletionItem QQmlLSCompletion::makeSnippet(QUtf8StringView label, QUtf8StringView insertText)
68{
69 return makeSnippet(QByteArray(), label, insertText);
70}
71
72/*!
73\internal
74\brief Compare left and right locations to the position denoted by ctx, see special cases below.
75
76Statements and expressions need to provide different completions depending on where the cursor is.
77For example, lets take following for-statement:
78\badcode
79for (let i = 0; <here> ; ++i) {}
80\endcode
81We want to provide script expression completion (method names, property names, available JS
82variables names, QML objects ids, and so on) at the place denoted by \c{<here>}.
83The question is: how do we know that the cursor is really at \c{<here>}? In the case of the
84for-loop, we can compare the position of the cursor with the first and the second semicolon of the
85for loop.
86
87If the first semicolon does not exist, it has an invalid sourcelocation and the cursor is
88definitively \e{not} at \c{<here>}. Therefore, return false when \c{left} is invalid.
89
90If the second semicolon does not exist, then just ignore it: it might not have been written yet.
91*/
92bool QQmlLSCompletion::betweenLocations(QQmlJS::SourceLocation left,
93 const QQmlLSCompletionPosition &positionInfo,
94 QQmlJS::SourceLocation right) const
95{
96 if (!left.isValid())
97 return false;
98 // note: left.end() == ctx.offset() means that the cursor lies exactly after left
99 if (!(left.end() <= positionInfo.offset()))
100 return false;
101 if (!right.isValid())
102 return true;
103
104 // note: ctx.offset() == right.begin() means that the cursor lies exactly before right
105 return positionInfo.offset() <= right.begin();
106}
107
108/*!
109\internal
110Returns true if ctx denotes an offset lying behind left.end(), and false otherwise.
111*/
112bool QQmlLSCompletion::afterLocation(QQmlJS::SourceLocation left,
113 const QQmlLSCompletionPosition &positionInfo) const
114{
115 return betweenLocations(left, positionInfo, QQmlJS::SourceLocation{});
116}
117
118/*!
119\internal
120Returns true if ctx denotes an offset lying before right.begin(), and false otherwise.
121*/
122bool QQmlLSCompletion::beforeLocation(const QQmlLSCompletionPosition &ctx,
123 QQmlJS::SourceLocation right) const
124{
125 if (!right.isValid())
126 return true;
127
128 // note: ctx.offset() == right.begin() means that the cursor lies exactly before right
129 if (ctx.offset() <= right.begin())
130 return true;
131
132 return false;
133}
134
135bool QQmlLSCompletion::ctxBeforeStatement(const QQmlLSCompletionPosition &positionInfo,
136 const DomItem &parentForContext,
137 FileLocationRegion firstRegion) const
138{
139 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
140 const bool result = beforeLocation(positionInfo, regions[firstRegion]);
141 return result;
142}
143
144void
145QQmlLSCompletion::suggestBindingCompletion(const DomItem &itemAtPosition, BackInsertIterator it) const
146{
147 suggestReachableTypes(itemAtPosition, LocalSymbolsType::AttachedType, CompletionItemKind::Class,
148 it);
149
150 const auto scope = [&]() -> QQmlJSScope::ConstPtr {
151 const DomItem owner = ownerOfQualifiedExpression(itemAtPosition);
152 if (!owner)
153 return itemAtPosition.qmlObject().semanticScope();
154
155 const auto expressionType = QQmlLSUtils::resolveExpressionType(
156 owner, QQmlLSUtils::ResolveActualTypeForFieldMemberExpression);
157
158 // no properties nor signal handlers inside a qualified import
159 if (!expressionType || expressionType->type == QQmlLSUtils::QualifiedModuleIdentifier)
160 return {};
161
162 return expressionType->semanticScope;
163 }();
164
165 if (!scope)
166 return;
167
168 propertyCompletion(scope, nullptr, it);
169 signalHandlerCompletion(scope, nullptr, it);
170}
171
172void QQmlLSCompletion::idsCompletions(const DomItem &component, BackInsertIterator it) const
173{
174 qCDebug(QQmlLSCompletionLog) << "adding ids completions";
175 for (const QString &k : component.field(Fields::ids).keys()) {
176 CompletionItem comp;
177 comp.label = k.toUtf8();
178 comp.kind = CompletionItemKind::Value;
179 it = comp;
180 }
181}
182
183static bool testScopeSymbol(const QQmlJSScope::ConstPtr &scope, LocalSymbolsTypes options,
184 CompletionItemKind kind)
185{
186 const bool currentIsSingleton = scope->isSingleton();
187 const bool currentIsAttached = !scope->attachedType().isNull();
188 if ((options & LocalSymbolsType::Singleton) && currentIsSingleton) {
189 return true;
190 }
191 if ((options & LocalSymbolsType::AttachedType) && currentIsAttached) {
192 return true;
193 }
194 const bool isObjectType = scope->isReferenceType();
195 if (options & LocalSymbolsType::ObjectType && !currentIsSingleton && isObjectType) {
196 return kind != CompletionItemKind::Constructor || scope->isCreatable();
197 }
198 if (options & LocalSymbolsType::ValueType && !currentIsSingleton && !isObjectType) {
199 return true;
200 }
201 return false;
202}
203
204/*!
205\internal
206Obtain the types reachable from \c{el} as a CompletionItems.
207*/
208void QQmlLSCompletion::suggestReachableTypes(const DomItem &el, LocalSymbolsTypes options,
209 CompletionItemKind kind, BackInsertIterator it) const
210{
211 auto file = el.containingFile().as<QmlFile>();
212 if (!file)
213 return;
214 auto resolver = file->typeResolver();
215 if (!resolver)
216 return;
217
218 const QString requiredQualifiers = QQmlLSUtils::qualifiersFrom(el);
219 const auto keyValueRange = resolver->importedTypes().asKeyValueRange();
220 for (const auto &type : keyValueRange) {
221 // ignore special QQmlJSImporterMarkers
222 const bool isMarkerType = type.first.contains(u"$internal$.")
223 || type.first.contains(u"$anonymous$.") || type.first.contains(u"$module$.");
224 if (isMarkerType || !type.first.startsWith(requiredQualifiers))
225 continue;
226
227 auto &scope = type.second.scope;
228 if (!scope)
229 continue;
230
231 if (!testScopeSymbol(scope, options, kind))
232 continue;
233
234 CompletionItem completion;
235 completion.label = QStringView(type.first).sliced(requiredQualifiers.size()).toUtf8();
236 completion.kind = kind;
237 it = completion;
238 }
239}
240
241void QQmlLSCompletion::jsIdentifierCompletion(const QQmlJSScope::ConstPtr &scope,
242 QDuplicateTracker<QString> *usedNames,
243 BackInsertIterator it) const
244{
245 for (const auto &[name, jsIdentifier] : scope->ownJSIdentifiers().asKeyValueRange()) {
246 CompletionItem completion;
247 if (usedNames && usedNames->hasSeen(name)) {
248 continue;
249 }
250 completion.label = name.toUtf8();
251 completion.kind = CompletionItemKind::Variable;
252 QString detail = u"has type "_s;
253 if (jsIdentifier.typeName) {
254 if (jsIdentifier.isConst) {
255 detail.append(u"const ");
256 }
257 detail.append(*jsIdentifier.typeName);
258 } else {
259 detail.append(jsIdentifier.isConst ? u"const"_s : u"var"_s);
260 }
261 completion.detail = detail.toUtf8();
262 it = completion;
263 }
264}
265
266void QQmlLSCompletion::methodCompletion(const QQmlJSScope::ConstPtr &scope,
267 QDuplicateTracker<QString> *usedNames,
268 BackInsertIterator it) const
269{
270 // JS functions in current and base scopes
271 for (const auto &[name, method] : scope->methods().asKeyValueRange()) {
272 if (method.access() != QQmlJSMetaMethod::Public)
273 continue;
274 if (usedNames && usedNames->hasSeen(name)) {
275 continue;
276 }
277 CompletionItem completion;
278 completion.label = name.toUtf8();
279 completion.kind = CompletionItemKind::Method;
280 it = completion;
281 // TODO: QQmlLSUtils::reachableSymbols seems to be able to do documentation and detail
282 // and co, it should also be done here if possible.
283 }
284}
285
286void QQmlLSCompletion::propertyCompletion(const QQmlJSScope::ConstPtr &scope,
287 QDuplicateTracker<QString> *usedNames,
288 BackInsertIterator it) const
289{
290 for (const auto &[name, property] : scope->properties().asKeyValueRange()) {
291 if (usedNames && usedNames->hasSeen(name)) {
292 continue;
293 }
294 CompletionItem completion;
295 completion.label = name.toUtf8();
296 completion.kind = CompletionItemKind::Property;
297 QString detail{ u"has type "_s };
298 if (!property.isWritable())
299 detail.append(u"readonly "_s);
300 detail.append(property.typeName().isEmpty() ? u"var"_s : property.typeName());
301 completion.detail = detail.toUtf8();
302 it = completion;
303 }
304}
305
306void QQmlLSCompletion::enumerationCompletion(const QQmlJSScope::ConstPtr &scope,
307 QDuplicateTracker<QString> *usedNames,
308 BackInsertIterator it) const
309{
310 for (const QQmlJSMetaEnum &enumerator : scope->enumerations()) {
311 if (usedNames && usedNames->hasSeen(enumerator.name())) {
312 continue;
313 }
314 CompletionItem completion;
315 completion.label = enumerator.name().toUtf8();
316 completion.kind = CompletionItemKind::Enum;
317 it = completion;
318 }
319}
320
321void QQmlLSCompletion::enumerationValueCompletionHelper(const QStringList &enumeratorKeys,
322 BackInsertIterator it) const
323{
324 for (const QString &enumeratorKey : enumeratorKeys) {
325 CompletionItem completion;
326 completion.label = enumeratorKey.toUtf8();
327 completion.kind = CompletionItemKind::EnumMember;
328 it = completion;
329 }
330}
331
332/*!
333\internal
334Creates completion items for enumerationvalues.
335If enumeratorName is a valid enumerator then only do completion for the requested enumerator, and
336otherwise do completion for \b{all other possible} enumerators.
337
338For example:
339```
340id: someItem
341enum Hello { World }
342enum MyEnum { ValueOne, ValueTwo }
343
344// Hello does refer to a enumerator:
345property var a: Hello.<complete only World here>
346
347// someItem does not refer to a enumerator:
348property var b: someItem.<complete World, ValueOne and ValueTwo here>
349```
350*/
351
352void QQmlLSCompletion::enumerationValueCompletion(const QQmlJSScope::ConstPtr &scope,
353 const QString &enumeratorName,
354 BackInsertIterator result) const
355{
356 auto enumerator = scope->enumeration(enumeratorName);
357 if (enumerator.isValid()) {
358 enumerationValueCompletionHelper(enumerator.keys(), result);
359 return;
360 }
361
362 const bool enforcesScopedEnums = scope->enforcesScopedEnums();
363 for (const QQmlJSMetaEnum &enumerator : scope->enumerations()) {
364 if (enforcesScopedEnums && enumerator.isScoped())
365 continue;
366 enumerationValueCompletionHelper(enumerator.keys(), result);
367 }
368}
369
370/*!
371\internal
372Calls F on all JavaScript-parents of scope. For example, you can use this method to
373collect all the JavaScript Identifiers from following code:
374```
375{ // this block statement contains only 'x'
376 let x = 3;
377 { // this block statement contains only 'y', and 'x' has to be retrieved via its parent.
378 let y = 4;
379 }
380}
381```
382*/
383template<typename F>
384void collectFromAllJavaScriptParents(const F &&f, const QQmlJSScope::ConstPtr &scope)
385{
386 for (QQmlJSScope::ConstPtr current = scope; current; current = current->parentScope()) {
387 f(current);
388 if (current->scopeType() == QQmlSA::ScopeType::QMLScope)
389 return;
390 }
391}
392
393/*!
394\internal
395Suggest enumerations (if applicable) and enumeration values from \c scope, for example \c
396Asynchronous from the \c CompilationMode enum:
397
398\qml
399property var xxx: Component.Asynchronous // Component contains the \c CompilationMode enum
400property var xxx2: CompilationMode.Asynchronous
401\endqml
402*/
403void QQmlLSCompletion::suggestEnumerationsAndEnumerationValues(
404 const QQmlJSScope::ConstPtr &scope, const QString &enumName,
405 QDuplicateTracker<QString> &usedNames, BackInsertIterator result) const
406{
407 enumerationValueCompletion(scope, enumName, result);
408
409 // skip enumeration types if already inside an enumeration type
410 if (auto enumerator = scope->enumeration(enumName); !enumerator.isValid()) {
411 enumerationCompletion(scope, &usedNames, result);
412 }
413}
414
415/*!
416\internal
417
418Returns the owner of a qualified expression for further resolving, for example:
4191. \c owner from the \c member ScriptExpression in \c {owner.member}. This happens when completion
420is requested on \c member.
4212. \c owner from the ScriptBinaryExpression \c {owner.member}. This happens when completion is
422requested on the dot between \c owner and \c member.
4233. An empty DomItem otherwise.
424*/
425DomItem QQmlLSCompletion::ownerOfQualifiedExpression(const DomItem &qualifiedExpression) const
426{
427 // note: there is an edge case, where the user asks for completion right after the dot
428 // of some qualified expression like `root.hello`. In this case, scriptIdentifier is actually
429 // the BinaryExpression instead of the left-hand-side that has not be written down yet.
430 const bool askForCompletionOnDot = QQmlLSUtils::isFieldMemberExpression(qualifiedExpression);
431 const bool hasQualifier =
432 QQmlLSUtils::isFieldMemberAccess(qualifiedExpression) || askForCompletionOnDot;
433
434 if (!hasQualifier)
435 return {};
436
437 const DomItem owner =
438 (askForCompletionOnDot ? qualifiedExpression : qualifiedExpression.directParent())
439 .field(Fields::left);
440 return owner;
441}
442
443/*!
444\internal
445Generate autocompletions for JS expressions, suggest possible properties, methods, etc.
446
447If scriptIdentifier is inside a Field Member Expression, like \c{onCompleted} in
448\c{Component.onCompleted} for example, then this method will only suggest properties, methods, etc
449from the correct type. For the previous example that would be properties, methods, etc. from the
450Component attached type.
451*/
452void QQmlLSCompletion::suggestJSExpressionCompletion(const DomItem &scriptIdentifier,
453 BackInsertIterator result) const
454{
455 QDuplicateTracker<QString> usedNames;
456 QQmlJSScope::ConstPtr nearestScope;
457
458 const DomItem owner = ownerOfQualifiedExpression(scriptIdentifier);
459
460 if (!owner) {
461 for (QUtf8StringView view : std::array<QUtf8StringView, 3>{ "null", "false", "true" }) {
462 CompletionItem completion;
463 completion.label = view.data();
464 completion.kind = CompletionItemKind::Value;
465 result = completion;
466 }
467 idsCompletions(scriptIdentifier.component(), result);
468 suggestReachableTypes(scriptIdentifier,
469 LocalSymbolsType::Singleton | LocalSymbolsType::AttachedType,
470 CompletionItemKind::Class, result);
471
472 auto scope = scriptIdentifier.nearestSemanticScope();
473 if (!scope)
474 return;
475 nearestScope = scope;
476
477 enumerationCompletion(nearestScope, &usedNames, result);
478 } else {
479 auto ownerExpressionType = QQmlLSUtils::resolveExpressionType(
480 owner, QQmlLSUtils::ResolveActualTypeForFieldMemberExpression);
481 if (!ownerExpressionType || !ownerExpressionType->semanticScope)
482 return;
483 nearestScope = ownerExpressionType->semanticScope;
484
485 switch (ownerExpressionType->type) {
486 case QQmlLSUtils::EnumeratorValueIdentifier:
487 return;
488 case QQmlLSUtils::EnumeratorIdentifier:
489 suggestEnumerationsAndEnumerationValues(nearestScope, *ownerExpressionType->name,
490 usedNames, result);
491 return;
492 case QQmlLSUtils::QmlComponentIdentifier:
493 // Suggest members of the attached type, for example suggest `progress` in
494 // `property real p: Component.progress`.
495 if (QQmlJSScope::ConstPtr attachedType =
496 ownerExpressionType->semanticScope->attachedType()) {
497 methodCompletion(attachedType, &usedNames, result);
498 propertyCompletion(attachedType, &usedNames, result);
499 suggestEnumerationsAndEnumerationValues(
500 attachedType, *ownerExpressionType->name, usedNames, result);
501 }
502 Q_FALLTHROUGH();
503 case QQmlLSUtils::SingletonIdentifier:
504 if (ownerExpressionType->name)
505 suggestEnumerationsAndEnumerationValues(nearestScope, *ownerExpressionType->name,
506 usedNames, result);
507 break;
508 default:
509 break;
510 }
511 }
512
513 Q_ASSERT(nearestScope);
514
515 methodCompletion(nearestScope, &usedNames, result);
516 propertyCompletion(nearestScope, &usedNames, result);
517
518 if (!owner) {
519 // collect all of the stuff from parents
520 collectFromAllJavaScriptParents(
521 [this, &usedNames, result](const QQmlJSScope::ConstPtr &scope) {
522 jsIdentifierCompletion(scope, &usedNames, result);
523 },
524 nearestScope);
525 collectFromAllJavaScriptParents(
526 [this, &usedNames, result](const QQmlJSScope::ConstPtr &scope) {
527 methodCompletion(scope, &usedNames, result);
528 },
529 nearestScope);
530 collectFromAllJavaScriptParents(
531 [this, &usedNames, result](const QQmlJSScope::ConstPtr &scope) {
532 propertyCompletion(scope, &usedNames, result);
533 },
534 nearestScope);
535
536 auto file = scriptIdentifier.containingFile().as<QmlFile>();
537 if (!file)
538 return;
539 auto resolver = file->typeResolver();
540 if (!resolver)
541 return;
542
543 const auto globals = resolver->jsGlobalObject();
544 methodCompletion(globals, &usedNames, result);
545 propertyCompletion(globals, &usedNames, result);
546 }
547}
548
549static const QQmlJSScope *resolve(const QQmlJSScope *current, const QStringList &names)
550{
551 for (const QString &name : names) {
552 if (auto property = current->property(name); property.isValid()) {
553 if (auto propertyType = property.type().get()) {
554 current = propertyType;
555 continue;
556 }
557 }
558 return {};
559 }
560 return current;
561}
562
563bool QQmlLSCompletion::cursorInFrontOfItem(const DomItem &parentForContext,
564 const QQmlLSCompletionPosition &positionInfo)
565{
566 auto fileLocations = FileLocations::treeOf(parentForContext)->info().fullRegion;
567 return positionInfo.offset() <= fileLocations.begin();
568}
569
570bool QQmlLSCompletion::cursorAfterColon(const DomItem &currentItem,
571 const QQmlLSCompletionPosition &positionInfo)
572{
573 auto location = FileLocations::treeOf(currentItem)->info();
574 auto region = location.regions.constFind(ColonTokenRegion);
575
576 if (region == location.regions.constEnd())
577 return false;
578
579 if (region.value().isValid() && region.value().begin() < positionInfo.offset()) {
580 return true;
581 }
582 return false;
583}
584
585/*!
586\internal
587\brief Mapping from pragma names to allowed pragma values.
588
589This mapping of pragma names to pragma values is not complete. In fact, it only contains the
590pragma names and values that one should see autocompletion for.
591Some pragmas like FunctionSignatureBehavior or Strict or the Reference/Value of ValueTypeBehavior,
592for example, should currently not be proposed as completion items by qmlls.
593
594An empty QList-value in the QMap means that the pragma does not accept pragma values.
595*/
596static const QMap<QString, QList<QString>> valuesForPragmas{
597 { u"ComponentBehavior"_s, { u"Unbound"_s, u"Bound"_s } },
598 { u"NativeMethodBehavior"_s, { u"AcceptThisObject"_s, u"RejectThisObject"_s } },
599 { u"ListPropertyAssignBehavior"_s, { u"Append"_s, u"Replace"_s, u"ReplaceIfNotDefault"_s } },
600 { u"Singleton"_s, {} },
601 { u"ValueTypeBehavior"_s, { u"Addressable"_s, u"Inaddressable"_s } },
602};
603
604void QQmlLSCompletion::insidePragmaCompletion(QQmlJS::Dom::DomItem currentItem,
605 const QQmlLSCompletionPosition &positionInfo,
606 BackInsertIterator result) const
607{
608 if (cursorAfterColon(currentItem, positionInfo)) {
609 const QString name = currentItem.field(Fields::name).value().toString();
610 auto values = valuesForPragmas.constFind(name);
611 if (values == valuesForPragmas.constEnd())
612 return;
613
614 for (const auto &value : *values) {
615 CompletionItem comp;
616 comp.label = value.toUtf8();
617 comp.kind = CompletionItemKind::Value;
618 result = comp;
619 }
620 return;
621 }
622
623 for (const auto &pragma : valuesForPragmas.asKeyValueRange()) {
624 CompletionItem comp;
625 comp.label = pragma.first.toUtf8();
626 if (!pragma.second.isEmpty()) {
627 comp.insertText = QString(pragma.first).append(u": ").toUtf8();
628 }
629 comp.kind = CompletionItemKind::Value;
630 result = comp;
631 }
632}
633
634void QQmlLSCompletion::insideQmlObjectCompletion(const DomItem &parentForContext,
635 const QQmlLSCompletionPosition &positionInfo,
636 BackInsertIterator result) const
637{
638
639 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
640
641 const QQmlJS::SourceLocation leftBrace = regions[LeftBraceRegion];
642 const QQmlJS::SourceLocation rightBrace = regions[RightBraceRegion];
643
644 if (beforeLocation(positionInfo, leftBrace)) {
645 LocalSymbolsTypes options;
646 options.setFlag(LocalSymbolsType::ObjectType);
647 suggestReachableTypes(positionInfo.itemAtPosition, options, CompletionItemKind::Constructor,
648 result);
649 if (parentForContext.directParent().internalKind() == DomType::Binding)
650 suggestSnippetsForRightHandSideOfBinding(positionInfo.itemAtPosition, result);
651 else
652 suggestSnippetsForLeftHandSideOfBinding(positionInfo.itemAtPosition, result);
653
654 if (QQmlLSUtils::isFieldMemberExpression(positionInfo.itemAtPosition)) {
655 /*!
656 \internal
657 In the case that a missing identifier is followed by an assignment to the default
658 property, the parser will create a QmlObject out of both binding and default
659 binding. For example, in \code property int x: root. Item {} \endcode the parser will
660 create one binding containing one QmlObject of type `root.Item`, instead of two
661 bindings (one for `x` and one for the default property). For this special case, if
662 completion is requested inside `root.Item`, then try to also suggest JS expressions.
663
664 Note: suggestJSExpressionCompletion() will suggest nothing if the
665 fieldMemberExpression starts with the name of a qualified module or a filename, so
666 this only adds invalid suggestions in the case that there is something shadowing the
667 qualified module name or filename, like a property name for example.
668
669 Note 2: This does not happen for field member accesses. For example, in
670 \code
671 property int x: root.x
672 Item {}
673 \endcode
674 The parser will create both bindings correctly.
675 */
676 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
677 }
678 return;
679 }
680
681 if (betweenLocations(leftBrace, positionInfo, rightBrace)) {
682 // TODO(QTBUG-138020)
683
684 // property attributes completion
685 constexpr static std::array completions{ ""_L1,
686 "default "_L1,
687 "final "_L1,
688 "virtual "_L1,
689 "override "_L1,
690 "required "_L1,
691 "readonly "_L1,
692 "default final "_L1,
693 "default virtual "_L1,
694 "default override "_L1,
695 "default required "_L1,
696 "final required "_L1,
697 "final readonly "_L1,
698 "virtual required "_L1,
699 "virtual readonly "_L1,
700 "override required "_L1,
701 "override readonly "_L1,
702 "default final required "_L1,
703 "default virtual required "_L1,
704 "default override required "_L1 };
705 for (QLatin1StringView completion : completions) {
706 // By default we should suggest both declarations: with and without an initializer
707 // However readonly properties are required to have an initializer,
708 // and required ones, on the contrary, should not have an initializer
709
710 if (!completion.contains(QLatin1StringView("readonly"))) {
711 result = makeSnippet(
712 QByteArray(completion.data()).append("property type name;"),
713 QByteArray(completion.data()).append("property ${1:type} ${0:name};"));
714 }
715
716 if (!completion.contains(QLatin1StringView("required"))) {
717 result = makeSnippet(
718 QByteArray(completion.data()).append("property type name: value;"),
719 QByteArray(completion.data())
720 .append("property ${1:type} ${2:name}: ${0:value};"));
721 }
722 }
723
724 // signal
725 result = makeSnippet("signal name(arg1:type1, ...)", "signal ${1:name}($0)");
726
727 // signal without parameters
728 result = makeSnippet("signal name;", "signal ${0:name};");
729
730 // make already existing property required
731 result = makeSnippet("required name;", "required ${0:name};");
732
733 // function
734 result = makeSnippet("function name(args...): returnType { statements...}",
735 "function ${1:name}($2): ${3:returnType} {\n\t$0\n}");
736
737 // enum
738 result = makeSnippet("enum name { Values...}", "enum ${1:name} {\n\t${0:values}\n}");
739
740 // inline component
741 result = makeSnippet("component Name: BaseType { ... }",
742 "component ${1:name}: ${2:baseType} {\n\t$0\n}");
743
744 suggestBindingCompletion(positionInfo.itemAtPosition, result);
745
746 // add Qml Types for default binding
747 const DomItem containingFile = parentForContext.containingFile();
748 suggestReachableTypes(containingFile, LocalSymbolsType::ObjectType,
749 CompletionItemKind::Constructor, result);
750 suggestSnippetsForLeftHandSideOfBinding(positionInfo.itemAtPosition, result);
751 return;
752 }
753}
754
755// TODO(QTBUG-138020)
756void QQmlLSCompletion::insidePropertyDefinitionCompletion(
757 const DomItem &currentItem, const QQmlLSCompletionPosition &positionInfo,
758 BackInsertIterator result) const
759{
760 auto info = FileLocations::treeOf(currentItem)->info();
761 const QQmlJS::SourceLocation propertyKeyword = info.regions[PropertyKeywordRegion];
762
763 // do completions for the keywords
764 if (positionInfo.offset() < propertyKeyword.end()) {
765 auto addCompletionKeyword = [&result](QUtf8StringView view) {
766 CompletionItem item;
767 item.label = view.data();
768 item.kind = CompletionItemKind::Keyword;
769 result = item;
770 };
771
772 const auto alreadyTyped = [&info,
773 &positionInfo](const FileLocationRegion &keywordRegion) -> bool {
774 const auto &keywordSLoc = info.regions[keywordRegion];
775 return keywordSLoc.isValid() && keywordSLoc.begin() < positionInfo.offset();
776 };
777
778 const bool alreadyTypedReadonlyOrRequired =
779 alreadyTyped(ReadonlyKeywordRegion) || alreadyTyped(RequiredKeywordRegion);
780 if (!alreadyTypedReadonlyOrRequired) {
781 // Suggestions for `readonly` and `required` are mutually exclusive.
782 // If one is already typed, we suggest neither.
783 // If neither is present, both are valid suggestions.
784
785 addCompletionKeyword(u8"readonly");
786 addCompletionKeyword(u8"required");
787 }
788
789 if (!alreadyTyped(DefaultKeywordRegion)) {
790 addCompletionKeyword(u8"default");
791 }
792
793 const bool alreadyTypedVirtualOrOverrideOrFinal = alreadyTyped(VirtualKeywordRegion)
794 || alreadyTyped(OverrideKeywordRegion) || alreadyTyped(FinalKeywordRegion);
795 if (!alreadyTypedVirtualOrOverrideOrFinal) {
796 // `virtual`, `override`, and `final` cannot be combined.
797 // If one is typed, suggest nothing.
798 // If none are typed, suggest all three.
799
800 addCompletionKeyword(u8"final");
801 addCompletionKeyword(u8"virtual");
802 addCompletionKeyword(u8"override");
803 }
804
805 addCompletionKeyword(u8"property");
806
807 return;
808 }
809
810 const QQmlJS::SourceLocation propertyIdentifier = info.regions[IdentifierRegion];
811 if (propertyKeyword.end() <= positionInfo.offset()
812 && positionInfo.offset() < propertyIdentifier.begin()) {
813 suggestReachableTypes(currentItem,
814 LocalSymbolsType::ObjectType | LocalSymbolsType::ValueType,
815 CompletionItemKind::Class, result);
816 }
817 // do not autocomplete the rest
818 return;
819}
820
821void QQmlLSCompletion::insideBindingCompletion(const DomItem &currentItem,
822 const QQmlLSCompletionPosition &positionInfo,
823 BackInsertIterator result) const
824{
825 const DomItem containingBinding = currentItem.filterUp(
826 [](DomType type, const QQmlJS::Dom::DomItem &) { return type == DomType::Binding; },
827 FilterUpOptions::ReturnOuter);
828
829 // do scriptidentifiercompletion after the ':' of a binding
830 if (cursorAfterColon(containingBinding, positionInfo)) {
831 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
832
833 if (auto type = QQmlLSUtils::resolveExpressionType(currentItem,
834 QQmlLSUtils::ResolveOwnerType)) {
835 const QStringList names = currentItem.field(Fields::name).toString().split(u'.');
836 const QQmlJSScope *current = resolve(type->semanticScope.get(), names);
837 // add type names when binding to an object type or a property with var type
838 if (!current || current->accessSemantics() == QQmlSA::AccessSemantics::Reference) {
839 LocalSymbolsTypes options;
840 options.setFlag(LocalSymbolsType::ObjectType);
841 suggestReachableTypes(positionInfo.itemAtPosition, options,
842 CompletionItemKind::Constructor, result);
843 suggestSnippetsForRightHandSideOfBinding(positionInfo.itemAtPosition, result);
844 }
845 }
846 return;
847 }
848
849 // ignore the binding if asking for completion in front of the binding
850 if (cursorInFrontOfItem(containingBinding, positionInfo)) {
851 insideQmlObjectCompletion(currentItem.containingObject(), positionInfo, result);
852 return;
853 }
854
855 const DomItem containingObject = currentItem.qmlObject();
856
857 suggestBindingCompletion(positionInfo.itemAtPosition, result);
858
859 // add Qml Types for default binding
860 suggestReachableTypes(positionInfo.itemAtPosition, LocalSymbolsType::ObjectType,
861 CompletionItemKind::Constructor, result);
862 suggestSnippetsForLeftHandSideOfBinding(positionInfo.itemAtPosition, result);
863}
864
865void QQmlLSCompletion::insideImportCompletion(const DomItem &currentItem,
866 const QQmlLSCompletionPosition &positionInfo,
867 BackInsertIterator result) const
868{
869 const DomItem containingFile = currentItem.containingFile();
870
871 // when in front of the import statement: propose types for root Qml Object completion
872 if (cursorInFrontOfItem(currentItem, positionInfo)) {
873 suggestReachableTypes(containingFile, LocalSymbolsType::ObjectType,
874 CompletionItemKind::Constructor, result);
875 return;
876 }
877
878 const auto regions = FileLocations::treeOf(currentItem)->info().regions;
879 const QQmlJS::SourceLocation importToken = regions.value(ImportTokenRegion);
880 const QQmlJS::SourceLocation uri = regions.value(ImportUriRegion);
881
882 if (importToken.isValid() && positionInfo.offset() <= importToken.end()) {
883 CompletionItem item;
884 item.label = "import";
885 item.kind = CompletionItemKind::Keyword;
886 result = item;
887 return;
888 }
889
890 if (!uri.isValid() || positionInfo.offset() < uri.begin())
891 return;
892
893 if (positionInfo.offset() > uri.end()) {
894 const QQmlJS::SourceLocation asToken = regions.value(AsTokenRegion);
895 if (!asToken.isValid() || positionInfo.offset() <= asToken.end()) {
896 CompletionItem item;
897 item.label = "as";
898 item.kind = CompletionItemKind::Keyword;
899 result = item;
900 }
901 return;
902 }
903
904 const auto environment = currentItem.environment().ownerAs<DomEnvironment>();
905 if (!environment)
906 return;
907
908 const auto qmlFile = containingFile.ownerAs<QmlFile>();
909 if (!qmlFile)
910 return;
911
912 QStringView typedModulePrefix =
913 QStringView(qmlFile->code()).mid(uri.begin(), positionInfo.offset() - uri.begin());
914 const qsizetype lastDotIndex = typedModulePrefix.lastIndexOf(u'.');
915 if (lastDotIndex == -1) {
916 for (const QString &moduleName : importableModules(environment->loadPaths())) {
917 CompletionItem item;
918 item.label = moduleName.toUtf8();
919 item.kind = CompletionItemKind::Module;
920 result = item;
921 }
922 } else {
923 // only complete after the last typed '.'
924 typedModulePrefix.truncate(lastDotIndex + 1);
925 for (const QString &moduleName : importableModules(environment->loadPaths())) {
926 if (!moduleName.startsWith(typedModulePrefix))
927 continue;
928 CompletionItem item;
929 item.label = moduleName.mid(lastDotIndex + 1).toUtf8();
930 item.kind = CompletionItemKind::Module;
931 result = item;
932 }
933 }
934}
935
936void QQmlLSCompletion::exploreImportPaths(const QStringList &importPaths)
937{
938 m_moduleExplorer.explore(importPaths);
939}
940
941QStringList QQmlLSCompletion::importableModules(const QStringList &importPaths) const
942{
943 m_moduleExplorer.explore(importPaths);
944 return m_moduleExplorer.modulesIn(importPaths);
945}
946
947void QQmlLSCompletion::insideQmlFileCompletion(const DomItem &currentItem,
948 const QQmlLSCompletionPosition &positionInfo,
949 BackInsertIterator result) const
950{
951 const DomItem containingFile = currentItem.containingFile();
952 // completions for code outside the root Qml Object
953 // global completions
954 if (positionInfo.cursorPosition.atLineStart()) {
955 if (positionInfo.cursorPosition.base().isEmpty()) {
956 for (const QStringView &s : std::array<QStringView, 2>({ u"pragma", u"import" })) {
957 CompletionItem comp;
958 comp.label = s.toUtf8();
959 comp.kind = CompletionItemKind::Keyword;
960 result = comp;
961 }
962 }
963 }
964 // Types for root Qml Object completion
965 suggestReachableTypes(containingFile, LocalSymbolsType::ObjectType,
966 CompletionItemKind::Constructor, result);
967}
968
969/*!
970\internal
971Generate the snippets for let, var and const variable declarations.
972*/
973void QQmlLSCompletion::suggestVariableDeclarationStatementCompletion(
974 BackInsertIterator result, AppendOption option) const
975{
976 // let/var/const statement
977 for (auto view : std::array<QUtf8StringView, 3>{ "let", "var", "const" }) {
978 auto snippet = makeSnippet(QByteArray(view.data()).append(" variable = value"),
979 QByteArray(view.data()).append(" ${1:variable} = $0"));
980 if (option == AppendSemicolon) {
981 snippet.insertText->append(";");
982 snippet.label.append(";");
983 }
984 result = snippet;
985 }
986}
987
988/*!
989\internal
990Generate the snippets for case and default statements.
991*/
992void QQmlLSCompletion::suggestCaseAndDefaultStatementCompletion(BackInsertIterator result) const
993{
994 // case snippet
995 result = makeSnippet("case value: statements...", "case ${1:value}:\n\t$0");
996 // case + brackets snippet
997 result = makeSnippet("case value: { statements... }", "case ${1:value}: {\n\t$0\n}");
998
999 // default snippet
1000 result = makeSnippet("default: statements...", "default:\n\t$0");
1001 // default + brackets snippet
1002 result = makeSnippet("default: { statements... }", "default: {\n\t$0\n}");
1003}
1004
1005/*!
1006\internal
1007Break and continue can be inserted only in following situations:
1008\list
1009 \li Break and continue inside a loop.
1010 \li Break inside a (nested) LabelledStatement
1011 \li Break inside a (nested) SwitchStatement
1012\endlist
1013*/
1014void QQmlLSCompletion::suggestContinueAndBreakStatementIfNeeded(const DomItem &itemAtPosition,
1015 BackInsertIterator result) const
1016{
1017 bool alreadyInLabel = false;
1018 bool alreadyInSwitch = false;
1019 for (DomItem current = itemAtPosition; current; current = current.directParent()) {
1020 switch (current.internalKind()) {
1021 case DomType::ScriptExpression:
1022 // reached end of script expression
1023 return;
1024
1025 case DomType::ScriptForStatement:
1026 case DomType::ScriptForEachStatement:
1027 case DomType::ScriptWhileStatement:
1028 case DomType::ScriptDoWhileStatement: {
1029 CompletionItem continueKeyword;
1030 continueKeyword.label = "continue";
1031 continueKeyword.kind = CompletionItemKind::Keyword;
1032 result = continueKeyword;
1033
1034 // do not add break twice
1035 if (!alreadyInSwitch && !alreadyInLabel) {
1036 CompletionItem breakKeyword;
1037 breakKeyword.label = "break";
1038 breakKeyword.kind = CompletionItemKind::Keyword;
1039 result = breakKeyword;
1040 }
1041 // early exit: cannot suggest more completions
1042 return;
1043 }
1044 case DomType::ScriptSwitchStatement: {
1045 // check if break was already inserted
1046 if (alreadyInSwitch || alreadyInLabel)
1047 break;
1048 alreadyInSwitch = true;
1049
1050 CompletionItem breakKeyword;
1051 breakKeyword.label = "break";
1052 breakKeyword.kind = CompletionItemKind::Keyword;
1053 result = breakKeyword;
1054 break;
1055 }
1056 case DomType::ScriptLabelledStatement: {
1057 // check if break was already inserted because of switch or loop
1058 if (alreadyInSwitch || alreadyInLabel)
1059 break;
1060 alreadyInLabel = true;
1061
1062 CompletionItem breakKeyword;
1063 breakKeyword.label = "break";
1064 breakKeyword.kind = CompletionItemKind::Keyword;
1065 result = breakKeyword;
1066 break;
1067 }
1068 default:
1069 break;
1070 }
1071 }
1072}
1073
1074/*!
1075\internal
1076Generates snippets or keywords for all possible JS statements where it makes sense. To use whenever
1077any JS statement can be expected, but when no JS statement is there yet.
1078
1079Only generates JS expression completions when itemAtPosition is a qualified name.
1080
1081Here is a list of statements that do \e{not} get any snippets:
1082\list
1083 \li BlockStatement does not need a code snippet, editors automatically include the closing
1084bracket anyway. \li EmptyStatement completion would only generate a single \c{;} \li
1085ExpressionStatement completion cannot generate any snippet, only identifiers \li WithStatement
1086completion is not recommended: qmllint will warn about usage of with statements \li
1087LabelledStatement completion might need to propose labels (TODO?) \li DebuggerStatement completion
1088does not strike as being very useful \endlist
1089*/
1090void QQmlLSCompletion::suggestJSStatementCompletion(const DomItem &itemAtPosition,
1091 BackInsertIterator result) const
1092{
1093 suggestJSExpressionCompletion(itemAtPosition, result);
1094
1095 if (QQmlLSUtils::isFieldMemberAccess(itemAtPosition)
1096 || QQmlLSUtils::isFieldMemberExpression(itemAtPosition))
1097 return;
1098
1099 // expression statements
1100 suggestVariableDeclarationStatementCompletion(result);
1101 // block statement
1102 result = makeSnippet("{ statements... }", "{\n\t$0\n}");
1103
1104 // if + brackets statement
1105 result = makeSnippet("if (condition) { statements }", "if ($1) {\n\t$0\n}");
1106
1107 // do statement
1108 result = makeSnippet("do { statements } while (condition);", "do {\n\t$1\n} while ($0);");
1109
1110 // while + brackets statement
1111 result = makeSnippet("while (condition) { statements...}", "while ($1) {\n\t$0\n}");
1112
1113 // for + brackets loop statement
1114 result = makeSnippet("for (initializer; condition; increment) { statements... }",
1115 "for ($1;$2;$3) {\n\t$0\n}");
1116
1117 // for ... in + brackets loop statement
1118 result = makeSnippet("for (property in object) { statements... }", "for ($1 in $2) {\n\t$0\n}");
1119
1120 // for ... of + brackets loop statement
1121 result = makeSnippet("for (element of array) { statements... }", "for ($1 of $2) {\n\t$0\n}");
1122
1123 // try + catch statement
1124 result = makeSnippet("try { statements... } catch(error) { statements... }",
1125 "try {\n\t$1\n} catch($2) {\n\t$0\n}");
1126
1127 // try + finally statement
1128 result = makeSnippet("try { statements... } finally { statements... }",
1129 "try {\n\t$1\n} finally {\n\t$0\n}");
1130
1131 // try + catch + finally statement
1132 result = makeSnippet(
1133 "try { statements... } catch(error) { statements... } finally { statements... }",
1134 "try {\n\t$1\n} catch($2) {\n\t$3\n} finally {\n\t$0\n}");
1135
1136 // one can always assume that JS code in QML is inside a function, so always propose `return`
1137 for (const QByteArray &view : { "return"_ba, "throw"_ba }) {
1138 CompletionItem item;
1139 item.label = view;
1140 item.kind = CompletionItemKind::Keyword;
1141 result = item;
1142 }
1143
1144 // rules for case+default statements:
1145 // 1) when inside a CaseBlock, or
1146 // 2) inside a CaseClause, as an (non-nested) element of the CaseClause statementlist.
1147 // 3) inside a DefaultClause, as an (non-nested) element of the DefaultClause statementlist,
1148 //
1149 // switch (x) {
1150 // // (1)
1151 // case 1:
1152 // myProperty = 5;
1153 // // (2) -> could be another statement of current case, but also a new case or default!
1154 // default:
1155 // myProperty = 5;
1156 // // (3) -> could be another statement of current default, but also a new case or default!
1157 // }
1158 const DomType currentKind = itemAtPosition.internalKind();
1159 const DomType parentKind = itemAtPosition.directParent().internalKind();
1160 if (currentKind == DomType::ScriptCaseBlock || currentKind == DomType::ScriptCaseClause
1161 || currentKind == DomType::ScriptDefaultClause
1162 || (currentKind == DomType::List
1163 && (parentKind == DomType::ScriptCaseClause
1164 || parentKind == DomType::ScriptDefaultClause))) {
1165 suggestCaseAndDefaultStatementCompletion(result);
1166 }
1167 suggestContinueAndBreakStatementIfNeeded(itemAtPosition, result);
1168}
1169
1170void QQmlLSCompletion::insideForStatementCompletion(const DomItem &parentForContext,
1171 const QQmlLSCompletionPosition &positionInfo,
1172 BackInsertIterator result) const
1173{
1174 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1175
1176 const QQmlJS::SourceLocation leftParenthesis = regions[LeftParenthesisRegion];
1177 const QQmlJS::SourceLocation firstSemicolon = regions[FirstSemicolonTokenRegion];
1178 const QQmlJS::SourceLocation secondSemicolon = regions[SecondSemicolonRegion];
1179 const QQmlJS::SourceLocation rightParenthesis = regions[RightParenthesisRegion];
1180
1181 if (betweenLocations(leftParenthesis, positionInfo, firstSemicolon)) {
1182 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1183 suggestVariableDeclarationStatementCompletion(result,
1184 AppendOption::AppendNothing);
1185 return;
1186 }
1187 if (betweenLocations(firstSemicolon, positionInfo, secondSemicolon)
1188 || betweenLocations(secondSemicolon, positionInfo, rightParenthesis)) {
1189 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1190 return;
1191 }
1192
1193 if (afterLocation(rightParenthesis, positionInfo)) {
1194 suggestJSStatementCompletion(positionInfo.itemAtPosition, result);
1195 return;
1196 }
1197}
1198
1199void QQmlLSCompletion::insideScriptLiteralCompletion(const DomItem &currentItem,
1200 const QQmlLSCompletionPosition &positionInfo,
1201 BackInsertIterator result) const
1202{
1203 Q_UNUSED(currentItem);
1204 if (positionInfo.cursorPosition.base().isEmpty()) {
1205 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1206 return;
1207 }
1208}
1209
1210void QQmlLSCompletion::insideCallExpression(const DomItem &currentItem,
1211 const QQmlLSCompletionPosition &positionInfo,
1212 BackInsertIterator result) const
1213{
1214 const auto regions = FileLocations::treeOf(currentItem)->info().regions;
1215 const QQmlJS::SourceLocation leftParenthesis = regions[LeftParenthesisRegion];
1216 const QQmlJS::SourceLocation rightParenthesis = regions[RightParenthesisRegion];
1217 if (beforeLocation(positionInfo, leftParenthesis)) {
1218 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1219 return;
1220 }
1221 if (betweenLocations(leftParenthesis, positionInfo, rightParenthesis)) {
1222 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1223 return;
1224 }
1225}
1226
1227void QQmlLSCompletion::insideIfStatement(const DomItem &currentItem,
1228 const QQmlLSCompletionPosition &positionInfo,
1229 BackInsertIterator result) const
1230{
1231 const auto regions = FileLocations::treeOf(currentItem)->info().regions;
1232 const QQmlJS::SourceLocation leftParenthesis = regions[LeftParenthesisRegion];
1233 const QQmlJS::SourceLocation rightParenthesis = regions[RightParenthesisRegion];
1234 const QQmlJS::SourceLocation elseKeyword = regions[ElseKeywordRegion];
1235
1236 if (betweenLocations(leftParenthesis, positionInfo, rightParenthesis)) {
1237 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1238 return;
1239 }
1240 if (betweenLocations(rightParenthesis, positionInfo, elseKeyword)) {
1241 suggestJSStatementCompletion(positionInfo.itemAtPosition, result);
1242 return;
1243 }
1244 if (afterLocation(elseKeyword, positionInfo)) {
1245 suggestJSStatementCompletion(positionInfo.itemAtPosition, result);
1246 return;
1247 }
1248}
1249
1250void QQmlLSCompletion::insideReturnStatement(const DomItem &currentItem,
1251 const QQmlLSCompletionPosition &positionInfo,
1252 BackInsertIterator result) const
1253{
1254 const auto regions = FileLocations::treeOf(currentItem)->info().regions;
1255 const QQmlJS::SourceLocation returnKeyword = regions[ReturnKeywordRegion];
1256
1257 if (afterLocation(returnKeyword, positionInfo)) {
1258 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1259 return;
1260 }
1261}
1262
1263void QQmlLSCompletion::insideWhileStatement(const DomItem &currentItem,
1264 const QQmlLSCompletionPosition &positionInfo,
1265 BackInsertIterator result) const
1266{
1267 const auto regions = FileLocations::treeOf(currentItem)->info().regions;
1268 const QQmlJS::SourceLocation leftParenthesis = regions[LeftParenthesisRegion];
1269 const QQmlJS::SourceLocation rightParenthesis = regions[RightParenthesisRegion];
1270
1271 if (betweenLocations(leftParenthesis, positionInfo, rightParenthesis)) {
1272 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1273 return;
1274 }
1275 if (afterLocation(rightParenthesis, positionInfo)) {
1276 suggestJSStatementCompletion(positionInfo.itemAtPosition, result);
1277 return;
1278 }
1279}
1280
1281void QQmlLSCompletion::insideDoWhileStatement(const DomItem &parentForContext,
1282 const QQmlLSCompletionPosition &positionInfo,
1283 BackInsertIterator result) const
1284{
1285 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1286 const QQmlJS::SourceLocation doKeyword = regions[DoKeywordRegion];
1287 const QQmlJS::SourceLocation whileKeyword = regions[WhileKeywordRegion];
1288 const QQmlJS::SourceLocation leftParenthesis = regions[LeftParenthesisRegion];
1289 const QQmlJS::SourceLocation rightParenthesis = regions[RightParenthesisRegion];
1290
1291 if (betweenLocations(doKeyword, positionInfo, whileKeyword)) {
1292 suggestJSStatementCompletion(positionInfo.itemAtPosition, result);
1293 return;
1294 }
1295 if (betweenLocations(leftParenthesis, positionInfo, rightParenthesis)) {
1296 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1297 return;
1298 }
1299}
1300
1301void QQmlLSCompletion::insideForEachStatement(const DomItem &parentForContext,
1302 const QQmlLSCompletionPosition &positionInfo,
1303 BackInsertIterator result) const
1304{
1305 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1306
1307 const QQmlJS::SourceLocation inOf = regions[InOfTokenRegion];
1308 const QQmlJS::SourceLocation leftParenthesis = regions[LeftParenthesisRegion];
1309 const QQmlJS::SourceLocation rightParenthesis = regions[RightParenthesisRegion];
1310
1311 if (betweenLocations(leftParenthesis, positionInfo, inOf)) {
1312 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1313 suggestVariableDeclarationStatementCompletion(result);
1314 return;
1315 }
1316 if (betweenLocations(inOf, positionInfo, rightParenthesis)) {
1317 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1318 return;
1319 }
1320
1321 if (afterLocation(rightParenthesis, positionInfo)) {
1322 suggestJSStatementCompletion(positionInfo.itemAtPosition, result);
1323 return;
1324 }
1325}
1326
1327void QQmlLSCompletion::insideSwitchStatement(const DomItem &parentForContext,
1328 const QQmlLSCompletionPosition positionInfo,
1329 BackInsertIterator result) const
1330{
1331 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1332
1333 const QQmlJS::SourceLocation leftParenthesis = regions[LeftParenthesisRegion];
1334 const QQmlJS::SourceLocation rightParenthesis = regions[RightParenthesisRegion];
1335
1336 if (betweenLocations(leftParenthesis, positionInfo, rightParenthesis)) {
1337 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1338 return;
1339 }
1340}
1341
1342void QQmlLSCompletion::insideCaseClause(const DomItem &parentForContext,
1343 const QQmlLSCompletionPosition &positionInfo,
1344 BackInsertIterator result) const
1345{
1346 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1347
1348 const QQmlJS::SourceLocation caseKeyword = regions[CaseKeywordRegion];
1349 const QQmlJS::SourceLocation colonToken = regions[ColonTokenRegion];
1350
1351 if (betweenLocations(caseKeyword, positionInfo, colonToken)) {
1352 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1353 return;
1354 }
1355 if (afterLocation(colonToken, positionInfo)) {
1356 suggestJSStatementCompletion(positionInfo.itemAtPosition, result);
1357 return;
1358 }
1359
1360}
1361
1362/*!
1363\internal
1364Checks if a case or default clause does happen before ctx in the code.
1365*/
1366bool QQmlLSCompletion::isCaseOrDefaultBeforeCtx(const DomItem &currentClause,
1367 const QQmlLSCompletionPosition &positionInfo,
1368 FileLocationRegion keywordRegion) const
1369{
1370 Q_ASSERT(keywordRegion == QQmlJS::Dom::CaseKeywordRegion
1371 || keywordRegion == QQmlJS::Dom::DefaultKeywordRegion);
1372
1373 if (!currentClause)
1374 return false;
1375
1376 const auto token = FileLocations::treeOf(currentClause)->info().regions[keywordRegion];
1377 if (afterLocation(token, positionInfo))
1378 return true;
1379
1380 return false;
1381}
1382
1383/*!
1384\internal
1385
1386Search for a `case ...:` or a `default: ` clause happening before ctx, and return the
1387corresponding DomItem of type DomType::CaseClauses or DomType::DefaultClause.
1388
1389Return an empty DomItem if neither case nor default was found.
1390*/
1391DomItem
1392QQmlLSCompletion::previousCaseOfCaseBlock(const DomItem &parentForContext,
1393 const QQmlLSCompletionPosition &positionInfo) const
1394{
1395 const DomItem caseClauses = parentForContext.field(Fields::caseClauses);
1396 for (int i = 0; i < caseClauses.indexes(); ++i) {
1397 const DomItem currentClause = caseClauses.index(i);
1398 if (isCaseOrDefaultBeforeCtx(currentClause, positionInfo, QQmlJS::Dom::CaseKeywordRegion)) {
1399 return currentClause;
1400 }
1401 }
1402
1403 const DomItem defaultClause = parentForContext.field(Fields::defaultClause);
1404 if (isCaseOrDefaultBeforeCtx(defaultClause, positionInfo, QQmlJS::Dom::DefaultKeywordRegion))
1405 return parentForContext.field(Fields::defaultClause);
1406
1407 const DomItem moreCaseClauses = parentForContext.field(Fields::moreCaseClauses);
1408 for (int i = 0; i < moreCaseClauses.indexes(); ++i) {
1409 const DomItem currentClause = moreCaseClauses.index(i);
1410 if (isCaseOrDefaultBeforeCtx(currentClause, positionInfo, QQmlJS::Dom::CaseKeywordRegion)) {
1411 return currentClause;
1412 }
1413 }
1414
1415 return {};
1416}
1417
1418void QQmlLSCompletion::insideCaseBlock(const DomItem &parentForContext,
1419 const QQmlLSCompletionPosition &positionInfo,
1420 BackInsertIterator result) const
1421{
1422 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1423
1424 const QQmlJS::SourceLocation leftBrace = regions[LeftBraceRegion];
1425 const QQmlJS::SourceLocation rightBrace = regions[RightBraceRegion];
1426
1427 if (!betweenLocations(leftBrace, positionInfo, rightBrace))
1428 return;
1429
1430 // TODO: looks fishy
1431 // if there is a previous case or default clause, you can still add statements to it
1432 if (const auto previousCase = previousCaseOfCaseBlock(parentForContext, positionInfo)) {
1433 suggestJSStatementCompletion(previousCase, result);
1434 return;
1435 }
1436
1437 // otherwise, only complete case and default
1438 suggestCaseAndDefaultStatementCompletion(result);
1439}
1440
1441void QQmlLSCompletion::insideDefaultClause(const DomItem &parentForContext,
1442 const QQmlLSCompletionPosition &positionInfo,
1443 BackInsertIterator result) const
1444{
1445 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1446
1447 const QQmlJS::SourceLocation colonToken = regions[ColonTokenRegion];
1448
1449 if (afterLocation(colonToken, positionInfo)) {
1450 suggestJSStatementCompletion(positionInfo.itemAtPosition, result);
1451 return ;
1452 }
1453}
1454
1455void QQmlLSCompletion::insideBinaryExpressionCompletion(
1456 const DomItem &parentForContext, const QQmlLSCompletionPosition &positionInfo,
1457 BackInsertIterator result) const
1458{
1459 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1460
1461 const QQmlJS::SourceLocation operatorLocation = regions[OperatorTokenRegion];
1462
1463 if (beforeLocation(positionInfo, operatorLocation)) {
1464 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1465 return;
1466 }
1467 if (afterLocation(operatorLocation, positionInfo)) {
1468 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1469 return;
1470 }
1471}
1472
1473/*!
1474\internal
1475Doing completion in variable declarations requires taking a look at all different cases:
1476
1477\list
1478 \li Normal variable names, like \c{let helloWorld = 123;}
1479 In this case, only autocomplete scriptexpressionidentifiers after the '=' token.
1480 Do not propose existing names for the variable name, because the variable name needs to be
1481 an identifier that is not used anywhere (to avoid shadowing and confusing code),
1482
1483 \li Deconstructed arrays, like \c{let [ helloWorld, ] = [ 123, ];}
1484 In this case, only autocomplete scriptexpressionidentifiers after the '=' token.
1485 Do not propose already existing identifiers inside the left hand side array.
1486
1487 \li Deconstructed arrays with initializers, like \c{let [ helloWorld = someVar, ] = [ 123, ];}
1488 Note: this assigns the value of someVar to helloWorld if the right hand side's first element
1489 is undefined or does not exist.
1490
1491 In this case, only autocomplete scriptexpressionidentifiers after the '=' tokens.
1492 Only propose already existing identifiers inside the left hand side array when behind a '='
1493 token.
1494
1495 \li Deconstructed Objects, like \c{let { helloWorld, } = { helloWorld: 123, };}
1496 In this case, only autocomplete scriptexpressionidentifiers after the '=' token.
1497 Do not propose already existing identifiers inside the left hand side object.
1498
1499 \li Deconstructed Objects with initializers, like \c{let { helloWorld = someVar, } = {};}
1500 Note: this assigns the value of someVar to helloWorld if the right hand side's object does
1501 not have a property called 'helloWorld'.
1502
1503 In this case, only autocomplete scriptexpressionidentifiers after the '=' token.
1504 Only propose already existing identifiers inside the left hand side object when behind a '='
1505 token.
1506
1507 \li Finally, you are allowed to nest and combine all above possibilities together for all your
1508 deconstruction needs, so the exact same completion needs to be done for
1509 DomType::ScriptPatternElement too.
1510
1511\endlist
1512*/
1513void QQmlLSCompletion::insideScriptPattern(const DomItem &parentForContext,
1514 const QQmlLSCompletionPosition &positionInfo,
1515 BackInsertIterator result) const
1516{
1517 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1518
1519 const QQmlJS::SourceLocation equal = regions[EqualTokenRegion];
1520
1521 if (!afterLocation(equal, positionInfo))
1522 return;
1523
1524 // otherwise, only complete case and default
1525 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1526}
1527
1528/*!
1529\internal
1530See comment on insideScriptPattern().
1531*/
1532void QQmlLSCompletion::insideVariableDeclarationEntry(const DomItem &parentForContext,
1533 const QQmlLSCompletionPosition &positionInfo,
1534 BackInsertIterator result) const
1535{
1536 insideScriptPattern(parentForContext, positionInfo, result);
1537}
1538
1539void QQmlLSCompletion::insideThrowStatement(const DomItem &parentForContext,
1540 const QQmlLSCompletionPosition &positionInfo,
1541 BackInsertIterator result) const
1542{
1543 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1544
1545 const QQmlJS::SourceLocation throwKeyword = regions[ThrowKeywordRegion];
1546
1547 if (afterLocation(throwKeyword, positionInfo)) {
1548 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1549 return;
1550 }
1551}
1552
1553void QQmlLSCompletion::insideLabelledStatement(const DomItem &parentForContext,
1554 const QQmlLSCompletionPosition &positionInfo,
1555 BackInsertIterator result) const
1556{
1557 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1558
1559 const QQmlJS::SourceLocation colon = regions[ColonTokenRegion];
1560
1561 if (afterLocation(colon, positionInfo)) {
1562 suggestJSStatementCompletion(positionInfo.itemAtPosition, result);
1563 return;
1564 }
1565 // note: the case "beforeLocation(ctx, colon)" probably never happens:
1566 // this is because without the colon, the parser will probably not parse this as a
1567 // labelledstatement but as a normal expression statement.
1568 // So this case only happens when the colon already exists, and the user goes back to the
1569 // label name and requests completion for that label.
1570}
1571
1572/*!
1573\internal
1574Collect the current set of labels that some DomItem can jump to.
1575*/
1576static void collectLabels(const DomItem &context, QQmlLSCompletion::BackInsertIterator result)
1577{
1578 for (DomItem current = context; current; current = current.directParent()) {
1579 if (current.internalKind() == DomType::ScriptLabelledStatement) {
1580 const QString label = current.field(Fields::label).value().toString();
1581 if (label.isEmpty())
1582 continue;
1583 CompletionItem item;
1584 item.label = label.toUtf8();
1585 item.kind = CompletionItemKind::Value; // variable?
1586 // TODO: more stuff here?
1587 result = item;
1588 } else if (current.internalKind() == DomType::ScriptExpression) {
1589 // quick exit when leaving the JS part
1590 return;
1591 }
1592 }
1593 return;
1594}
1595
1596void QQmlLSCompletion::insideContinueStatement(const DomItem &parentForContext,
1597 const QQmlLSCompletionPosition &positionInfo,
1598 BackInsertIterator result) const
1599{
1600 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1601
1602 const QQmlJS::SourceLocation continueKeyword = regions[ContinueKeywordRegion];
1603
1604 if (afterLocation(continueKeyword, positionInfo)) {
1605 collectLabels(parentForContext, result);
1606 return;
1607 }
1608}
1609
1610void QQmlLSCompletion::insideBreakStatement(const DomItem &parentForContext,
1611 const QQmlLSCompletionPosition &positionInfo,
1612 BackInsertIterator result) const
1613{
1614 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1615
1616 const QQmlJS::SourceLocation breakKeyword = regions[BreakKeywordRegion];
1617
1618 if (afterLocation(breakKeyword, positionInfo)) {
1619 collectLabels(parentForContext, result);
1620 return;
1621 }
1622}
1623
1624void QQmlLSCompletion::insideConditionalExpression(const DomItem &parentForContext,
1625 const QQmlLSCompletionPosition &positionInfo,
1626 BackInsertIterator result) const
1627{
1628 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1629
1630 const QQmlJS::SourceLocation questionMark = regions[QuestionMarkTokenRegion];
1631 const QQmlJS::SourceLocation colon = regions[ColonTokenRegion];
1632
1633 if (beforeLocation(positionInfo, questionMark)) {
1634 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1635 return;
1636 }
1637 if (betweenLocations(questionMark, positionInfo, colon)) {
1638 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1639 return;
1640 }
1641 if (afterLocation(colon, positionInfo)) {
1642 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1643 return;
1644 }
1645}
1646
1647void QQmlLSCompletion::insideUnaryExpression(const DomItem &parentForContext,
1648 const QQmlLSCompletionPosition &positionInfo,
1649 BackInsertIterator result) const
1650{
1651 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1652
1653 const QQmlJS::SourceLocation operatorToken = regions[OperatorTokenRegion];
1654
1655 if (afterLocation(operatorToken, positionInfo)) {
1656 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1657 return;
1658 }
1659}
1660
1661void QQmlLSCompletion::insidePostExpression(const DomItem &parentForContext,
1662 const QQmlLSCompletionPosition &positionInfo,
1663 BackInsertIterator result) const
1664{
1665 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1666
1667 const QQmlJS::SourceLocation operatorToken = regions[OperatorTokenRegion];
1668
1669 if (beforeLocation(positionInfo, operatorToken)) {
1670 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1671 return;
1672 }
1673}
1674
1675void QQmlLSCompletion::insideParenthesizedExpression(const DomItem &parentForContext,
1676 const QQmlLSCompletionPosition &positionInfo,
1677 BackInsertIterator result) const
1678{
1679 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1680
1681 const QQmlJS::SourceLocation leftParenthesis = regions[LeftParenthesisRegion];
1682 const QQmlJS::SourceLocation rightParenthesis = regions[RightParenthesisRegion];
1683
1684 if (betweenLocations(leftParenthesis, positionInfo, rightParenthesis)) {
1685 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1686 return;
1687 }
1688}
1689
1690void QQmlLSCompletion::insideTemplateLiteral(const DomItem &parentForContext,
1691 const QQmlLSCompletionPosition &positionInfo,
1692 BackInsertIterator result) const
1693{
1694 Q_UNUSED(parentForContext);
1695 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1696}
1697
1698void QQmlLSCompletion::insideNewExpression(const DomItem &parentForContext,
1699 const QQmlLSCompletionPosition &positionInfo,
1700 BackInsertIterator result) const
1701{
1702 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1703 const QQmlJS::SourceLocation newKeyword = regions[NewKeywordRegion];
1704
1705 if (afterLocation(newKeyword, positionInfo)) {
1706 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1707 return;
1708 }
1709}
1710
1711void QQmlLSCompletion::insideNewMemberExpression(const DomItem &parentForContext,
1712 const QQmlLSCompletionPosition &positionInfo,
1713 BackInsertIterator result) const
1714{
1715 const auto regions = FileLocations::treeOf(parentForContext)->info().regions;
1716 const QQmlJS::SourceLocation newKeyword = regions[NewKeywordRegion];
1717 const QQmlJS::SourceLocation leftParenthesis = regions[LeftParenthesisRegion];
1718 const QQmlJS::SourceLocation rightParenthesis = regions[RightParenthesisRegion];
1719
1720 if (betweenLocations(newKeyword, positionInfo, leftParenthesis)
1721 || betweenLocations(leftParenthesis, positionInfo, rightParenthesis)) {
1722 suggestJSExpressionCompletion(positionInfo.itemAtPosition, result);
1723 return;
1724 }
1725}
1726
1727void QQmlLSCompletion::signalHandlerCompletion(const QQmlJSScope::ConstPtr &scope,
1728 QDuplicateTracker<QString> *usedNames,
1729 BackInsertIterator result) const
1730{
1731 const auto keyValues = scope->methods().asKeyValueRange();
1732 for (const auto &[name, method] : keyValues) {
1733 if (method.access() != QQmlJSMetaMethod::Public
1734 || method.methodType() != QQmlJSMetaMethodType::Signal) {
1735 continue;
1736 }
1737 if (usedNames && usedNames->hasSeen(name)) {
1738 continue;
1739 }
1740
1741 CompletionItem completion;
1742 completion.label = QQmlSignalNames::signalNameToHandlerName(name).toUtf8();
1743 completion.kind = CompletionItemKind::Method;
1744 result = completion;
1745 }
1746}
1747
1748/*!
1749\internal
1750Decide which completions can be used at currentItem and compute them.
1751*/
1753QQmlLSCompletion::completions(const DomItem &currentItem,
1754 const CompletionContextStrings &contextStrings) const
1755{
1756 QList<CompletionItem> result;
1757 collectCompletions(currentItem, contextStrings, std::back_inserter(result));
1758 return result;
1759}
1760
1761void QQmlLSCompletion::collectCompletions(const DomItem &currentItem,
1762 const CompletionContextStrings &contextStrings,
1763 BackInsertIterator result) const
1764{
1765 /*!
1766 Completion is not provided on a script identifier expression because script identifier
1767 expressions lack context information. Instead, find the first parent that has enough
1768 context information and provide completion for this one.
1769 For example, a script identifier expression \c{le} in
1770 \badcode
1771 for (;le;) { ... }
1772 \endcode
1773 will get completion for a property called \c{leProperty}, while the same script identifier
1774 expression in
1775 \badcode
1776 for (le;;) { ... }
1777 \endcode
1778 will, in addition to \c{leProperty}, also get completion for the \c{let} statement snippet.
1779 In this example, the parent used for the completion is the for-statement, of type
1780 DomType::ScriptForStatement.
1781
1782 In addition of the parent for the context, use positionInfo to have exact information on where
1783 the cursor is (to compare with the SourceLocations of tokens) and which item is at this position
1784 (required to provide completion at the correct position, for example for attached properties).
1785 */
1786 const QQmlLSCompletionPosition positionInfo{ currentItem, contextStrings };
1787 for (DomItem currentParent = currentItem; currentParent;
1788 currentParent = currentParent.directParent()) {
1789 const DomType currentType = currentParent.internalKind();
1790
1791 switch (currentType) {
1792 case DomType::Id:
1793 // suppress completions for ids
1794 return;
1795 case DomType::Pragma:
1796 insidePragmaCompletion(currentParent, positionInfo, result);
1797 return;
1798 case DomType::ScriptType: {
1799 if (currentParent.directParent().internalKind() == DomType::QmlObject) {
1800 insideQmlObjectCompletion(currentParent.directParent(), positionInfo, result);
1801 return;
1802 }
1803
1804 LocalSymbolsTypes options;
1805 options.setFlag(LocalSymbolsType::ObjectType);
1806 options.setFlag(LocalSymbolsType::ValueType);
1807 suggestReachableTypes(currentItem, options, CompletionItemKind::Class, result);
1808 return;
1809 }
1810 case DomType::ScriptFormalParameter:
1811 // no autocompletion inside of function parameter definition
1812 return;
1813 case DomType::Binding:
1814 insideBindingCompletion(currentParent, positionInfo, result);
1815 return;
1816 case DomType::Import:
1817 insideImportCompletion(currentParent, positionInfo, result);
1818 return;
1819 case DomType::ScriptForStatement:
1820 insideForStatementCompletion(currentParent, positionInfo, result);
1821 return;
1822 case DomType::ScriptBlockStatement:
1823 suggestJSStatementCompletion(positionInfo.itemAtPosition, result);
1824 return;
1825 case DomType::QmlFile:
1826 insideQmlFileCompletion(currentParent, positionInfo, result);
1827 return;
1828 case DomType::QmlObject:
1829 insideQmlObjectCompletion(currentParent, positionInfo, result);
1830 return;
1831 case DomType::MethodInfo:
1832 // suppress completions
1833 return;
1834 case DomType::PropertyDefinition:
1835 insidePropertyDefinitionCompletion(currentParent, positionInfo, result);
1836 return;
1837 case DomType::ScriptBinaryExpression:
1838 // ignore field member expressions: these need additional context from its parents
1839 if (QQmlLSUtils::isFieldMemberExpression(currentParent))
1840 continue;
1841 insideBinaryExpressionCompletion(currentParent, positionInfo, result);
1842 return;
1843 case DomType::ScriptLiteral:
1844 insideScriptLiteralCompletion(currentParent, positionInfo, result);
1845 return;
1846 case DomType::ScriptRegExpLiteral:
1847 // no completion inside of regexp literals
1848 return;
1849 case DomType::ScriptCallExpression:
1850 insideCallExpression(currentParent, positionInfo, result);
1851 return;
1852 case DomType::ScriptIfStatement:
1853 insideIfStatement(currentParent, positionInfo, result);
1854 return;
1855 case DomType::ScriptReturnStatement:
1856 insideReturnStatement(currentParent, positionInfo, result);
1857 return;
1858 case DomType::ScriptWhileStatement:
1859 insideWhileStatement(currentParent, positionInfo, result);
1860 return;
1861 case DomType::ScriptDoWhileStatement:
1862 insideDoWhileStatement(currentParent, positionInfo, result);
1863 return;
1864 case DomType::ScriptForEachStatement:
1865 insideForEachStatement(currentParent, positionInfo, result);
1866 return;
1867 case DomType::ScriptTryCatchStatement:
1868 /*!
1869 \internal
1870 The Ecmascript standard specifies that there can only be a block statement between \c
1871 try and \c catch(...), \c try and \c finally and \c catch(...) and \c finally, so all of
1872 these completions are already handled by the DomType::ScriptBlockStatement completion.
1873 The only place in the try statement where there is no BlockStatement and therefore needs
1874 its own completion is inside the catch parameter, but that is
1875 \quotation
1876 An optional identifier or pattern to hold the caught exception for the associated catch
1877 block.
1878 \endquotation
1879 citing
1880 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch?retiredLocale=de#exceptionvar.
1881 This means that no completion is needed inside a catch-expression, as it should contain
1882 an identifier that is not yet used anywhere.
1883 Therefore, no completion is required at all when inside a try-statement but outside a
1884 block-statement.
1885 */
1886 return;
1887 case DomType::ScriptSwitchStatement:
1888 insideSwitchStatement(currentParent, positionInfo, result);
1889 return;
1890 case DomType::ScriptCaseClause:
1891 insideCaseClause(currentParent, positionInfo, result);
1892 return;
1893 case DomType::ScriptDefaultClause:
1894 if (ctxBeforeStatement(positionInfo, currentParent, QQmlJS::Dom::DefaultKeywordRegion))
1895 continue;
1896 insideDefaultClause(currentParent, positionInfo, result);
1897 return;
1898 case DomType::ScriptCaseBlock:
1899 insideCaseBlock(currentParent, positionInfo, result);
1900 return;
1901 case DomType::ScriptVariableDeclaration:
1902 // not needed: thats a list of ScriptVariableDeclarationEntry, and those entries cannot
1903 // be suggested because they all start with `{`, `[` or an identifier that should not be
1904 // in use yet.
1905 return;
1906 case DomType::ScriptVariableDeclarationEntry:
1907 insideVariableDeclarationEntry(currentParent, positionInfo, result);
1908 return;
1909 case DomType::ScriptProperty:
1910 // fallthrough: a ScriptProperty is a ScriptPattern but inside a JS Object. It gets the
1911 // same completions as a ScriptPattern.
1912 case DomType::ScriptPattern:
1913 insideScriptPattern(currentParent, positionInfo, result);
1914 return;
1915 case DomType::ScriptThrowStatement:
1916 insideThrowStatement(currentParent, positionInfo, result);
1917 return;
1918 case DomType::ScriptLabelledStatement:
1919 insideLabelledStatement(currentParent, positionInfo, result);
1920 return;
1921 case DomType::ScriptContinueStatement:
1922 insideContinueStatement(currentParent, positionInfo, result);
1923 return;
1924 case DomType::ScriptBreakStatement:
1925 insideBreakStatement(currentParent, positionInfo, result);
1926 return;
1927 case DomType::ScriptConditionalExpression:
1928 insideConditionalExpression(currentParent, positionInfo, result);
1929 return;
1930 case DomType::ScriptUnaryExpression:
1931 insideUnaryExpression(currentParent, positionInfo, result);
1932 return;
1933 case DomType::ScriptPostExpression:
1934 insidePostExpression(currentParent, positionInfo, result);
1935 return;
1936 case DomType::ScriptParenthesizedExpression:
1937 insideParenthesizedExpression(currentParent, positionInfo, result);
1938 return;
1939 case DomType::ScriptTemplateLiteral:
1940 insideTemplateLiteral(currentParent, positionInfo, result);
1941 return;
1942 case DomType::ScriptTemplateStringPart:
1943 // no completion inside of the non-expression parts of template strings
1944 return;
1945 case DomType::ScriptNewExpression:
1946 insideNewExpression(currentParent, positionInfo, result);
1947 return;
1948 case DomType::ScriptNewMemberExpression:
1949 insideNewMemberExpression(currentParent, positionInfo, result);
1950 return;
1951 case DomType::ScriptThisExpression:
1952 // suppress completions on `this`
1953 return;
1954 case DomType::ScriptSuperLiteral:
1955 // suppress completions on `super`
1956 return;
1957 case DomType::Comment:
1958 // no completion inside of comments
1959 return;
1960
1961 // TODO: Implement those statements.
1962 // In the meanwhile, suppress completions to avoid weird behaviors.
1963 case DomType::ScriptArray:
1964 case DomType::ScriptObject:
1965 case DomType::ScriptElision:
1966 case DomType::ScriptArrayEntry:
1967 return;
1968
1969 default:
1970 continue;
1971 }
1972 Q_UNREACHABLE();
1973 }
1974
1975 // no completion could be found
1976 qCDebug(QQmlLSUtilsLog) << "No completion was found for current request.";
1977 return;
1978}
1979
1980QQmlLSCompletion::QQmlLSCompletion(const QFactoryLoader &pluginLoader)
1981{
1982 const auto keys = pluginLoader.metaDataKeys();
1983 for (qsizetype i = 0; i < keys.size(); ++i) {
1984 auto instance = std::unique_ptr<QQmlLSPlugin>(
1985 qobject_cast<QQmlLSPlugin *>(pluginLoader.instance(i)));
1986 if (!instance)
1987 continue;
1988 if (auto completionInstance = instance->createCompletionPlugin())
1989 m_plugins.push_back(std::move(completionInstance));
1990 }
1991}
1992
1993/*!
1994\internal
1995Helper method to call a method on all loaded plugins.
1996*/
1997void QQmlLSCompletion::collectFromPlugins(qxp::function_ref<CompletionFromPluginFunction> f,
1998 BackInsertIterator result) const
1999{
2000 for (const auto &plugin : m_plugins) {
2001 Q_ASSERT(plugin);
2002 f(plugin.get(), result);
2003 }
2004}
2005
2006void QQmlLSCompletion::suggestSnippetsForLeftHandSideOfBinding(const DomItem &itemAtPosition,
2007 BackInsertIterator result) const
2008{
2009 collectFromPlugins(
2010 [&itemAtPosition](QQmlLSCompletionPlugin *p, BackInsertIterator result) {
2011 p->suggestSnippetsForLeftHandSideOfBinding(itemAtPosition, result);
2012 },
2013 result);
2014}
2015
2016void QQmlLSCompletion::suggestSnippetsForRightHandSideOfBinding(const DomItem &itemAtPosition,
2017 BackInsertIterator result) const
2018{
2019 collectFromPlugins(
2020 [&itemAtPosition](QQmlLSCompletionPlugin *p, BackInsertIterator result) {
2021 p->suggestSnippetsForRightHandSideOfBinding(itemAtPosition, result);
2022 },
2023 result);
2024}
2025
2026QT_END_NAMESPACE
QQmlLSCompletion provides completions for all kinds of QML and JS constructs.
void exploreImportPaths(const QStringList &importPaths)
QList< CompletionItem > completions(const DomItem &currentItem, const CompletionContextStrings &ctx) const
QQmlLSCompletion(const QFactoryLoader &pluginLoader)
Combined button and popup list for selecting options.
void collectFromAllJavaScriptParents(const F &&f, const QQmlJSScope::ConstPtr &scope)
static const QQmlJSScope * resolve(const QQmlJSScope *current, const QStringList &names)
static void collectLabels(const DomItem &context, QQmlLSCompletion::BackInsertIterator result)
static bool testScopeSymbol(const QQmlJSScope::ConstPtr &scope, LocalSymbolsTypes options, CompletionItemKind kind)